UNPKG

1.68 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 3.20.2
10 * @date 2018-02-07
11 *
12 * @license
13 * Copyright (C) 2013-2018 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 * http://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})(typeof self !== 'undefined' ? self : 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, {
77/******/ configurable: false,
78/******/ enumerable: true,
79/******/ get: getter
80/******/ });
81/******/ }
82/******/ };
83/******/
84/******/ // getDefaultExport function for compatibility with non-harmony modules
85/******/ __webpack_require__.n = function(module) {
86/******/ var getter = module && module.__esModule ?
87/******/ function getDefault() { return module['default']; } :
88/******/ function getModuleExports() { return module; };
89/******/ __webpack_require__.d(getter, 'a', getter);
90/******/ return getter;
91/******/ };
92/******/
93/******/ // Object.prototype.hasOwnProperty.call
94/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
95/******/
96/******/ // __webpack_public_path__
97/******/ __webpack_require__.p = "";
98/******/
99/******/ // Load entry module and return exports
100/******/ return __webpack_require__(__webpack_require__.s = 151);
101/******/ })
102/************************************************************************/
103/******/ ([
104/* 0 */
105/***/ (function(module, exports, __webpack_require__) {
106
107"use strict";
108
109
110function factory (type, config, load, typed) {
111 /**
112 * Create a Matrix. The function creates a new `math.type.Matrix` object from
113 * an `Array`. A Matrix has utility functions to manipulate the data in the
114 * matrix, like getting the size and getting or setting values in the matrix.
115 * Supported storage formats are 'dense' and 'sparse'.
116 *
117 * Syntax:
118 *
119 * math.matrix() // creates an empty matrix using default storage format (dense).
120 * math.matrix(data) // creates a matrix with initial data using default storage format (dense).
121 * math.matrix('dense') // creates an empty matrix using the given storage format.
122 * math.matrix(data, 'dense') // creates a matrix with initial data using the given storage format.
123 * math.matrix(data, 'sparse') // creates a sparse matrix with initial data.
124 * math.matrix(data, 'sparse', 'number') // creates a sparse matrix with initial data, number data type.
125 *
126 * Examples:
127 *
128 * var m = math.matrix([[1, 2], [3, 4]]);
129 * m.size(); // Array [2, 2]
130 * m.resize([3, 2], 5);
131 * m.valueOf(); // Array [[1, 2], [3, 4], [5, 5]]
132 * m.get([1, 0]) // number 3
133 *
134 * See also:
135 *
136 * bignumber, boolean, complex, index, number, string, unit, sparse
137 *
138 * @param {Array | Matrix} [data] A multi dimensional array
139 * @param {string} [format] The Matrix storage format
140 *
141 * @return {Matrix} The created matrix
142 */
143 var matrix = typed('matrix', {
144 '': function () {
145 return _create([]);
146 },
147
148 'string': function (format) {
149 return _create([], format);
150 },
151
152 'string, string': function (format, datatype) {
153 return _create([], format, datatype);
154 },
155
156 'Array': function (data) {
157 return _create(data);
158 },
159
160 'Matrix': function (data) {
161 return _create(data, data.storage());
162 },
163
164 'Array | Matrix, string': _create,
165
166 'Array | Matrix, string, string': _create
167 });
168
169 matrix.toTex = {
170 0: '\\begin{bmatrix}\\end{bmatrix}',
171 1: '\\left(${args[0]}\\right)',
172 2: '\\left(${args[0]}\\right)'
173 };
174
175 return matrix;
176
177 /**
178 * Create a new Matrix with given storage format
179 * @param {Array} data
180 * @param {string} [format]
181 * @param {string} [datatype]
182 * @returns {Matrix} Returns a new Matrix
183 * @private
184 */
185 function _create(data, format, datatype) {
186 // get storage format constructor
187 var M = type.Matrix.storage(format || 'default');
188
189 // create instance
190 return new M(data, datatype);
191 }
192}
193
194exports.name = 'matrix';
195exports.factory = factory;
196
197
198/***/ }),
199/* 1 */
200/***/ (function(module, exports, __webpack_require__) {
201
202"use strict";
203
204
205/**
206 * Execute the callback function element wise for each element in array and any
207 * nested array
208 * Returns an array with the results
209 * @param {Array | Matrix} array
210 * @param {Function} callback The callback is called with two parameters:
211 * value1 and value2, which contain the current
212 * element of both arrays.
213 * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.
214 *
215 * @return {Array | Matrix} res
216 */
217module.exports = function deepMap(array, callback, skipZeros) {
218 if (array && (typeof array.map === 'function')) {
219 // TODO: replace array.map with a for loop to improve performance
220 return array.map(function (x) {
221 return deepMap(x, callback, skipZeros);
222 });
223 }
224 else {
225 return callback(array);
226 }
227};
228
229
230/***/ }),
231/* 2 */
232/***/ (function(module, exports, __webpack_require__) {
233
234"use strict";
235
236
237var number = __webpack_require__(3);
238var string = __webpack_require__(9);
239var object = __webpack_require__(5);
240var types = __webpack_require__(60);
241
242var DimensionError = __webpack_require__(11);
243var IndexError = __webpack_require__(53);
244
245/**
246 * Calculate the size of a multi dimensional array.
247 * This function checks the size of the first entry, it does not validate
248 * whether all dimensions match. (use function `validate` for that)
249 * @param {Array} x
250 * @Return {Number[]} size
251 */
252exports.size = function (x) {
253 var s = [];
254
255 while (Array.isArray(x)) {
256 s.push(x.length);
257 x = x[0];
258 }
259
260 return s;
261};
262
263/**
264 * Recursively validate whether each element in a multi dimensional array
265 * has a size corresponding to the provided size array.
266 * @param {Array} array Array to be validated
267 * @param {number[]} size Array with the size of each dimension
268 * @param {number} dim Current dimension
269 * @throws DimensionError
270 * @private
271 */
272function _validate(array, size, dim) {
273 var i;
274 var len = array.length;
275
276 if (len != size[dim]) {
277 throw new DimensionError(len, size[dim]);
278 }
279
280 if (dim < size.length - 1) {
281 // recursively validate each child array
282 var dimNext = dim + 1;
283 for (i = 0; i < len; i++) {
284 var child = array[i];
285 if (!Array.isArray(child)) {
286 throw new DimensionError(size.length - 1, size.length, '<');
287 }
288 _validate(array[i], size, dimNext);
289 }
290 }
291 else {
292 // last dimension. none of the childs may be an array
293 for (i = 0; i < len; i++) {
294 if (Array.isArray(array[i])) {
295 throw new DimensionError(size.length + 1, size.length, '>');
296 }
297 }
298 }
299}
300
301/**
302 * Validate whether each element in a multi dimensional array has
303 * a size corresponding to the provided size array.
304 * @param {Array} array Array to be validated
305 * @param {number[]} size Array with the size of each dimension
306 * @throws DimensionError
307 */
308exports.validate = function(array, size) {
309 var isScalar = (size.length == 0);
310 if (isScalar) {
311 // scalar
312 if (Array.isArray(array)) {
313 throw new DimensionError(array.length, 0);
314 }
315 }
316 else {
317 // array
318 _validate(array, size, 0);
319 }
320};
321
322/**
323 * Test whether index is an integer number with index >= 0 and index < length
324 * when length is provided
325 * @param {number} index Zero-based index
326 * @param {number} [length] Length of the array
327 */
328exports.validateIndex = function(index, length) {
329 if (!number.isNumber(index) || !number.isInteger(index)) {
330 throw new TypeError('Index must be an integer (value: ' + index + ')');
331 }
332 if (index < 0 || (typeof length === 'number' && index >= length)) {
333 throw new IndexError(index, length);
334 }
335};
336
337// a constant used to specify an undefined defaultValue
338exports.UNINITIALIZED = {};
339
340/**
341 * Resize a multi dimensional array. The resized array is returned.
342 * @param {Array} array Array to be resized
343 * @param {Array.<number>} size Array with the size of each dimension
344 * @param {*} [defaultValue=0] Value to be filled in in new entries,
345 * zero by default. To leave new entries undefined,
346 * specify array.UNINITIALIZED as defaultValue
347 * @return {Array} array The resized array
348 */
349exports.resize = function(array, size, defaultValue) {
350 // TODO: add support for scalars, having size=[] ?
351
352 // check the type of the arguments
353 if (!Array.isArray(array) || !Array.isArray(size)) {
354 throw new TypeError('Array expected');
355 }
356 if (size.length === 0) {
357 throw new Error('Resizing to scalar is not supported');
358 }
359
360 // check whether size contains positive integers
361 size.forEach(function (value) {
362 if (!number.isNumber(value) || !number.isInteger(value) || value < 0) {
363 throw new TypeError('Invalid size, must contain positive integers ' +
364 '(size: ' + string.format(size) + ')');
365 }
366 });
367
368 // recursively resize the array
369 var _defaultValue = (defaultValue !== undefined) ? defaultValue : 0;
370 _resize(array, size, 0, _defaultValue);
371
372 return array;
373};
374
375/**
376 * Recursively resize a multi dimensional array
377 * @param {Array} array Array to be resized
378 * @param {number[]} size Array with the size of each dimension
379 * @param {number} dim Current dimension
380 * @param {*} [defaultValue] Value to be filled in in new entries,
381 * undefined by default.
382 * @private
383 */
384function _resize (array, size, dim, defaultValue) {
385 var i;
386 var elem;
387 var oldLen = array.length;
388 var newLen = size[dim];
389 var minLen = Math.min(oldLen, newLen);
390
391 // apply new length
392 array.length = newLen;
393
394 if (dim < size.length - 1) {
395 // non-last dimension
396 var dimNext = dim + 1;
397
398 // resize existing child arrays
399 for (i = 0; i < minLen; i++) {
400 // resize child array
401 elem = array[i];
402 if (!Array.isArray(elem)) {
403 elem = [elem]; // add a dimension
404 array[i] = elem;
405 }
406 _resize(elem, size, dimNext, defaultValue);
407 }
408
409 // create new child arrays
410 for (i = minLen; i < newLen; i++) {
411 // get child array
412 elem = [];
413 array[i] = elem;
414
415 // resize new child array
416 _resize(elem, size, dimNext, defaultValue);
417 }
418 }
419 else {
420 // last dimension
421
422 // remove dimensions of existing values
423 for (i = 0; i < minLen; i++) {
424 while (Array.isArray(array[i])) {
425 array[i] = array[i][0];
426 }
427 }
428
429 if(defaultValue !== exports.UNINITIALIZED) {
430 // fill new elements with the default value
431 for (i = minLen; i < newLen; i++) {
432 array[i] = defaultValue;
433 }
434 }
435 }
436}
437
438/**
439 * Re-shape a multi dimensional array to fit the specified dimensions
440 * @param {Array} array Array to be reshaped
441 * @param {Array.<number>} sizes List of sizes for each dimension
442 * @returns {Array} Array whose data has been formatted to fit the
443 * specified dimensions
444 *
445 * @throws {DimensionError} If the product of the new dimension sizes does
446 * not equal that of the old ones
447 */
448exports.reshape = function(array, sizes) {
449 var flatArray = exports.flatten(array);
450 var newArray;
451
452 var product = function (arr) {
453 return arr.reduce(function (prev, curr) {
454 return prev * curr;
455 });
456 };
457
458 if (!Array.isArray(array) || !Array.isArray(sizes)) {
459 throw new TypeError('Array expected');
460 }
461
462 if (sizes.length === 0) {
463 throw new DimensionError(0, product(exports.size(array)), '!=');
464 }
465
466 try {
467 newArray = _reshape(flatArray, sizes);
468 } catch (e) {
469 if (e instanceof DimensionError) {
470 throw new DimensionError(
471 product(sizes),
472 product(exports.size(array)),
473 '!='
474 );
475 }
476 throw e;
477 }
478
479 if (flatArray.length > 0) {
480 throw new DimensionError(
481 product(sizes),
482 product(exports.size(array)),
483 '!='
484 );
485 }
486
487 return newArray;
488};
489
490/**
491 * Recursively re-shape a multi dimensional array to fit the specified dimensions
492 * @param {Array} array Array to be reshaped
493 * @param {Array.<number>} sizes List of sizes for each dimension
494 * @returns {Array} Array whose data has been formatted to fit the
495 * specified dimensions
496 *
497 * @throws {DimensionError} If the product of the new dimension sizes does
498 * not equal that of the old ones
499 */
500function _reshape(array, sizes) {
501 var accumulator = [];
502 var i;
503
504 if (sizes.length === 0) {
505 if (array.length === 0) {
506 throw new DimensionError(null, null, '!=');
507 }
508 return array.shift();
509 }
510 for (i = 0; i < sizes[0]; i += 1) {
511 accumulator.push(_reshape(array, sizes.slice(1)));
512 }
513 return accumulator;
514}
515
516
517/**
518 * Squeeze a multi dimensional array
519 * @param {Array} array
520 * @param {Array} [size]
521 * @returns {Array} returns the array itself
522 */
523exports.squeeze = function(array, size) {
524 var s = size || exports.size(array);
525
526 // squeeze outer dimensions
527 while (Array.isArray(array) && array.length === 1) {
528 array = array[0];
529 s.shift();
530 }
531
532 // find the first dimension to be squeezed
533 var dims = s.length;
534 while (s[dims - 1] === 1) {
535 dims--;
536 }
537
538 // squeeze inner dimensions
539 if (dims < s.length) {
540 array = _squeeze(array, dims, 0);
541 s.length = dims;
542 }
543
544 return array;
545};
546
547/**
548 * Recursively squeeze a multi dimensional array
549 * @param {Array} array
550 * @param {number} dims Required number of dimensions
551 * @param {number} dim Current dimension
552 * @returns {Array | *} Returns the squeezed array
553 * @private
554 */
555function _squeeze (array, dims, dim) {
556 var i, ii;
557
558 if (dim < dims) {
559 var next = dim + 1;
560 for (i = 0, ii = array.length; i < ii; i++) {
561 array[i] = _squeeze(array[i], dims, next);
562 }
563 }
564 else {
565 while (Array.isArray(array)) {
566 array = array[0];
567 }
568 }
569
570 return array;
571}
572
573/**
574 * Unsqueeze a multi dimensional array: add dimensions when missing
575 *
576 * Paramter `size` will be mutated to match the new, unqueezed matrix size.
577 *
578 * @param {Array} array
579 * @param {number} dims Desired number of dimensions of the array
580 * @param {number} [outer] Number of outer dimensions to be added
581 * @param {Array} [size] Current size of array.
582 * @returns {Array} returns the array itself
583 * @private
584 */
585exports.unsqueeze = function(array, dims, outer, size) {
586 var s = size || exports.size(array);
587
588 // unsqueeze outer dimensions
589 if (outer) {
590 for (var i = 0; i < outer; i++) {
591 array = [array];
592 s.unshift(1);
593 }
594 }
595
596 // unsqueeze inner dimensions
597 array = _unsqueeze(array, dims, 0);
598 while (s.length < dims) {
599 s.push(1);
600 }
601
602 return array;
603};
604
605/**
606 * Recursively unsqueeze a multi dimensional array
607 * @param {Array} array
608 * @param {number} dims Required number of dimensions
609 * @param {number} dim Current dimension
610 * @returns {Array | *} Returns the squeezed array
611 * @private
612 */
613function _unsqueeze (array, dims, dim) {
614 var i, ii;
615
616 if (Array.isArray(array)) {
617 var next = dim + 1;
618 for (i = 0, ii = array.length; i < ii; i++) {
619 array[i] = _unsqueeze(array[i], dims, next);
620 }
621 }
622 else {
623 for (var d = dim; d < dims; d++) {
624 array = [array];
625 }
626 }
627
628 return array;
629}
630/**
631 * Flatten a multi dimensional array, put all elements in a one dimensional
632 * array
633 * @param {Array} array A multi dimensional array
634 * @return {Array} The flattened array (1 dimensional)
635 */
636exports.flatten = function(array) {
637 if (!Array.isArray(array)) {
638 //if not an array, return as is
639 return array;
640 }
641 var flat = [];
642
643 array.forEach(function callback(value) {
644 if (Array.isArray(value)) {
645 value.forEach(callback); //traverse through sub-arrays recursively
646 }
647 else {
648 flat.push(value);
649 }
650 });
651
652 return flat;
653};
654
655/**
656 * A safe map
657 * @param {Array} array
658 * @param {function} callback
659 */
660exports.map = function (array, callback) {
661 return Array.prototype.map.call(array, callback);
662}
663
664/**
665 * A safe forEach
666 * @param {Array} array
667 * @param {function} callback
668 */
669exports.forEach = function (array, callback) {
670 Array.prototype.forEach.call(array, callback);
671}
672
673/**
674 * A safe filter
675 * @param {Array} array
676 * @param {function} callback
677 */
678exports.filter = function (array, callback) {
679 if (exports.size(array).length !== 1) {
680 throw new Error('Only one dimensional matrices supported');
681 }
682
683 return Array.prototype.filter.call(array, callback);
684}
685
686/**
687 * Filter values in a callback given a regular expression
688 * @param {Array} array
689 * @param {RegExp} regexp
690 * @return {Array} Returns the filtered array
691 * @private
692 */
693exports.filterRegExp = function (array, regexp) {
694 if (exports.size(array).length !== 1) {
695 throw new Error('Only one dimensional matrices supported');
696 }
697
698 return Array.prototype.filter.call(array, function (entry) {
699 return regexp.test(entry);
700 });
701}
702
703/**
704 * A safe join
705 * @param {Array} array
706 * @param {string} separator
707 */
708exports.join = function (array, separator) {
709 return Array.prototype.join.call(array, separator);
710}
711
712/**
713 * Assign a numeric identifier to every element of a sorted array
714 * @param {Array} a An array
715 * @return {Array} An array of objects containing the original value and its identifier
716 */
717exports.identify = function(a) {
718 if (!Array.isArray(a)) {
719 throw new TypeError('Array input expected');
720 }
721
722 if (a.length === 0) {
723 return a;
724 }
725
726 var b = [];
727 var count = 0;
728 b[0] = {value: a[0], identifier: 0};
729 for (var i=1; i<a.length; i++) {
730 if (a[i] === a[i-1]) {
731 count++;
732 }
733 else {
734 count = 0;
735 }
736 b.push({value: a[i], identifier: count});
737 }
738 return b;
739}
740
741/**
742 * Remove the numeric identifier from the elements
743 * @param a An array
744 * @return An array of values without identifiers
745 */
746exports.generalize = function(a) {
747 if (!Array.isArray(a)) {
748 throw new TypeError('Array input expected');
749 }
750
751 if (a.length === 0) {
752 return a;
753 }
754
755 var b = [];
756 for (var i=0; i<a.length; i++) {
757 b.push(a[i].value);
758 }
759 return b;
760}
761
762/**
763 * Test whether an object is an array
764 * @param {*} value
765 * @return {boolean} isArray
766 */
767exports.isArray = Array.isArray;
768
769
770/***/ }),
771/* 3 */
772/***/ (function(module, exports, __webpack_require__) {
773
774"use strict";
775
776
777/**
778 * @typedef {{sign: '+' | '-' | '', coefficients: number[], exponent: number}} SplitValue
779 */
780
781/**
782 * Test whether value is a number
783 * @param {*} value
784 * @return {boolean} isNumber
785 */
786exports.isNumber = function(value) {
787 return typeof value === 'number';
788};
789
790/**
791 * Check if a number is integer
792 * @param {number | boolean} value
793 * @return {boolean} isInteger
794 */
795exports.isInteger = function(value) {
796 return isFinite(value)
797 ? (value == Math.round(value))
798 : false;
799 // Note: we use ==, not ===, as we can have Booleans as well
800};
801
802/**
803 * Calculate the sign of a number
804 * @param {number} x
805 * @returns {*}
806 */
807exports.sign = Math.sign || function(x) {
808 if (x > 0) {
809 return 1;
810 }
811 else if (x < 0) {
812 return -1;
813 }
814 else {
815 return 0;
816 }
817};
818
819/**
820 * Convert a number to a formatted string representation.
821 *
822 * Syntax:
823 *
824 * format(value)
825 * format(value, options)
826 * format(value, precision)
827 * format(value, fn)
828 *
829 * Where:
830 *
831 * {number} value The value to be formatted
832 * {Object} options An object with formatting options. Available options:
833 * {string} notation
834 * Number notation. Choose from:
835 * 'fixed' Always use regular number notation.
836 * For example '123.40' and '14000000'
837 * 'exponential' Always use exponential notation.
838 * For example '1.234e+2' and '1.4e+7'
839 * 'engineering' Always use engineering notation.
840 * For example '123.4e+0' and '14.0e+6'
841 * 'auto' (default) Regular number notation for numbers
842 * having an absolute value between
843 * `lower` and `upper` bounds, and uses
844 * exponential notation elsewhere.
845 * Lower bound is included, upper bound
846 * is excluded.
847 * For example '123.4' and '1.4e7'.
848 * {number} precision A number between 0 and 16 to round
849 * the digits of the number.
850 * In case of notations 'exponential' and
851 * 'auto', `precision` defines the total
852 * number of significant digits returned
853 * and is undefined by default.
854 * In case of notation 'fixed',
855 * `precision` defines the number of
856 * significant digits after the decimal
857 * point, and is 0 by default.
858 * {Object} exponential An object containing two parameters,
859 * {number} lower and {number} upper,
860 * used by notation 'auto' to determine
861 * when to return exponential notation.
862 * Default values are `lower=1e-3` and
863 * `upper=1e5`.
864 * Only applicable for notation `auto`.
865 * {Function} fn A custom formatting function. Can be used to override the
866 * built-in notations. Function `fn` is called with `value` as
867 * parameter and must return a string. Is useful for example to
868 * format all values inside a matrix in a particular way.
869 *
870 * Examples:
871 *
872 * format(6.4); // '6.4'
873 * format(1240000); // '1.24e6'
874 * format(1/3); // '0.3333333333333333'
875 * format(1/3, 3); // '0.333'
876 * format(21385, 2); // '21000'
877 * format(12.071, {notation: 'fixed'}); // '12'
878 * format(2.3, {notation: 'fixed', precision: 2}); // '2.30'
879 * format(52.8, {notation: 'exponential'}); // '5.28e+1'
880 * format(12345678, {notation: 'engineering'}); // '12.345678e+6'
881 *
882 * @param {number} value
883 * @param {Object | Function | number} [options]
884 * @return {string} str The formatted value
885 */
886exports.format = function(value, options) {
887 if (typeof options === 'function') {
888 // handle format(value, fn)
889 return options(value);
890 }
891
892 // handle special cases
893 if (value === Infinity) {
894 return 'Infinity';
895 }
896 else if (value === -Infinity) {
897 return '-Infinity';
898 }
899 else if (isNaN(value)) {
900 return 'NaN';
901 }
902
903 // default values for options
904 var notation = 'auto';
905 var precision = undefined;
906
907 if (options) {
908 // determine notation from options
909 if (options.notation) {
910 notation = options.notation;
911 }
912
913 // determine precision from options
914 if (exports.isNumber(options)) {
915 precision = options;
916 }
917 else if (options.precision) {
918 precision = options.precision;
919 }
920 }
921
922 // handle the various notations
923 switch (notation) {
924 case 'fixed':
925 return exports.toFixed(value, precision);
926
927 case 'exponential':
928 return exports.toExponential(value, precision);
929
930 case 'engineering':
931 return exports.toEngineering(value, precision);
932
933 case 'auto':
934 return exports
935 .toPrecision(value, precision, options && options.exponential)
936
937 // remove trailing zeros after the decimal point
938 .replace(/((\.\d*?)(0+))($|e)/, function () {
939 var digits = arguments[2];
940 var e = arguments[4];
941 return (digits !== '.') ? digits + e : e;
942 });
943
944 default:
945 throw new Error('Unknown notation "' + notation + '". ' +
946 'Choose "auto", "exponential", or "fixed".');
947 }
948};
949
950/**
951 * Split a number into sign, coefficients, and exponent
952 * @param {number | string} value
953 * @return {SplitValue}
954 * Returns an object containing sign, coefficients, and exponent
955 */
956exports.splitNumber = function (value) {
957 // parse the input value
958 var match = String(value).toLowerCase().match(/^0*?(-?)(\d+\.?\d*)(e([+-]?\d+))?$/);
959 if (!match) {
960 throw new SyntaxError('Invalid number ' + value);
961 }
962
963 var sign = match[1];
964 var digits = match[2];
965 var exponent = parseFloat(match[4] || '0');
966
967 var dot = digits.indexOf('.');
968 exponent += (dot !== -1) ? (dot - 1) : (digits.length - 1);
969
970 var coefficients = digits
971 .replace('.', '') // remove the dot (must be removed before removing leading zeros)
972 .replace(/^0*/, function (zeros) {
973 // remove leading zeros, add their count to the exponent
974 exponent -= zeros.length;
975 return '';
976 })
977 .replace(/0*$/, '') // remove trailing zeros
978 .split('')
979 .map(function (d) {
980 return parseInt(d);
981 });
982
983 if (coefficients.length === 0) {
984 coefficients.push(0);
985 exponent++;
986 }
987
988 return {
989 sign: sign,
990 coefficients: coefficients,
991 exponent: exponent
992 };
993};
994
995
996/**
997 * Format a number in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3'
998 * @param {number | string} value
999 * @param {number} [precision=0] Optional number of decimals after the
1000 * decimal point. Zero by default.
1001 */
1002exports.toEngineering = function (value, precision) {
1003 if (isNaN(value) || !isFinite(value)) {
1004 return String(value);
1005 }
1006
1007 var rounded = exports.roundDigits(exports.splitNumber(value), precision);
1008
1009 var e = rounded.exponent;
1010 var c = rounded.coefficients;
1011
1012 // find nearest lower multiple of 3 for exponent
1013 var newExp = e % 3 === 0 ? e : (e < 0 ? (e - 3) - (e % 3) : e - (e % 3));
1014
1015 // concatenate coefficients with necessary zeros
1016 var significandsDiff = e >= 0 ? e : Math.abs(newExp);
1017
1018 // add zeros if necessary (for ex: 1e+8)
1019 if (c.length - 1 < significandsDiff) c = c.concat(zeros(significandsDiff - (c.length - 1)));
1020
1021 // find difference in exponents
1022 var expDiff = Math.abs(e - newExp);
1023
1024 var decimalIdx = 1;
1025
1026 // push decimal index over by expDiff times
1027 while (--expDiff >= 0) decimalIdx++;
1028
1029 // if all coefficient values are zero after the decimal point, don't add a decimal value.
1030 // otherwise concat with the rest of the coefficients
1031 var decimals = c.slice(decimalIdx).join('');
1032 var decimalVal = decimals.match(/[1-9]/) ? ('.' + decimals) : '';
1033
1034 var str = c.slice(0, decimalIdx).join('') +
1035 decimalVal +
1036 'e' + (e >= 0 ? '+' : '') + newExp.toString();
1037 return rounded.sign + str;
1038};
1039
1040/**
1041 * Format a number with fixed notation.
1042 * @param {number | string} value
1043 * @param {number} [precision=0] Optional number of decimals after the
1044 * decimal point. Zero by default.
1045 */
1046exports.toFixed = function (value, precision) {
1047 if (isNaN(value) || !isFinite(value)) {
1048 return String(value);
1049 }
1050
1051 var splitValue = exports.splitNumber(value)
1052 var rounded = exports.roundDigits(splitValue, splitValue.exponent + 1 + (precision || 0));
1053 var c = rounded.coefficients;
1054 var p = rounded.exponent + 1; // exponent may have changed
1055
1056 // append zeros if needed
1057 var pp = p + (precision || 0);
1058 if (c.length < pp) {
1059 c = c.concat(zeros(pp - c.length));
1060 }
1061
1062 // prepend zeros if needed
1063 if (p < 0) {
1064 c = zeros(-p + 1).concat(c);
1065 p = 1;
1066 }
1067
1068 // insert a dot if needed
1069 if (precision) {
1070 c.splice(p, 0, (p === 0) ? '0.' : '.');
1071 }
1072
1073 return rounded.sign + c.join('');
1074};
1075
1076/**
1077 * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3'
1078 * @param {number | string} value
1079 * @param {number} [precision] Number of digits in formatted output.
1080 * If not provided, the maximum available digits
1081 * is used.
1082 */
1083exports.toExponential = function (value, precision) {
1084 if (isNaN(value) || !isFinite(value)) {
1085 return String(value);
1086 }
1087
1088 // round if needed, else create a clone
1089 var split = exports.splitNumber(value)
1090 var rounded = precision ? exports.roundDigits(split, precision) : split;
1091 var c = rounded.coefficients;
1092 var e = rounded.exponent;
1093
1094 // append zeros if needed
1095 if (c.length < precision) {
1096 c = c.concat(zeros(precision - c.length));
1097 }
1098
1099 // format as `C.CCCe+EEE` or `C.CCCe-EEE`
1100 var first = c.shift();
1101 return rounded.sign + first + (c.length > 0 ? ('.' + c.join('')) : '') +
1102 'e' + (e >= 0 ? '+' : '') + e;
1103}
1104
1105/**
1106 * Format a number with a certain precision
1107 * @param {number | string} value
1108 * @param {number} [precision=undefined] Optional number of digits.
1109 * @param {{lower: number | undefined, upper: number | undefined}} [options]
1110 * By default:
1111 * lower = 1e-3 (excl)
1112 * upper = 1e+5 (incl)
1113 * @return {string}
1114 */
1115exports.toPrecision = function (value, precision, options) {
1116 if (isNaN(value) || !isFinite(value)) {
1117 return String(value);
1118 }
1119
1120 // determine lower and upper bound for exponential notation.
1121 var lower = (options && options.lower !== undefined) ? options.lower : 1e-3;
1122 var upper = (options && options.upper !== undefined) ? options.upper : 1e+5;
1123
1124 var split = exports.splitNumber(value)
1125 var abs = Math.abs(Math.pow(10, split.exponent));
1126 if (abs < lower || abs >= upper) {
1127 // exponential notation
1128 return exports.toExponential(value, precision);
1129 }
1130 else {
1131 var rounded = precision ? exports.roundDigits(split, precision) : split;
1132 var c = rounded.coefficients;
1133 var e = rounded.exponent;
1134
1135 // append trailing zeros
1136 if (c.length < precision) {
1137 c = c.concat(zeros(precision - c.length));
1138 }
1139
1140 // append trailing zeros
1141 // TODO: simplify the next statement
1142 c = c.concat(zeros(e - c.length + 1 +
1143 (c.length < precision ? precision - c.length : 0)));
1144
1145 // prepend zeros
1146 c = zeros(-e).concat(c);
1147
1148 var dot = e > 0 ? e : 0;
1149 if (dot < c.length - 1) {
1150 c.splice(dot + 1, 0, '.');
1151 }
1152
1153 return rounded.sign + c.join('');
1154 }
1155}
1156
1157/**
1158 * Round the number of digits of a number *
1159 * @param {SplitValue} split A value split with .splitNumber(value)
1160 * @param {number} precision A positive integer
1161 * @return {SplitValue}
1162 * Returns an object containing sign, coefficients, and exponent
1163 * with rounded digits
1164 */
1165exports.roundDigits = function (split, precision) {
1166 // create a clone
1167 var rounded = {
1168 sign: split.sign,
1169 coefficients: split.coefficients,
1170 exponent: split.exponent
1171 }
1172 var c = rounded.coefficients;
1173
1174 // prepend zeros if needed
1175 while (precision <= 0) {
1176 c.unshift(0);
1177 rounded.exponent++;
1178 precision++;
1179 }
1180
1181 if (c.length > precision) {
1182 var removed = c.splice(precision, c.length - precision);
1183
1184 if (removed[0] >= 5) {
1185 var i = precision - 1;
1186 c[i]++;
1187 while (c[i] === 10) {
1188 c.pop();
1189 if (i === 0) {
1190 c.unshift(0);
1191 rounded.exponent++;
1192 i++;
1193 }
1194 i--;
1195 c[i]++;
1196 }
1197 }
1198 }
1199
1200 return rounded;
1201};
1202
1203/**
1204 * Create an array filled with zeros.
1205 * @param {number} length
1206 * @return {Array}
1207 */
1208function zeros(length) {
1209 var arr = [];
1210 for (var i = 0; i < length; i++) {
1211 arr.push(0);
1212 }
1213 return arr;
1214}
1215
1216/**
1217 * Count the number of significant digits of a number.
1218 *
1219 * For example:
1220 * 2.34 returns 3
1221 * 0.0034 returns 2
1222 * 120.5e+30 returns 4
1223 *
1224 * @param {number} value
1225 * @return {number} digits Number of significant digits
1226 */
1227exports.digits = function(value) {
1228 return value
1229 .toExponential()
1230 .replace(/e.*$/, '') // remove exponential notation
1231 .replace( /^0\.?0*|\./, '') // remove decimal point and leading zeros
1232 .length
1233};
1234
1235/**
1236 * Minimum number added to one that makes the result different than one
1237 */
1238exports.DBL_EPSILON = Number.EPSILON || 2.2204460492503130808472633361816E-16;
1239
1240/**
1241 * Compares two floating point numbers.
1242 * @param {number} x First value to compare
1243 * @param {number} y Second value to compare
1244 * @param {number} [epsilon] The maximum relative difference between x and y
1245 * If epsilon is undefined or null, the function will
1246 * test whether x and y are exactly equal.
1247 * @return {boolean} whether the two numbers are nearly equal
1248*/
1249exports.nearlyEqual = function(x, y, epsilon) {
1250 // if epsilon is null or undefined, test whether x and y are exactly equal
1251 if (epsilon == null) {
1252 return x == y;
1253 }
1254
1255 // use "==" operator, handles infinities
1256 if (x == y) {
1257 return true;
1258 }
1259
1260 // NaN
1261 if (isNaN(x) || isNaN(y)) {
1262 return false;
1263 }
1264
1265 // at this point x and y should be finite
1266 if(isFinite(x) && isFinite(y)) {
1267 // check numbers are very close, needed when comparing numbers near zero
1268 var diff = Math.abs(x - y);
1269 if (diff < exports.DBL_EPSILON) {
1270 return true;
1271 }
1272 else {
1273 // use relative error
1274 return diff <= Math.max(Math.abs(x), Math.abs(y)) * epsilon;
1275 }
1276 }
1277
1278 // Infinite and Number or negative Infinite and positive Infinite cases
1279 return false;
1280};
1281
1282
1283/***/ }),
1284/* 4 */
1285/***/ (function(module, exports, __webpack_require__) {
1286
1287"use strict";
1288
1289
1290var escape_latex = __webpack_require__(173)
1291
1292exports.symbols = {
1293 // GREEK LETTERS
1294 Alpha: 'A', alpha: '\\alpha',
1295 Beta: 'B', beta: '\\beta',
1296 Gamma: '\\Gamma', gamma: '\\gamma',
1297 Delta: '\\Delta', delta: '\\delta',
1298 Epsilon: 'E', epsilon: '\\epsilon', varepsilon: '\\varepsilon',
1299 Zeta: 'Z', zeta: '\\zeta',
1300 Eta: 'H', eta: '\\eta',
1301 Theta: '\\Theta', theta: '\\theta', vartheta: '\\vartheta',
1302 Iota: 'I', iota: '\\iota',
1303 Kappa: 'K', kappa: '\\kappa', varkappa: '\\varkappa',
1304 Lambda: '\\Lambda', lambda: '\\lambda',
1305 Mu: 'M', mu: '\\mu',
1306 Nu: 'N', nu: '\\nu',
1307 Xi: '\\Xi', xi: '\\xi',
1308 Omicron: 'O', omicron: 'o',
1309 Pi: '\\Pi', pi: '\\pi', varpi: '\\varpi',
1310 Rho: 'P', rho: '\\rho', varrho: '\\varrho',
1311 Sigma: '\\Sigma', sigma: '\\sigma', varsigma: '\\varsigma',
1312 Tau: 'T', tau: '\\tau',
1313 Upsilon: '\\Upsilon', upsilon: '\\upsilon',
1314 Phi: '\\Phi', phi: '\\phi', varphi: '\\varphi',
1315 Chi: 'X', chi: '\\chi',
1316 Psi: '\\Psi', psi: '\\psi',
1317 Omega: '\\Omega', omega: '\\omega',
1318 //logic
1319 'true': '\\mathrm{True}',
1320 'false': '\\mathrm{False}',
1321 //other
1322 i: 'i', //TODO use \i ??
1323 inf: '\\infty',
1324 Inf: '\\infty',
1325 infinity: '\\infty',
1326 Infinity: '\\infty',
1327 oo: '\\infty',
1328 lim: '\\lim',
1329 'undefined': '\\mathbf{?}'
1330};
1331
1332exports.operators = {
1333 'transpose': '^\\top',
1334 'factorial': '!',
1335 'pow': '^',
1336 'dotPow': '.^\\wedge', //TODO find ideal solution
1337 'unaryPlus': '+',
1338 'unaryMinus': '-',
1339 'bitNot': '~', //TODO find ideal solution
1340 'not': '\\neg',
1341 'multiply': '\\cdot',
1342 'divide': '\\frac', //TODO how to handle that properly?
1343 'dotMultiply': '.\\cdot', //TODO find ideal solution
1344 'dotDivide': '.:', //TODO find ideal solution
1345 'mod': '\\mod',
1346 'add': '+',
1347 'subtract': '-',
1348 'to': '\\rightarrow',
1349 'leftShift': '<<',
1350 'rightArithShift': '>>',
1351 'rightLogShift': '>>>',
1352 'equal': '=',
1353 'unequal': '\\neq',
1354 'smaller': '<',
1355 'larger': '>',
1356 'smallerEq': '\\leq',
1357 'largerEq': '\\geq',
1358 'bitAnd': '\\&',
1359 'bitXor': '\\underline{|}',
1360 'bitOr': '|',
1361 'and': '\\wedge',
1362 'xor': '\\veebar',
1363 'or': '\\vee'
1364};
1365
1366exports.defaultTemplate = '\\mathrm{${name}}\\left(${args}\\right)';
1367
1368var units = {
1369 deg: '^\\circ'
1370};
1371
1372exports.escape = function (string) {
1373 return escape_latex(string, {'preserveFormatting': true});
1374}
1375
1376//@param {string} name
1377//@param {boolean} isUnit
1378exports.toSymbol = function (name, isUnit) {
1379 isUnit = typeof isUnit === 'undefined' ? false : isUnit;
1380 if (isUnit) {
1381 if (units.hasOwnProperty(name)) {
1382 return units[name];
1383 }
1384
1385 return '\\mathrm{' + exports.escape(name) + '}';
1386 }
1387
1388 if (exports.symbols.hasOwnProperty(name)) {
1389 return exports.symbols[name];
1390 }
1391
1392 return exports.escape(name);
1393};
1394
1395
1396/***/ }),
1397/* 5 */
1398/***/ (function(module, exports, __webpack_require__) {
1399
1400"use strict";
1401
1402
1403var isBigNumber = __webpack_require__(71);
1404
1405/**
1406 * Clone an object
1407 *
1408 * clone(x)
1409 *
1410 * Can clone any primitive type, array, and object.
1411 * If x has a function clone, this function will be invoked to clone the object.
1412 *
1413 * @param {*} x
1414 * @return {*} clone
1415 */
1416exports.clone = function clone(x) {
1417 var type = typeof x;
1418
1419 // immutable primitive types
1420 if (type === 'number' || type === 'string' || type === 'boolean' ||
1421 x === null || x === undefined) {
1422 return x;
1423 }
1424
1425 // use clone function of the object when available
1426 if (typeof x.clone === 'function') {
1427 return x.clone();
1428 }
1429
1430 // array
1431 if (Array.isArray(x)) {
1432 return x.map(function (value) {
1433 return clone(value);
1434 });
1435 }
1436
1437 if (x instanceof Number) return new Number(x.valueOf());
1438 if (x instanceof String) return new String(x.valueOf());
1439 if (x instanceof Boolean) return new Boolean(x.valueOf());
1440 if (x instanceof Date) return new Date(x.valueOf());
1441 if (isBigNumber(x)) return x; // bignumbers are immutable
1442 if (x instanceof RegExp) throw new TypeError('Cannot clone ' + x); // TODO: clone a RegExp
1443
1444 // object
1445 return exports.map(x, clone);
1446};
1447
1448/**
1449 * Apply map to all properties of an object
1450 * @param {Object} object
1451 * @param {function} callback
1452 * @return {Object} Returns a copy of the object with mapped properties
1453 */
1454exports.map = function(object, callback) {
1455 var clone = {};
1456
1457 for (var key in object) {
1458 if (exports.hasOwnProperty(object, key)) {
1459 clone[key] = callback(object[key]);
1460 }
1461 }
1462
1463 return clone;
1464}
1465
1466/**
1467 * Extend object a with the properties of object b
1468 * @param {Object} a
1469 * @param {Object} b
1470 * @return {Object} a
1471 */
1472exports.extend = function(a, b) {
1473 for (var prop in b) {
1474 if (exports.hasOwnProperty(b, prop)) {
1475 a[prop] = b[prop];
1476 }
1477 }
1478 return a;
1479};
1480
1481/**
1482 * Deep extend an object a with the properties of object b
1483 * @param {Object} a
1484 * @param {Object} b
1485 * @returns {Object}
1486 */
1487exports.deepExtend = function deepExtend (a, b) {
1488 // TODO: add support for Arrays to deepExtend
1489 if (Array.isArray(b)) {
1490 throw new TypeError('Arrays are not supported by deepExtend');
1491 }
1492
1493 for (var prop in b) {
1494 if (exports.hasOwnProperty(b, prop)) {
1495 if (b[prop] && b[prop].constructor === Object) {
1496 if (a[prop] === undefined) {
1497 a[prop] = {};
1498 }
1499 if (a[prop].constructor === Object) {
1500 deepExtend(a[prop], b[prop]);
1501 }
1502 else {
1503 a[prop] = b[prop];
1504 }
1505 } else if (Array.isArray(b[prop])) {
1506 throw new TypeError('Arrays are not supported by deepExtend');
1507 } else {
1508 a[prop] = b[prop];
1509 }
1510 }
1511 }
1512 return a;
1513};
1514
1515/**
1516 * Deep test equality of all fields in two pairs of arrays or objects.
1517 * @param {Array | Object} a
1518 * @param {Array | Object} b
1519 * @returns {boolean}
1520 */
1521exports.deepEqual = function deepEqual (a, b) {
1522 var prop, i, len;
1523 if (Array.isArray(a)) {
1524 if (!Array.isArray(b)) {
1525 return false;
1526 }
1527
1528 if (a.length != b.length) {
1529 return false;
1530 }
1531
1532 for (i = 0, len = a.length; i < len; i++) {
1533 if (!exports.deepEqual(a[i], b[i])) {
1534 return false;
1535 }
1536 }
1537 return true;
1538 }
1539 else if (a instanceof Object) {
1540 if (Array.isArray(b) || !(b instanceof Object)) {
1541 return false;
1542 }
1543
1544 for (prop in a) {
1545 //noinspection JSUnfilteredForInLoop
1546 if (!exports.deepEqual(a[prop], b[prop])) {
1547 return false;
1548 }
1549 }
1550 for (prop in b) {
1551 //noinspection JSUnfilteredForInLoop
1552 if (!exports.deepEqual(a[prop], b[prop])) {
1553 return false;
1554 }
1555 }
1556 return true;
1557 }
1558 else {
1559 return (typeof a === typeof b) && (a == b);
1560 }
1561};
1562
1563/**
1564 * Test whether the current JavaScript engine supports Object.defineProperty
1565 * @returns {boolean} returns true if supported
1566 */
1567exports.canDefineProperty = function () {
1568 // test needed for broken IE8 implementation
1569 try {
1570 if (Object.defineProperty) {
1571 Object.defineProperty({}, 'x', { get: function () {} });
1572 return true;
1573 }
1574 } catch (e) {}
1575
1576 return false;
1577};
1578
1579/**
1580 * Attach a lazy loading property to a constant.
1581 * The given function `fn` is called once when the property is first requested.
1582 * On older browsers (<IE8), the function will fall back to direct evaluation
1583 * of the properties value.
1584 * @param {Object} object Object where to add the property
1585 * @param {string} prop Property name
1586 * @param {Function} fn Function returning the property value. Called
1587 * without arguments.
1588 */
1589exports.lazy = function (object, prop, fn) {
1590 if (exports.canDefineProperty()) {
1591 var _uninitialized = true;
1592 var _value;
1593 Object.defineProperty(object, prop, {
1594 get: function () {
1595 if (_uninitialized) {
1596 _value = fn();
1597 _uninitialized = false;
1598 }
1599 return _value;
1600 },
1601
1602 set: function (value) {
1603 _value = value;
1604 _uninitialized = false;
1605 },
1606
1607 configurable: true,
1608 enumerable: true
1609 });
1610 }
1611 else {
1612 // fall back to immediate evaluation
1613 object[prop] = fn();
1614 }
1615};
1616
1617/**
1618 * Traverse a path into an object.
1619 * When a namespace is missing, it will be created
1620 * @param {Object} object
1621 * @param {string} path A dot separated string like 'name.space'
1622 * @return {Object} Returns the object at the end of the path
1623 */
1624exports.traverse = function(object, path) {
1625 var obj = object;
1626
1627 if (path) {
1628 var names = path.split('.');
1629 for (var i = 0; i < names.length; i++) {
1630 var name = names[i];
1631 if (!(name in obj)) {
1632 obj[name] = {};
1633 }
1634 obj = obj[name];
1635 }
1636 }
1637
1638 return obj;
1639};
1640
1641/**
1642 * A safe hasOwnProperty
1643 * @param {Object} object
1644 * @param {string} property
1645 */
1646exports.hasOwnProperty = function (object, property) {
1647 return object && Object.hasOwnProperty.call(object, property);
1648}
1649
1650/**
1651 * Test whether an object is a factory. a factory has fields:
1652 *
1653 * - factory: function (type: Object, config: Object, load: function, typed: function [, math: Object]) (required)
1654 * - name: string (optional)
1655 * - path: string A dot separated path (optional)
1656 * - math: boolean If true (false by default), the math namespace is passed
1657 * as fifth argument of the factory function
1658 *
1659 * @param {*} object
1660 * @returns {boolean}
1661 */
1662exports.isFactory = function (object) {
1663 return object && typeof object.factory === 'function';
1664};
1665
1666
1667/***/ }),
1668/* 6 */
1669/***/ (function(module, exports, __webpack_require__) {
1670
1671"use strict";
1672
1673
1674var clone = __webpack_require__(5).clone;
1675
1676function factory (type, config, load, typed) {
1677
1678 var DenseMatrix = type.DenseMatrix;
1679
1680 /**
1681 * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, b).
1682 * Callback function invoked MxN times.
1683 *
1684 * C(i,j,...z) = f(Aij..z, b)
1685 *
1686 * @param {Matrix} a The DenseMatrix instance (A)
1687 * @param {Scalar} b The Scalar value
1688 * @param {Function} callback The f(Aij..z,b) operation to invoke
1689 * @param {boolean} inverse A true value indicates callback should be invoked f(b,Aij..z)
1690 *
1691 * @return {Matrix} DenseMatrix (C)
1692 *
1693 * https://github.com/josdejong/mathjs/pull/346#issuecomment-97659042
1694 */
1695 var algorithm14 = function (a, b, callback, inverse) {
1696 // a arrays
1697 var adata = a._data;
1698 var asize = a._size;
1699 var adt = a._datatype;
1700
1701 // datatype
1702 var dt;
1703 // callback signature to use
1704 var cf = callback;
1705
1706 // process data types
1707 if (typeof adt === 'string') {
1708 // datatype
1709 dt = adt;
1710 // convert b to the same datatype
1711 b = typed.convert(b, dt);
1712 // callback
1713 cf = typed.find(callback, [dt, dt]);
1714 }
1715
1716 // populate cdata, iterate through dimensions
1717 var cdata = asize.length > 0 ? _iterate(cf, 0, asize, asize[0], adata, b, inverse) : [];
1718
1719 // c matrix
1720 return new DenseMatrix({
1721 data: cdata,
1722 size: clone(asize),
1723 datatype: dt
1724 });
1725 };
1726
1727 // recursive function
1728 var _iterate = function (f, level, s, n, av, bv, inverse) {
1729 // initialize array for this level
1730 var cv = [];
1731 // check we reach the last level
1732 if (level === s.length - 1) {
1733 // loop arrays in last level
1734 for (var i = 0; i < n; i++) {
1735 // invoke callback and store value
1736 cv[i] = inverse ? f(bv, av[i]) : f(av[i], bv);
1737 }
1738 }
1739 else {
1740 // iterate current level
1741 for (var j = 0; j < n; j++) {
1742 // iterate next level
1743 cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv, inverse);
1744 }
1745 }
1746 return cv;
1747 };
1748
1749 return algorithm14;
1750}
1751
1752exports.name = 'algorithm14';
1753exports.factory = factory;
1754
1755
1756/***/ }),
1757/* 7 */
1758/***/ (function(module, exports, __webpack_require__) {
1759
1760// the compile functions which compile a Node into JavaScript are not
1761// exposed as class methods for security reasons to prevent being able to
1762// override them or create fake Nodes. Instead, only compile functions of
1763// registered nodes can be executed
1764
1765var hasOwnProperty = __webpack_require__(5).hasOwnProperty;
1766
1767function factory () {
1768 // map with node type as key and compile functions as value
1769 var compileFunctions = {}
1770
1771 /**
1772 * Register a compile function for a node
1773 * @param {string} type
1774 * @param {function} compileFunction
1775 * The compile function, invoked as
1776 * compileFunction(node, defs, args)
1777 */
1778 function register(type, compileFunction) {
1779 if (compileFunctions[type] === undefined) {
1780 compileFunctions[type] = compileFunction;
1781 }
1782 else {
1783 throw new Error('Cannot register type "' + type + '": already exists');
1784 }
1785 }
1786
1787 /**
1788 * Compile a Node into JavaScript
1789 * @param {Node} node
1790 * @param {Object} defs Object which can be used to define functions
1791 * or constants globally available for the compiled
1792 * expression
1793 * @param {Object} args Object with local function arguments, the key is
1794 * the name of the argument, and the value is `true`.
1795 * The object may not be mutated, but must be
1796 * extended instead.
1797 * @return {string} Returns JavaScript code
1798 */
1799 function compile (node, defs, args) {
1800 if (hasOwnProperty(compileFunctions, node.type)) {
1801 var compileFunction = compileFunctions[node.type];
1802 return compileFunction(node, defs, args);
1803 }
1804 else if (typeof node._compile === 'function' &&
1805 !hasOwnProperty(node, '_compile')) {
1806 // Compatibility for CustomNodes
1807 // TODO: this is a security risk, change it such that you have to register CustomNodes separately in math.js, like math.expression.node.register(MyCustomNode)
1808 return node._compile(defs, args);
1809 }
1810 else {
1811 throw new Error('Cannot compile node: unknown type "' + node.type + '"');
1812 }
1813 }
1814
1815 return {
1816 register: register,
1817 compile: compile
1818 }
1819}
1820
1821exports.factory = factory;
1822
1823
1824/***/ }),
1825/* 8 */
1826/***/ (function(module, exports, __webpack_require__) {
1827
1828"use strict";
1829
1830
1831var util = __webpack_require__(25);
1832var DimensionError = __webpack_require__(11);
1833
1834var string = util.string,
1835 isString = string.isString;
1836
1837function factory (type, config, load, typed) {
1838
1839 var DenseMatrix = type.DenseMatrix;
1840
1841 /**
1842 * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, Bij..z).
1843 * Callback function invoked MxN times.
1844 *
1845 * C(i,j,...z) = f(Aij..z, Bij..z)
1846 *
1847 * @param {Matrix} a The DenseMatrix instance (A)
1848 * @param {Matrix} b The DenseMatrix instance (B)
1849 * @param {Function} callback The f(Aij..z,Bij..z) operation to invoke
1850 *
1851 * @return {Matrix} DenseMatrix (C)
1852 *
1853 * https://github.com/josdejong/mathjs/pull/346#issuecomment-97658658
1854 */
1855 var algorithm13 = function (a, b, callback) {
1856 // a arrays
1857 var adata = a._data;
1858 var asize = a._size;
1859 var adt = a._datatype;
1860 // b arrays
1861 var bdata = b._data;
1862 var bsize = b._size;
1863 var bdt = b._datatype;
1864 // c arrays
1865 var csize = [];
1866
1867 // validate dimensions
1868 if (asize.length !== bsize.length)
1869 throw new DimensionError(asize.length, bsize.length);
1870
1871 // validate each one of the dimension sizes
1872 for (var s = 0; s < asize.length; s++) {
1873 // must match
1874 if (asize[s] !== bsize[s])
1875 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
1876 // update dimension in c
1877 csize[s] = asize[s];
1878 }
1879
1880 // datatype
1881 var dt;
1882 // callback signature to use
1883 var cf = callback;
1884
1885 // process data types
1886 if (typeof adt === 'string' && adt === bdt) {
1887 // datatype
1888 dt = adt;
1889 // convert b to the same datatype
1890 b = typed.convert(b, dt);
1891 // callback
1892 cf = typed.find(callback, [dt, dt]);
1893 }
1894
1895 // populate cdata, iterate through dimensions
1896 var cdata = csize.length > 0 ? _iterate(cf, 0, csize, csize[0], adata, bdata) : [];
1897
1898 // c matrix
1899 return new DenseMatrix({
1900 data: cdata,
1901 size: csize,
1902 datatype: dt
1903 });
1904 };
1905
1906 // recursive function
1907 var _iterate = function (f, level, s, n, av, bv) {
1908 // initialize array for this level
1909 var cv = [];
1910 // check we reach the last level
1911 if (level === s.length - 1) {
1912 // loop arrays in last level
1913 for (var i = 0; i < n; i++) {
1914 // invoke callback and store value
1915 cv[i] = f(av[i], bv[i]);
1916 }
1917 }
1918 else {
1919 // iterate current level
1920 for (var j = 0; j < n; j++) {
1921 // iterate next level
1922 cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv[j]);
1923 }
1924 }
1925 return cv;
1926 };
1927
1928 return algorithm13;
1929}
1930
1931exports.name = 'algorithm13';
1932exports.factory = factory;
1933
1934
1935/***/ }),
1936/* 9 */
1937/***/ (function(module, exports, __webpack_require__) {
1938
1939"use strict";
1940
1941
1942var formatNumber = __webpack_require__(3).format;
1943var formatBigNumber = __webpack_require__(168).format;
1944var isBigNumber = __webpack_require__(71);
1945
1946/**
1947 * Test whether value is a string
1948 * @param {*} value
1949 * @return {boolean} isString
1950 */
1951exports.isString = function(value) {
1952 return typeof value === 'string';
1953};
1954
1955/**
1956 * Check if a text ends with a certain string.
1957 * @param {string} text
1958 * @param {string} search
1959 */
1960exports.endsWith = function(text, search) {
1961 var start = text.length - search.length;
1962 var end = text.length;
1963 return (text.substring(start, end) === search);
1964};
1965
1966/**
1967 * Format a value of any type into a string.
1968 *
1969 * Usage:
1970 * math.format(value)
1971 * math.format(value, precision)
1972 *
1973 * When value is a function:
1974 *
1975 * - When the function has a property `syntax`, it returns this
1976 * syntax description.
1977 * - In other cases, a string `'function'` is returned.
1978 *
1979 * When `value` is an Object:
1980 *
1981 * - When the object contains a property `format` being a function, this
1982 * function is invoked as `value.format(options)` and the result is returned.
1983 * - When the object has its own `toString` method, this method is invoked
1984 * and the result is returned.
1985 * - In other cases the function will loop over all object properties and
1986 * return JSON object notation like '{"a": 2, "b": 3}'.
1987 *
1988 * Example usage:
1989 * math.format(2/7); // '0.2857142857142857'
1990 * math.format(math.pi, 3); // '3.14'
1991 * math.format(new Complex(2, 3)); // '2 + 3i'
1992 * math.format('hello'); // '"hello"'
1993 *
1994 * @param {*} value Value to be stringified
1995 * @param {Object | number | Function} [options] Formatting options. See
1996 * lib/utils/number:format for a
1997 * description of the available
1998 * options.
1999 * @return {string} str
2000 */
2001exports.format = function(value, options) {
2002 if (typeof value === 'number') {
2003 return formatNumber(value, options);
2004 }
2005
2006 if (isBigNumber(value)) {
2007 return formatBigNumber(value, options);
2008 }
2009
2010 // note: we use unsafe duck-typing here to check for Fractions, this is
2011 // ok here since we're only invoking toString or concatenating its values
2012 if (looksLikeFraction(value)) {
2013 if (!options || options.fraction !== 'decimal') {
2014 // output as ratio, like '1/3'
2015 return (value.s * value.n) + '/' + value.d;
2016 }
2017 else {
2018 // output as decimal, like '0.(3)'
2019 return value.toString();
2020 }
2021 }
2022
2023 if (Array.isArray(value)) {
2024 return formatArray(value, options);
2025 }
2026
2027 if (exports.isString(value)) {
2028 return '"' + value + '"';
2029 }
2030
2031 if (typeof value === 'function') {
2032 return value.syntax ? String(value.syntax) : 'function';
2033 }
2034
2035 if (value && typeof value === 'object') {
2036 if (typeof value.format === 'function') {
2037 return value.format(options);
2038 }
2039 else if (value && value.toString() !== {}.toString()) {
2040 // this object has a non-native toString method, use that one
2041 return value.toString();
2042 }
2043 else {
2044 var entries = [];
2045
2046 for (var key in value) {
2047 if (value.hasOwnProperty(key)) {
2048 entries.push('"' + key + '": ' + exports.format(value[key], options));
2049 }
2050 }
2051
2052 return '{' + entries.join(', ') + '}';
2053 }
2054 }
2055
2056 return String(value);
2057};
2058
2059/**
2060 * Stringify a value into a string enclosed in double quotes.
2061 * Unescaped double quotes and backslashes inside the value are escaped.
2062 * @param {*} value
2063 * @return {string}
2064 */
2065exports.stringify = function (value) {
2066 var text = String(value);
2067 var escaped = '';
2068 var i = 0;
2069 while (i < text.length) {
2070 var c = text.charAt(i);
2071
2072 if (c === '\\') {
2073 escaped += c;
2074 i++;
2075
2076 c = text.charAt(i);
2077 if (c === '' || '"\\/bfnrtu'.indexOf(c) === -1) {
2078 escaped += '\\'; // no valid escape character -> escape it
2079 }
2080 escaped += c;
2081 }
2082 else if (c === '"') {
2083 escaped += '\\"';
2084 }
2085 else {
2086 escaped += c;
2087 }
2088 i++;
2089 }
2090
2091 return '"' + escaped + '"';
2092}
2093
2094/**
2095 * Escape special HTML characters
2096 * @param {*} value
2097 * @return {string}
2098 */
2099exports.escape = function (value) {
2100 var text = String(value);
2101 text = text.replace(/&/g, '&amp;')
2102 .replace(/"/g, '&quot;')
2103 .replace(/'/g, '&#39;')
2104 .replace(/</g, '&lt;')
2105 .replace(/>/g, '&gt;');
2106
2107 return text;
2108}
2109
2110/**
2111 * Recursively format an n-dimensional matrix
2112 * Example output: "[[1, 2], [3, 4]]"
2113 * @param {Array} array
2114 * @param {Object | number | Function} [options] Formatting options. See
2115 * lib/utils/number:format for a
2116 * description of the available
2117 * options.
2118 * @returns {string} str
2119 */
2120function formatArray (array, options) {
2121 if (Array.isArray(array)) {
2122 var str = '[';
2123 var len = array.length;
2124 for (var i = 0; i < len; i++) {
2125 if (i != 0) {
2126 str += ', ';
2127 }
2128 str += formatArray(array[i], options);
2129 }
2130 str += ']';
2131 return str;
2132 }
2133 else {
2134 return exports.format(array, options);
2135 }
2136}
2137
2138/**
2139 * Check whether a value looks like a Fraction (unsafe duck-type check)
2140 * @param {*} value
2141 * @return {boolean}
2142 */
2143function looksLikeFraction (value) {
2144 return (value &&
2145 typeof value === 'object' &&
2146 typeof value.s === 'number' &&
2147 typeof value.n === 'number' &&
2148 typeof value.d === 'number') || false;
2149}
2150
2151
2152/***/ }),
2153/* 10 */
2154/***/ (function(module, exports, __webpack_require__) {
2155
2156"use strict";
2157
2158
2159var nearlyEqual = __webpack_require__(3).nearlyEqual;
2160var bigNearlyEqual = __webpack_require__(37);
2161
2162function factory (type, config, load, typed) {
2163
2164 /**
2165 * Test whether two values are equal.
2166 *
2167 * @param {number | BigNumber | Fraction | boolean | Complex | Unit} x First value to compare
2168 * @param {number | BigNumber | Fraction | boolean | Complex} y Second value to compare
2169 * @return {boolean} Returns true when the compared values are equal, else returns false
2170 * @private
2171 */
2172 var equalScalar = typed('equalScalar', {
2173
2174 'boolean, boolean': function (x, y) {
2175 return x === y;
2176 },
2177
2178 'number, number': function (x, y) {
2179 return x === y || nearlyEqual(x, y, config.epsilon);
2180 },
2181
2182 'BigNumber, BigNumber': function (x, y) {
2183 return x.eq(y) || bigNearlyEqual(x, y, config.epsilon);
2184 },
2185
2186 'Fraction, Fraction': function (x, y) {
2187 return x.equals(y);
2188 },
2189
2190 'Complex, Complex': function (x, y) {
2191 return x.equals(y);
2192 },
2193
2194 'Unit, Unit': function (x, y) {
2195 if (!x.equalBase(y)) {
2196 throw new Error('Cannot compare units with different base');
2197 }
2198 return equalScalar(x.value, y.value);
2199 },
2200
2201 'string, string': function (x, y) {
2202 return x === y;
2203 }
2204 });
2205
2206 return equalScalar;
2207}
2208
2209exports.factory = factory;
2210
2211
2212/***/ }),
2213/* 11 */
2214/***/ (function(module, exports, __webpack_require__) {
2215
2216"use strict";
2217
2218
2219/**
2220 * Create a range error with the message:
2221 * 'Dimension mismatch (<actual size> != <expected size>)'
2222 * @param {number | number[]} actual The actual size
2223 * @param {number | number[]} expected The expected size
2224 * @param {string} [relation='!='] Optional relation between actual
2225 * and expected size: '!=', '<', etc.
2226 * @extends RangeError
2227 */
2228function DimensionError(actual, expected, relation) {
2229 if (!(this instanceof DimensionError)) {
2230 throw new SyntaxError('Constructor must be called with the new operator');
2231 }
2232
2233 this.actual = actual;
2234 this.expected = expected;
2235 this.relation = relation;
2236
2237 this.message = 'Dimension mismatch (' +
2238 (Array.isArray(actual) ? ('[' + actual.join(', ') + ']') : actual) +
2239 ' ' + (this.relation || '!=') + ' ' +
2240 (Array.isArray(expected) ? ('[' + expected.join(', ') + ']') : expected) +
2241 ')';
2242
2243 this.stack = (new Error()).stack;
2244}
2245
2246DimensionError.prototype = new RangeError();
2247DimensionError.prototype.constructor = RangeError;
2248DimensionError.prototype.name = 'DimensionError';
2249DimensionError.prototype.isDimensionError = true;
2250
2251module.exports = DimensionError;
2252
2253
2254/***/ }),
2255/* 12 */
2256/***/ (function(module, exports, __webpack_require__) {
2257
2258"use strict";
2259
2260
2261var extend = __webpack_require__(5).extend;
2262var array = __webpack_require__(2);
2263
2264function factory (type, config, load, typed) {
2265 var latex = __webpack_require__(4);
2266
2267 var matrix = load(__webpack_require__(0));
2268 var addScalar = load(__webpack_require__(16));
2269 var multiplyScalar = load(__webpack_require__(22));
2270 var equalScalar = load(__webpack_require__(10));
2271
2272 var algorithm11 = load(__webpack_require__(19));
2273 var algorithm14 = load(__webpack_require__(6));
2274
2275 var DenseMatrix = type.DenseMatrix;
2276 var SparseMatrix = type.SparseMatrix;
2277
2278 /**
2279 * Multiply two or more values, `x * y`.
2280 * For matrices, the matrix product is calculated.
2281 *
2282 * Syntax:
2283 *
2284 * math.multiply(x, y)
2285 * math.multiply(x, y, z, ...)
2286 *
2287 * Examples:
2288 *
2289 * math.multiply(4, 5.2); // returns number 20.8
2290 * math.multiply(2, 3, 4); // returns number 24
2291 *
2292 * var a = math.complex(2, 3);
2293 * var b = math.complex(4, 1);
2294 * math.multiply(a, b); // returns Complex 5 + 14i
2295 *
2296 * var c = [[1, 2], [4, 3]];
2297 * var d = [[1, 2, 3], [3, -4, 7]];
2298 * math.multiply(c, d); // returns Array [[7, -6, 17], [13, -4, 33]]
2299 *
2300 * var e = math.unit('2.1 km');
2301 * math.multiply(3, e); // returns Unit 6.3 km
2302 *
2303 * See also:
2304 *
2305 * divide, prod, cross, dot
2306 *
2307 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First value to multiply
2308 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second value to multiply
2309 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y`
2310 */
2311 var multiply = typed('multiply', extend({
2312 // we extend the signatures of multiplyScalar with signatures dealing with matrices
2313
2314 'Array, Array': function (x, y) {
2315 // check dimensions
2316 _validateMatrixDimensions(array.size(x), array.size(y));
2317
2318 // use dense matrix implementation
2319 var m = multiply(matrix(x), matrix(y));
2320 // return array or scalar
2321 return type.isMatrix(m) ? m.valueOf() : m;
2322 },
2323
2324 'Matrix, Matrix': function (x, y) {
2325 // dimensions
2326 var xsize = x.size();
2327 var ysize = y.size();
2328
2329 // check dimensions
2330 _validateMatrixDimensions(xsize, ysize);
2331
2332 // process dimensions
2333 if (xsize.length === 1) {
2334 // process y dimensions
2335 if (ysize.length === 1) {
2336 // Vector * Vector
2337 return _multiplyVectorVector(x, y, xsize[0]);
2338 }
2339 // Vector * Matrix
2340 return _multiplyVectorMatrix(x, y);
2341 }
2342 // process y dimensions
2343 if (ysize.length === 1) {
2344 // Matrix * Vector
2345 return _multiplyMatrixVector(x, y);
2346 }
2347 // Matrix * Matrix
2348 return _multiplyMatrixMatrix(x, y);
2349 },
2350
2351 'Matrix, Array': function (x, y) {
2352 // use Matrix * Matrix implementation
2353 return multiply(x, matrix(y));
2354 },
2355
2356 'Array, Matrix': function (x, y) {
2357 // use Matrix * Matrix implementation
2358 return multiply(matrix(x, y.storage()), y);
2359 },
2360
2361 'Matrix, any': function (x, y) {
2362 // result
2363 var c;
2364
2365 // process storage format
2366 switch (x.storage()) {
2367 case 'sparse':
2368 c = algorithm11(x, y, multiplyScalar, false);
2369 break;
2370 case 'dense':
2371 c = algorithm14(x, y, multiplyScalar, false);
2372 break;
2373 }
2374 return c;
2375 },
2376
2377 'any, Matrix': function (x, y) {
2378 // result
2379 var c;
2380 // check storage format
2381 switch (y.storage()) {
2382 case 'sparse':
2383 c = algorithm11(y, x, multiplyScalar, true);
2384 break;
2385 case 'dense':
2386 c = algorithm14(y, x, multiplyScalar, true);
2387 break;
2388 }
2389 return c;
2390 },
2391
2392 'Array, any': function (x, y) {
2393 // use matrix implementation
2394 return algorithm14(matrix(x), y, multiplyScalar, false).valueOf();
2395 },
2396
2397 'any, Array': function (x, y) {
2398 // use matrix implementation
2399 return algorithm14(matrix(y), x, multiplyScalar, true).valueOf();
2400 },
2401
2402 'any, any': multiplyScalar,
2403
2404 'Array | Matrix | any, Array | Matrix | any, ...any': function (x, y, rest) {
2405 var result = multiply(x, y);
2406
2407 for (var i = 0; i < rest.length; i++) {
2408 result = multiply(result, rest[i]);
2409 }
2410
2411 return result;
2412 }
2413 }, multiplyScalar.signatures));
2414
2415 var _validateMatrixDimensions = function (size1, size2) {
2416 // check left operand dimensions
2417 switch (size1.length) {
2418 case 1:
2419 // check size2
2420 switch (size2.length) {
2421 case 1:
2422 // Vector x Vector
2423 if (size1[0] !== size2[0]) {
2424 // throw error
2425 throw new RangeError('Dimension mismatch in multiplication. Vectors must have the same length');
2426 }
2427 break;
2428 case 2:
2429 // Vector x Matrix
2430 if (size1[0] !== size2[0]) {
2431 // throw error
2432 throw new RangeError('Dimension mismatch in multiplication. Vector length (' + size1[0] + ') must match Matrix rows (' + size2[0] + ')');
2433 }
2434 break;
2435 default:
2436 throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)');
2437 }
2438 break;
2439 case 2:
2440 // check size2
2441 switch (size2.length) {
2442 case 1:
2443 // Matrix x Vector
2444 if (size1[1] !== size2[0]) {
2445 // throw error
2446 throw new RangeError('Dimension mismatch in multiplication. Matrix columns (' + size1[1] + ') must match Vector length (' + size2[0] + ')');
2447 }
2448 break;
2449 case 2:
2450 // Matrix x Matrix
2451 if (size1[1] !== size2[0]) {
2452 // throw error
2453 throw new RangeError('Dimension mismatch in multiplication. Matrix A columns (' + size1[1] + ') must match Matrix B rows (' + size2[0] + ')');
2454 }
2455 break;
2456 default:
2457 throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)');
2458 }
2459 break;
2460 default:
2461 throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix A has ' + size1.length + ' dimensions)');
2462 }
2463 };
2464
2465 /**
2466 * C = A * B
2467 *
2468 * @param {Matrix} a Dense Vector (N)
2469 * @param {Matrix} b Dense Vector (N)
2470 *
2471 * @return {number} Scalar value
2472 */
2473 var _multiplyVectorVector = function (a, b, n) {
2474 // check empty vector
2475 if (n === 0)
2476 throw new Error('Cannot multiply two empty vectors');
2477
2478 // a dense
2479 var adata = a._data;
2480 var adt = a._datatype;
2481 // b dense
2482 var bdata = b._data;
2483 var bdt = b._datatype;
2484
2485 // datatype
2486 var dt;
2487 // addScalar signature to use
2488 var af = addScalar;
2489 // multiplyScalar signature to use
2490 var mf = multiplyScalar;
2491
2492 // process data types
2493 if (adt && bdt && adt === bdt && typeof adt === 'string') {
2494 // datatype
2495 dt = adt;
2496 // find signatures that matches (dt, dt)
2497 af = typed.find(addScalar, [dt, dt]);
2498 mf = typed.find(multiplyScalar, [dt, dt]);
2499 }
2500
2501 // result (do not initialize it with zero)
2502 var c = mf(adata[0], bdata[0]);
2503 // loop data
2504 for (var i = 1; i < n; i++) {
2505 // multiply and accumulate
2506 c = af(c, mf(adata[i], bdata[i]));
2507 }
2508 return c;
2509 };
2510
2511 /**
2512 * C = A * B
2513 *
2514 * @param {Matrix} a Dense Vector (M)
2515 * @param {Matrix} b Matrix (MxN)
2516 *
2517 * @return {Matrix} Dense Vector (N)
2518 */
2519 var _multiplyVectorMatrix = function (a, b) {
2520 // process storage
2521 switch (b.storage()) {
2522 case 'dense':
2523 return _multiplyVectorDenseMatrix(a, b);
2524 }
2525 throw new Error('Not implemented');
2526 };
2527
2528 /**
2529 * C = A * B
2530 *
2531 * @param {Matrix} a Dense Vector (M)
2532 * @param {Matrix} b Dense Matrix (MxN)
2533 *
2534 * @return {Matrix} Dense Vector (N)
2535 */
2536 var _multiplyVectorDenseMatrix = function (a, b) {
2537 // a dense
2538 var adata = a._data;
2539 var asize = a._size;
2540 var adt = a._datatype;
2541 // b dense
2542 var bdata = b._data;
2543 var bsize = b._size;
2544 var bdt = b._datatype;
2545 // rows & columns
2546 var alength = asize[0];
2547 var bcolumns = bsize[1];
2548
2549 // datatype
2550 var dt;
2551 // addScalar signature to use
2552 var af = addScalar;
2553 // multiplyScalar signature to use
2554 var mf = multiplyScalar;
2555
2556 // process data types
2557 if (adt && bdt && adt === bdt && typeof adt === 'string') {
2558 // datatype
2559 dt = adt;
2560 // find signatures that matches (dt, dt)
2561 af = typed.find(addScalar, [dt, dt]);
2562 mf = typed.find(multiplyScalar, [dt, dt]);
2563 }
2564
2565 // result
2566 var c = [];
2567
2568 // loop matrix columns
2569 for (var j = 0; j < bcolumns; j++) {
2570 // sum (do not initialize it with zero)
2571 var sum = mf(adata[0], bdata[0][j]);
2572 // loop vector
2573 for (var i = 1; i < alength; i++) {
2574 // multiply & accumulate
2575 sum = af(sum, mf(adata[i], bdata[i][j]));
2576 }
2577 c[j] = sum;
2578 }
2579
2580 // return matrix
2581 return new DenseMatrix({
2582 data: c,
2583 size: [bcolumns],
2584 datatype: dt
2585 });
2586 };
2587
2588 /**
2589 * C = A * B
2590 *
2591 * @param {Matrix} a Matrix (MxN)
2592 * @param {Matrix} b Dense Vector (N)
2593 *
2594 * @return {Matrix} Dense Vector (M)
2595 */
2596 var _multiplyMatrixVector = function (a, b) {
2597 // process storage
2598 switch (a.storage()) {
2599 case 'dense':
2600 return _multiplyDenseMatrixVector(a, b);
2601 case 'sparse':
2602 return _multiplySparseMatrixVector(a, b);
2603 }
2604 };
2605
2606 /**
2607 * C = A * B
2608 *
2609 * @param {Matrix} a Matrix (MxN)
2610 * @param {Matrix} b Matrix (NxC)
2611 *
2612 * @return {Matrix} Matrix (MxC)
2613 */
2614 var _multiplyMatrixMatrix = function (a, b) {
2615 // process storage
2616 switch (a.storage()) {
2617 case 'dense':
2618 // process storage
2619 switch (b.storage()) {
2620 case 'dense':
2621 return _multiplyDenseMatrixDenseMatrix(a, b);
2622 case 'sparse':
2623 return _multiplyDenseMatrixSparseMatrix(a, b);
2624 }
2625 break;
2626 case 'sparse':
2627 // process storage
2628 switch (b.storage()) {
2629 case 'dense':
2630 return _multiplySparseMatrixDenseMatrix(a, b);
2631 case 'sparse':
2632 return _multiplySparseMatrixSparseMatrix(a, b);
2633 }
2634 break;
2635 }
2636 };
2637
2638 /**
2639 * C = A * B
2640 *
2641 * @param {Matrix} a DenseMatrix (MxN)
2642 * @param {Matrix} b Dense Vector (N)
2643 *
2644 * @return {Matrix} Dense Vector (M)
2645 */
2646 var _multiplyDenseMatrixVector = function (a, b) {
2647 // a dense
2648 var adata = a._data;
2649 var asize = a._size;
2650 var adt = a._datatype;
2651 // b dense
2652 var bdata = b._data;
2653 var bdt = b._datatype;
2654 // rows & columns
2655 var arows = asize[0];
2656 var acolumns = asize[1];
2657
2658 // datatype
2659 var dt;
2660 // addScalar signature to use
2661 var af = addScalar;
2662 // multiplyScalar signature to use
2663 var mf = multiplyScalar;
2664
2665 // process data types
2666 if (adt && bdt && adt === bdt && typeof adt === 'string') {
2667 // datatype
2668 dt = adt;
2669 // find signatures that matches (dt, dt)
2670 af = typed.find(addScalar, [dt, dt]);
2671 mf = typed.find(multiplyScalar, [dt, dt]);
2672 }
2673
2674 // result
2675 var c = [];
2676
2677 // loop matrix a rows
2678 for (var i = 0; i < arows; i++) {
2679 // current row
2680 var row = adata[i];
2681 // sum (do not initialize it with zero)
2682 var sum = mf(row[0], bdata[0]);
2683 // loop matrix a columns
2684 for (var j = 1; j < acolumns; j++) {
2685 // multiply & accumulate
2686 sum = af(sum, mf(row[j], bdata[j]));
2687 }
2688 c[i] = sum;
2689 }
2690
2691 // return matrix
2692 return new DenseMatrix({
2693 data: c,
2694 size: [arows],
2695 datatype: dt
2696 });
2697 };
2698
2699 /**
2700 * C = A * B
2701 *
2702 * @param {Matrix} a DenseMatrix (MxN)
2703 * @param {Matrix} b DenseMatrix (NxC)
2704 *
2705 * @return {Matrix} DenseMatrix (MxC)
2706 */
2707 var _multiplyDenseMatrixDenseMatrix = function (a, b) {
2708 // a dense
2709 var adata = a._data;
2710 var asize = a._size;
2711 var adt = a._datatype;
2712 // b dense
2713 var bdata = b._data;
2714 var bsize = b._size;
2715 var bdt = b._datatype;
2716 // rows & columns
2717 var arows = asize[0];
2718 var acolumns = asize[1];
2719 var bcolumns = bsize[1];
2720
2721 // datatype
2722 var dt;
2723 // addScalar signature to use
2724 var af = addScalar;
2725 // multiplyScalar signature to use
2726 var mf = multiplyScalar;
2727
2728 // process data types
2729 if (adt && bdt && adt === bdt && typeof adt === 'string') {
2730 // datatype
2731 dt = adt;
2732 // find signatures that matches (dt, dt)
2733 af = typed.find(addScalar, [dt, dt]);
2734 mf = typed.find(multiplyScalar, [dt, dt]);
2735 }
2736
2737 // result
2738 var c = [];
2739
2740 // loop matrix a rows
2741 for (var i = 0; i < arows; i++) {
2742 // current row
2743 var row = adata[i];
2744 // initialize row array
2745 c[i] = [];
2746 // loop matrix b columns
2747 for (var j = 0; j < bcolumns; j++) {
2748 // sum (avoid initializing sum to zero)
2749 var sum = mf(row[0], bdata[0][j]);
2750 // loop matrix a columns
2751 for (var x = 1; x < acolumns; x++) {
2752 // multiply & accumulate
2753 sum = af(sum, mf(row[x], bdata[x][j]));
2754 }
2755 c[i][j] = sum;
2756 }
2757 }
2758
2759 // return matrix
2760 return new DenseMatrix({
2761 data: c,
2762 size: [arows, bcolumns],
2763 datatype: dt
2764 });
2765 };
2766
2767 /**
2768 * C = A * B
2769 *
2770 * @param {Matrix} a DenseMatrix (MxN)
2771 * @param {Matrix} b SparseMatrix (NxC)
2772 *
2773 * @return {Matrix} SparseMatrix (MxC)
2774 */
2775 var _multiplyDenseMatrixSparseMatrix = function (a, b) {
2776 // a dense
2777 var adata = a._data;
2778 var asize = a._size;
2779 var adt = a._datatype;
2780 // b sparse
2781 var bvalues = b._values;
2782 var bindex = b._index;
2783 var bptr = b._ptr;
2784 var bsize = b._size;
2785 var bdt = b._datatype;
2786 // validate b matrix
2787 if (!bvalues)
2788 throw new Error('Cannot multiply Dense Matrix times Pattern only Matrix');
2789 // rows & columns
2790 var arows = asize[0];
2791 var bcolumns = bsize[1];
2792
2793 // datatype
2794 var dt;
2795 // addScalar signature to use
2796 var af = addScalar;
2797 // multiplyScalar signature to use
2798 var mf = multiplyScalar;
2799 // equalScalar signature to use
2800 var eq = equalScalar;
2801 // zero value
2802 var zero = 0;
2803
2804 // process data types
2805 if (adt && bdt && adt === bdt && typeof adt === 'string') {
2806 // datatype
2807 dt = adt;
2808 // find signatures that matches (dt, dt)
2809 af = typed.find(addScalar, [dt, dt]);
2810 mf = typed.find(multiplyScalar, [dt, dt]);
2811 eq = typed.find(equalScalar, [dt, dt]);
2812 // convert 0 to the same datatype
2813 zero = typed.convert(0, dt);
2814 }
2815
2816 // result
2817 var cvalues = [];
2818 var cindex = [];
2819 var cptr = [];
2820 // c matrix
2821 var c = new SparseMatrix({
2822 values : cvalues,
2823 index: cindex,
2824 ptr: cptr,
2825 size: [arows, bcolumns],
2826 datatype: dt
2827 });
2828
2829 // loop b columns
2830 for (var jb = 0; jb < bcolumns; jb++) {
2831 // update ptr
2832 cptr[jb] = cindex.length;
2833 // indeces in column jb
2834 var kb0 = bptr[jb];
2835 var kb1 = bptr[jb + 1];
2836 // do not process column jb if no data exists
2837 if (kb1 > kb0) {
2838 // last row mark processed
2839 var last = 0;
2840 // loop a rows
2841 for (var i = 0; i < arows; i++) {
2842 // column mark
2843 var mark = i + 1;
2844 // C[i, jb]
2845 var cij;
2846 // values in b column j
2847 for (var kb = kb0; kb < kb1; kb++) {
2848 // row
2849 var ib = bindex[kb];
2850 // check value has been initialized
2851 if (last !== mark) {
2852 // first value in column jb
2853 cij = mf(adata[i][ib], bvalues[kb]);
2854 // update mark
2855 last = mark;
2856 }
2857 else {
2858 // accumulate value
2859 cij = af(cij, mf(adata[i][ib], bvalues[kb]));
2860 }
2861 }
2862 // check column has been processed and value != 0
2863 if (last === mark && !eq(cij, zero)) {
2864 // push row & value
2865 cindex.push(i);
2866 cvalues.push(cij);
2867 }
2868 }
2869 }
2870 }
2871 // update ptr
2872 cptr[bcolumns] = cindex.length;
2873
2874 // return sparse matrix
2875 return c;
2876 };
2877
2878 /**
2879 * C = A * B
2880 *
2881 * @param {Matrix} a SparseMatrix (MxN)
2882 * @param {Matrix} b Dense Vector (N)
2883 *
2884 * @return {Matrix} SparseMatrix (M, 1)
2885 */
2886 var _multiplySparseMatrixVector = function (a, b) {
2887 // a sparse
2888 var avalues = a._values;
2889 var aindex = a._index;
2890 var aptr = a._ptr;
2891 var adt = a._datatype;
2892 // validate a matrix
2893 if (!avalues)
2894 throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix');
2895 // b dense
2896 var bdata = b._data;
2897 var bdt = b._datatype;
2898 // rows & columns
2899 var arows = a._size[0];
2900 var brows = b._size[0];
2901 // result
2902 var cvalues = [];
2903 var cindex = [];
2904 var cptr = [];
2905
2906 // datatype
2907 var dt;
2908 // addScalar signature to use
2909 var af = addScalar;
2910 // multiplyScalar signature to use
2911 var mf = multiplyScalar;
2912 // equalScalar signature to use
2913 var eq = equalScalar;
2914 // zero value
2915 var zero = 0;
2916
2917 // process data types
2918 if (adt && bdt && adt === bdt && typeof adt === 'string') {
2919 // datatype
2920 dt = adt;
2921 // find signatures that matches (dt, dt)
2922 af = typed.find(addScalar, [dt, dt]);
2923 mf = typed.find(multiplyScalar, [dt, dt]);
2924 eq = typed.find(equalScalar, [dt, dt]);
2925 // convert 0 to the same datatype
2926 zero = typed.convert(0, dt);
2927 }
2928
2929 // workspace
2930 var x = [];
2931 // vector with marks indicating a value x[i] exists in a given column
2932 var w = [];
2933
2934 // update ptr
2935 cptr[0] = 0;
2936 // rows in b
2937 for (var ib = 0; ib < brows; ib++) {
2938 // b[ib]
2939 var vbi = bdata[ib];
2940 // check b[ib] != 0, avoid loops
2941 if (!eq(vbi, zero)) {
2942 // A values & index in ib column
2943 for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
2944 // a row
2945 var ia = aindex[ka];
2946 // check value exists in current j
2947 if (!w[ia]) {
2948 // ia is new entry in j
2949 w[ia] = true;
2950 // add i to pattern of C
2951 cindex.push(ia);
2952 // x(ia) = A
2953 x[ia] = mf(vbi, avalues[ka]);
2954 }
2955 else {
2956 // i exists in C already
2957 x[ia] = af(x[ia], mf(vbi, avalues[ka]));
2958 }
2959 }
2960 }
2961 }
2962 // copy values from x to column jb of c
2963 for (var p1 = cindex.length, p = 0; p < p1; p++) {
2964 // row
2965 var ic = cindex[p];
2966 // copy value
2967 cvalues[p] = x[ic];
2968 }
2969 // update ptr
2970 cptr[1] = cindex.length;
2971
2972 // return sparse matrix
2973 return new SparseMatrix({
2974 values : cvalues,
2975 index: cindex,
2976 ptr: cptr,
2977 size: [arows, 1],
2978 datatype: dt
2979 });
2980 };
2981
2982 /**
2983 * C = A * B
2984 *
2985 * @param {Matrix} a SparseMatrix (MxN)
2986 * @param {Matrix} b DenseMatrix (NxC)
2987 *
2988 * @return {Matrix} SparseMatrix (MxC)
2989 */
2990 var _multiplySparseMatrixDenseMatrix = function (a, b) {
2991 // a sparse
2992 var avalues = a._values;
2993 var aindex = a._index;
2994 var aptr = a._ptr;
2995 var adt = a._datatype;
2996 // validate a matrix
2997 if (!avalues)
2998 throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix');
2999 // b dense
3000 var bdata = b._data;
3001 var bdt = b._datatype;
3002 // rows & columns
3003 var arows = a._size[0];
3004 var brows = b._size[0];
3005 var bcolumns = b._size[1];
3006
3007 // datatype
3008 var dt;
3009 // addScalar signature to use
3010 var af = addScalar;
3011 // multiplyScalar signature to use
3012 var mf = multiplyScalar;
3013 // equalScalar signature to use
3014 var eq = equalScalar;
3015 // zero value
3016 var zero = 0;
3017
3018 // process data types
3019 if (adt && bdt && adt === bdt && typeof adt === 'string') {
3020 // datatype
3021 dt = adt;
3022 // find signatures that matches (dt, dt)
3023 af = typed.find(addScalar, [dt, dt]);
3024 mf = typed.find(multiplyScalar, [dt, dt]);
3025 eq = typed.find(equalScalar, [dt, dt]);
3026 // convert 0 to the same datatype
3027 zero = typed.convert(0, dt);
3028 }
3029
3030 // result
3031 var cvalues = [];
3032 var cindex = [];
3033 var cptr = [];
3034 // c matrix
3035 var c = new SparseMatrix({
3036 values : cvalues,
3037 index: cindex,
3038 ptr: cptr,
3039 size: [arows, bcolumns],
3040 datatype: dt
3041 });
3042
3043 // workspace
3044 var x = [];
3045 // vector with marks indicating a value x[i] exists in a given column
3046 var w = [];
3047
3048 // loop b columns
3049 for (var jb = 0; jb < bcolumns; jb++) {
3050 // update ptr
3051 cptr[jb] = cindex.length;
3052 // mark in workspace for current column
3053 var mark = jb + 1;
3054 // rows in jb
3055 for (var ib = 0; ib < brows; ib++) {
3056 // b[ib, jb]
3057 var vbij = bdata[ib][jb];
3058 // check b[ib, jb] != 0, avoid loops
3059 if (!eq(vbij, zero)) {
3060 // A values & index in ib column
3061 for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
3062 // a row
3063 var ia = aindex[ka];
3064 // check value exists in current j
3065 if (w[ia] !== mark) {
3066 // ia is new entry in j
3067 w[ia] = mark;
3068 // add i to pattern of C
3069 cindex.push(ia);
3070 // x(ia) = A
3071 x[ia] = mf(vbij, avalues[ka]);
3072 }
3073 else {
3074 // i exists in C already
3075 x[ia] = af(x[ia], mf(vbij, avalues[ka]));
3076 }
3077 }
3078 }
3079 }
3080 // copy values from x to column jb of c
3081 for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) {
3082 // row
3083 var ic = cindex[p];
3084 // copy value
3085 cvalues[p] = x[ic];
3086 }
3087 }
3088 // update ptr
3089 cptr[bcolumns] = cindex.length;
3090
3091 // return sparse matrix
3092 return c;
3093 };
3094
3095 /**
3096 * C = A * B
3097 *
3098 * @param {Matrix} a SparseMatrix (MxN)
3099 * @param {Matrix} b SparseMatrix (NxC)
3100 *
3101 * @return {Matrix} SparseMatrix (MxC)
3102 */
3103 var _multiplySparseMatrixSparseMatrix = function (a, b) {
3104 // a sparse
3105 var avalues = a._values;
3106 var aindex = a._index;
3107 var aptr = a._ptr;
3108 var adt = a._datatype;
3109 // b sparse
3110 var bvalues = b._values;
3111 var bindex = b._index;
3112 var bptr = b._ptr;
3113 var bdt = b._datatype;
3114
3115 // rows & columns
3116 var arows = a._size[0];
3117 var bcolumns = b._size[1];
3118 // flag indicating both matrices (a & b) contain data
3119 var values = avalues && bvalues;
3120
3121 // datatype
3122 var dt;
3123 // addScalar signature to use
3124 var af = addScalar;
3125 // multiplyScalar signature to use
3126 var mf = multiplyScalar;
3127
3128 // process data types
3129 if (adt && bdt && adt === bdt && typeof adt === 'string') {
3130 // datatype
3131 dt = adt;
3132 // find signatures that matches (dt, dt)
3133 af = typed.find(addScalar, [dt, dt]);
3134 mf = typed.find(multiplyScalar, [dt, dt]);
3135 }
3136
3137 // result
3138 var cvalues = values ? [] : undefined;
3139 var cindex = [];
3140 var cptr = [];
3141 // c matrix
3142 var c = new SparseMatrix({
3143 values : cvalues,
3144 index: cindex,
3145 ptr: cptr,
3146 size: [arows, bcolumns],
3147 datatype: dt
3148 });
3149
3150 // workspace
3151 var x = values ? [] : undefined;
3152 // vector with marks indicating a value x[i] exists in a given column
3153 var w = [];
3154 // variables
3155 var ka, ka0, ka1, kb, kb0, kb1, ia, ib;
3156 // loop b columns
3157 for (var jb = 0; jb < bcolumns; jb++) {
3158 // update ptr
3159 cptr[jb] = cindex.length;
3160 // mark in workspace for current column
3161 var mark = jb + 1;
3162 // B values & index in j
3163 for (kb0 = bptr[jb], kb1 = bptr[jb + 1], kb = kb0; kb < kb1; kb++) {
3164 // b row
3165 ib = bindex[kb];
3166 // check we need to process values
3167 if (values) {
3168 // loop values in a[:,ib]
3169 for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
3170 // row
3171 ia = aindex[ka];
3172 // check value exists in current j
3173 if (w[ia] !== mark) {
3174 // ia is new entry in j
3175 w[ia] = mark;
3176 // add i to pattern of C
3177 cindex.push(ia);
3178 // x(ia) = A
3179 x[ia] = mf(bvalues[kb], avalues[ka]);
3180 }
3181 else {
3182 // i exists in C already
3183 x[ia] = af(x[ia], mf(bvalues[kb], avalues[ka]));
3184 }
3185 }
3186 }
3187 else {
3188 // loop values in a[:,ib]
3189 for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
3190 // row
3191 ia = aindex[ka];
3192 // check value exists in current j
3193 if (w[ia] !== mark) {
3194 // ia is new entry in j
3195 w[ia] = mark;
3196 // add i to pattern of C
3197 cindex.push(ia);
3198 }
3199 }
3200 }
3201 }
3202 // check we need to process matrix values (pattern matrix)
3203 if (values) {
3204 // copy values from x to column jb of c
3205 for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) {
3206 // row
3207 var ic = cindex[p];
3208 // copy value
3209 cvalues[p] = x[ic];
3210 }
3211 }
3212 }
3213 // update ptr
3214 cptr[bcolumns] = cindex.length;
3215
3216 // return sparse matrix
3217 return c;
3218 };
3219
3220 multiply.toTex = {
3221 2: '\\left(${args[0]}' + latex.operators['multiply'] + '${args[1]}\\right)'
3222 };
3223
3224 return multiply;
3225}
3226
3227exports.name = 'multiply';
3228exports.factory = factory;
3229
3230
3231/***/ }),
3232/* 13 */
3233/***/ (function(module, exports, __webpack_require__) {
3234
3235"use strict";
3236
3237
3238var hasOwnProperty = __webpack_require__(5).hasOwnProperty;
3239
3240/**
3241 * Get a property of a plain object
3242 * Throws an error in case the object is not a plain object or the
3243 * property is not defined on the object itself
3244 * @param {Object} object
3245 * @param {string} prop
3246 * @return {*} Returns the property value when safe
3247 */
3248function getSafeProperty (object, prop) {
3249 // only allow getting safe properties of a plain object
3250 if (isPlainObject(object) && isSafeProperty(object, prop)) {
3251 return object[prop];
3252 }
3253
3254 if (typeof object[prop] === 'function' && isSafeMethod(object, prop)) {
3255 throw new Error('Cannot access method "' + prop + '" as a property');
3256 }
3257
3258 throw new Error('No access to property "' + prop + '"');
3259}
3260
3261/**
3262 * Set a property on a plain object.
3263 * Throws an error in case the object is not a plain object or the
3264 * property would override an inherited property like .constructor or .toString
3265 * @param {Object} object
3266 * @param {string} prop
3267 * @param {*} value
3268 * @return {*} Returns the value
3269 */
3270// TODO: merge this function into access.js?
3271function setSafeProperty (object, prop, value) {
3272 // only allow setting safe properties of a plain object
3273 if (isPlainObject(object) && isSafeProperty(object, prop)) {
3274 return object[prop] = value;
3275 }
3276
3277 throw new Error('No access to property "' + prop + '"');
3278}
3279
3280/**
3281 * Test whether a property is safe to use for an object.
3282 * For example .toString and .constructor are not safe
3283 * @param {string} prop
3284 * @return {boolean} Returns true when safe
3285 */
3286function isSafeProperty (object, prop) {
3287 if (!object || typeof object !== 'object') {
3288 return false;
3289 }
3290 // SAFE: whitelisted
3291 // e.g length
3292 if (hasOwnProperty(safeNativeProperties, prop)) {
3293 return true;
3294 }
3295 // UNSAFE: inherited from Object prototype
3296 // e.g constructor
3297 if (prop in Object.prototype) {
3298 // 'in' is used instead of hasOwnProperty for nodejs v0.10
3299 // which is inconsistent on root prototypes. It is safe
3300 // here because Object.prototype is a root object
3301 return false;
3302 }
3303 // UNSAFE: inherited from Function prototype
3304 // e.g call, apply
3305 if (prop in Function.prototype) {
3306 // 'in' is used instead of hasOwnProperty for nodejs v0.10
3307 // which is inconsistent on root prototypes. It is safe
3308 // here because Function.prototype is a root object
3309 return false;
3310 }
3311 return true;
3312}
3313
3314/**
3315 * Validate whether a method is safe.
3316 * Throws an error when that's not the case.
3317 * @param {Object} object
3318 * @param {string} method
3319 */
3320// TODO: merge this function into assign.js?
3321function validateSafeMethod (object, method) {
3322 if (!isSafeMethod(object, method)) {
3323 throw new Error('No access to method "' + method + '"');
3324 }
3325}
3326
3327/**
3328 * Check whether a method is safe.
3329 * Throws an error when that's not the case (for example for `constructor`).
3330 * @param {Object} object
3331 * @param {string} method
3332 * @return {boolean} Returns true when safe, false otherwise
3333 */
3334function isSafeMethod (object, method) {
3335 if (!object || typeof object[method] !== 'function') {
3336 return false;
3337 }
3338 // UNSAFE: ghosted
3339 // e.g overridden toString
3340 // Note that IE10 doesn't support __proto__ and we can't do this check there.
3341 if (hasOwnProperty(object, method) &&
3342 (object.__proto__ && (method in object.__proto__))) {
3343 return false;
3344 }
3345 // SAFE: whitelisted
3346 // e.g toString
3347 if (hasOwnProperty(safeNativeMethods, method)) {
3348 return true;
3349 }
3350 // UNSAFE: inherited from Object prototype
3351 // e.g constructor
3352 if (method in Object.prototype) {
3353 // 'in' is used instead of hasOwnProperty for nodejs v0.10
3354 // which is inconsistent on root prototypes. It is safe
3355 // here because Object.prototype is a root object
3356 return false;
3357 }
3358 // UNSAFE: inherited from Function prototype
3359 // e.g call, apply
3360 if (method in Function.prototype) {
3361 // 'in' is used instead of hasOwnProperty for nodejs v0.10
3362 // which is inconsistent on root prototypes. It is safe
3363 // here because Function.prototype is a root object
3364 return false;
3365 }
3366 return true;
3367}
3368
3369function isPlainObject (object) {
3370 return typeof object === 'object' && object && object.constructor === Object;
3371}
3372
3373var safeNativeProperties = {
3374 length: true,
3375 name: true
3376};
3377
3378var safeNativeMethods = {
3379 toString: true,
3380 valueOf: true,
3381 toLocaleString: true
3382};
3383
3384exports.getSafeProperty = getSafeProperty;
3385exports.setSafeProperty = setSafeProperty;
3386exports.isSafeProperty = isSafeProperty;
3387exports.validateSafeMethod = validateSafeMethod;
3388exports.isSafeMethod = isSafeMethod;
3389exports.isPlainObject = isPlainObject;
3390
3391
3392/***/ }),
3393/* 14 */
3394/***/ (function(module, exports, __webpack_require__) {
3395
3396"use strict";
3397
3398
3399function factory(type, config, load, typed) {
3400 var multiplyScalar = load(__webpack_require__(22));
3401
3402 /**
3403 * Divide two scalar values, `x / y`.
3404 * This function is meant for internal use: it is used by the public functions
3405 * `divide` and `inv`.
3406 *
3407 * This function does not support collections (Array or Matrix), and does
3408 * not validate the number of of inputs.
3409 *
3410 * @param {number | BigNumber | Fraction | Complex | Unit} x Numerator
3411 * @param {number | BigNumber | Fraction | Complex} y Denominator
3412 * @return {number | BigNumber | Fraction | Complex | Unit} Quotient, `x / y`
3413 * @private
3414 */
3415 var divideScalar = typed('divide', {
3416 'number, number': function (x, y) {
3417 return x / y;
3418 },
3419
3420 'Complex, Complex': function (x, y) {
3421 return x.div(y);
3422 },
3423
3424 'BigNumber, BigNumber': function (x, y) {
3425 return x.div(y);
3426 },
3427
3428 'Fraction, Fraction': function (x, y) {
3429 return x.div(y);
3430 },
3431
3432 'Unit, number | Fraction | BigNumber': function (x, y) {
3433 var res = x.clone();
3434 // TODO: move the divide function to Unit.js, it uses internals of Unit
3435 res.value = divideScalar(((res.value === null) ? res._normalize(1) : res.value), y);
3436 return res;
3437 },
3438
3439 'number | Fraction | BigNumber, Unit': function (x, y) {
3440 var res = y.pow(-1);
3441 // TODO: move the divide function to Unit.js, it uses internals of Unit
3442 res.value = multiplyScalar(((res.value === null) ? res._normalize(1) : res.value), x);
3443 return res;
3444 },
3445
3446 'Unit, Unit': function (x, y) {
3447 return x.divide(y);
3448 }
3449
3450 });
3451
3452 return divideScalar;
3453}
3454
3455exports.factory = factory;
3456
3457
3458/***/ }),
3459/* 15 */
3460/***/ (function(module, exports, __webpack_require__) {
3461
3462"use strict";
3463
3464
3465var keywords = __webpack_require__(77);
3466var deepEqual= __webpack_require__(5).deepEqual;
3467var hasOwnProperty = __webpack_require__(5).hasOwnProperty;
3468
3469function factory (type, config, load, typed, math) {
3470 var compile = load(__webpack_require__(7)).compile;
3471
3472 /**
3473 * Node
3474 */
3475 function Node() {
3476 if (!(this instanceof Node)) {
3477 throw new SyntaxError('Constructor must be called with the new operator');
3478 }
3479 }
3480
3481 /**
3482 * Evaluate the node
3483 * @param {Object} [scope] Scope to read/write variables
3484 * @return {*} Returns the result
3485 */
3486 Node.prototype.eval = function(scope) {
3487 return this.compile().eval(scope);
3488 };
3489
3490 Node.prototype.type = 'Node';
3491
3492 Node.prototype.isNode = true;
3493
3494 Node.prototype.comment = '';
3495
3496 /**
3497 * Compile the node to javascript code
3498 * @return {{eval: function}} expr Returns an object with a function 'eval',
3499 * which can be invoked as expr.eval([scope]),
3500 * where scope is an optional object with
3501 * variables.
3502 */
3503 Node.prototype.compile = function () {
3504 // TODO: calling compile(math) is deprecated since version 2.0.0. Remove this warning some day
3505 if (arguments.length > 0) {
3506 throw new Error('Calling compile(math) is deprecated. Call the function as compile() instead.');
3507 }
3508
3509 // definitions globally available inside the closure of the compiled expressions
3510 var defs = {
3511 math: math.expression.mathWithTransform,
3512 args: {}, // can be filled with names of FunctionAssignment arguments
3513 _validateScope: _validateScope
3514 };
3515
3516 // will be used to put local function arguments
3517 var args = {};
3518
3519 var code = compile(this, defs, args);
3520
3521 var defsCode = Object.keys(defs).map(function (name) {
3522 return ' var ' + name + ' = defs["' + name + '"];';
3523 });
3524
3525 var factoryCode =
3526 defsCode.join(' ') +
3527 'return {' +
3528 ' "eval": function (scope) {' +
3529 ' if (scope) _validateScope(scope);' +
3530 ' scope = scope || {};' +
3531 ' return ' + code + ';' +
3532 ' }' +
3533 '};';
3534
3535 var factory = new Function('defs', factoryCode);
3536 return factory(defs);
3537 };
3538
3539 /**
3540 * Execute a callback for each of the child nodes of this node
3541 * @param {function(child: Node, path: string, parent: Node)} callback
3542 */
3543 Node.prototype.forEach = function (callback) {
3544 // must be implemented by each of the Node implementations
3545 throw new Error('Cannot run forEach on a Node interface');
3546 };
3547
3548 /**
3549 * Create a new Node having it's childs be the results of calling
3550 * the provided callback function for each of the childs of the original node.
3551 * @param {function(child: Node, path: string, parent: Node): Node} callback
3552 * @returns {OperatorNode} Returns a transformed copy of the node
3553 */
3554 Node.prototype.map = function (callback) {
3555 // must be implemented by each of the Node implementations
3556 throw new Error('Cannot run map on a Node interface');
3557 };
3558
3559 /**
3560 * Validate whether an object is a Node, for use with map
3561 * @param {Node} node
3562 * @returns {Node} Returns the input if it's a node, else throws an Error
3563 * @protected
3564 */
3565 Node.prototype._ifNode = function (node) {
3566 if (!type.isNode(node)) {
3567 throw new TypeError('Callback function must return a Node');
3568 }
3569
3570 return node;
3571 };
3572
3573 /**
3574 * Recursively traverse all nodes in a node tree. Executes given callback for
3575 * this node and each of its child nodes.
3576 * @param {function(node: Node, path: string, parent: Node)} callback
3577 * A callback called for every node in the node tree.
3578 */
3579 Node.prototype.traverse = function (callback) {
3580 // execute callback for itself
3581 callback(this, null, null);
3582
3583 // recursively traverse over all childs of a node
3584 function _traverse(node, callback) {
3585 node.forEach(function (child, path, parent) {
3586 callback(child, path, parent);
3587 _traverse(child, callback);
3588 });
3589 }
3590
3591 _traverse(this, callback);
3592 };
3593
3594 /**
3595 * Recursively transform a node tree via a transform function.
3596 *
3597 * For example, to replace all nodes of type SymbolNode having name 'x' with a
3598 * ConstantNode with value 2:
3599 *
3600 * var res = Node.transform(function (node, path, parent) {
3601 * if (node && node.isSymbolNode) && (node.name == 'x')) {
3602 * return new ConstantNode(2);
3603 * }
3604 * else {
3605 * return node;
3606 * }
3607 * });
3608 *
3609 * @param {function(node: Node, path: string, parent: Node) : Node} callback
3610 * A mapping function accepting a node, and returning
3611 * a replacement for the node or the original node.
3612 * Signature: callback(node: Node, index: string, parent: Node) : Node
3613 * @return {Node} Returns the original node or its replacement
3614 */
3615 Node.prototype.transform = function (callback) {
3616 // traverse over all childs
3617 function _transform (node, callback) {
3618 return node.map(function(child, path, parent) {
3619 var replacement = callback(child, path, parent);
3620 return _transform(replacement, callback);
3621 });
3622 }
3623
3624 var replacement = callback(this, null, null);
3625 return _transform(replacement, callback);
3626 };
3627
3628 /**
3629 * Find any node in the node tree matching given filter function. For example, to
3630 * find all nodes of type SymbolNode having name 'x':
3631 *
3632 * var results = Node.filter(function (node) {
3633 * return (node && node.isSymbolNode) && (node.name == 'x');
3634 * });
3635 *
3636 * @param {function(node: Node, path: string, parent: Node) : Node} callback
3637 * A test function returning true when a node matches, and false
3638 * otherwise. Function signature:
3639 * callback(node: Node, index: string, parent: Node) : boolean
3640 * @return {Node[]} nodes An array with nodes matching given filter criteria
3641 */
3642 Node.prototype.filter = function (callback) {
3643 var nodes = [];
3644
3645 this.traverse(function (node, path, parent) {
3646 if (callback(node, path, parent)) {
3647 nodes.push(node);
3648 }
3649 });
3650
3651 return nodes;
3652 };
3653
3654 // TODO: deprecated since version 1.1.0, remove this some day
3655 Node.prototype.find = function () {
3656 throw new Error('Function Node.find is deprecated. Use Node.filter instead.');
3657 };
3658
3659 // TODO: deprecated since version 1.1.0, remove this some day
3660 Node.prototype.match = function () {
3661 throw new Error('Function Node.match is deprecated. See functions Node.filter, Node.transform, Node.traverse.');
3662 };
3663
3664 /**
3665 * Create a shallow clone of this node
3666 * @return {Node}
3667 */
3668 Node.prototype.clone = function () {
3669 // must be implemented by each of the Node implementations
3670 throw new Error('Cannot clone a Node interface');
3671 };
3672
3673 /**
3674 * Create a deep clone of this node
3675 * @return {Node}
3676 */
3677 Node.prototype.cloneDeep = function () {
3678 return this.map(function (node) {
3679 return node.cloneDeep();
3680 });
3681 };
3682
3683 /**
3684 * Deep compare this node with another node.
3685 * @param {Node} other
3686 * @return {boolean} Returns true when both nodes are of the same type and
3687 * contain the same values (as do their childs)
3688 */
3689 Node.prototype.equals = function (other) {
3690 return other
3691 ? deepEqual(this, other)
3692 : false
3693 };
3694
3695 /**
3696 * Get string representation. (wrapper function)
3697 *
3698 * This function can get an object of the following form:
3699 * {
3700 * handler: //This can be a callback function of the form
3701 * // "function callback(node, options)"or
3702 * // a map that maps function names (used in FunctionNodes)
3703 * // to callbacks
3704 * parenthesis: "keep" //the parenthesis option (This is optional)
3705 * }
3706 *
3707 * @param {Object} [options]
3708 * @return {string}
3709 */
3710 Node.prototype.toString = function (options) {
3711 var customString;
3712 if (options && typeof options === 'object') {
3713 switch (typeof options.handler) {
3714 case 'object':
3715 case 'undefined':
3716 break;
3717 case 'function':
3718 customString = options.handler(this, options);
3719 break;
3720 default:
3721 throw new TypeError('Object or function expected as callback');
3722 }
3723 }
3724
3725 if (typeof customString !== 'undefined') {
3726 return customString;
3727 }
3728
3729 return this._toString(options);
3730 };
3731
3732 /**
3733 * Get HTML representation. (wrapper function)
3734 *
3735 * This function can get an object of the following form:
3736 * {
3737 * handler: //This can be a callback function of the form
3738 * // "function callback(node, options)" or
3739 * // a map that maps function names (used in FunctionNodes)
3740 * // to callbacks
3741 * parenthesis: "keep" //the parenthesis option (This is optional)
3742 * }
3743 *
3744 * @param {Object} [options]
3745 * @return {string}
3746 */
3747 Node.prototype.toHTML = function (options) {
3748 var customString;
3749 if (options && typeof options === 'object') {
3750 switch (typeof options.handler) {
3751 case 'object':
3752 case 'undefined':
3753 break;
3754 case 'function':
3755 customString = options.handler(this, options);
3756 break;
3757 default:
3758 throw new TypeError('Object or function expected as callback');
3759 }
3760 }
3761
3762 if (typeof customString !== 'undefined') {
3763 return customString;
3764 }
3765
3766 return this.toHTML(options);
3767 };
3768
3769 /**
3770 * Internal function to generate the string output.
3771 * This has to be implemented by every Node
3772 *
3773 * @throws {Error}
3774 */
3775 Node.prototype._toString = function () {
3776 //must be implemented by each of the Node implementations
3777 throw new Error('_toString not implemented for ' + this.type);
3778 };
3779
3780 /**
3781 * Get LaTeX representation. (wrapper function)
3782 *
3783 * This function can get an object of the following form:
3784 * {
3785 * handler: //This can be a callback function of the form
3786 * // "function callback(node, options)"or
3787 * // a map that maps function names (used in FunctionNodes)
3788 * // to callbacks
3789 * parenthesis: "keep" //the parenthesis option (This is optional)
3790 * }
3791 *
3792 * @param {Object} [options]
3793 * @return {string}
3794 */
3795 Node.prototype.toTex = function (options) {
3796 var customTex;
3797 if (options && typeof options == 'object') {
3798 switch (typeof options.handler) {
3799 case 'object':
3800 case 'undefined':
3801 break;
3802 case 'function':
3803 customTex = options.handler(this, options);
3804 break;
3805 default:
3806 throw new TypeError('Object or function expected as callback');
3807 }
3808 }
3809
3810 if (typeof customTex !== 'undefined') {
3811 return customTex;
3812 }
3813
3814 return this._toTex(options);
3815 };
3816
3817 /**
3818 * Internal function to generate the LaTeX output.
3819 * This has to be implemented by every Node
3820 *
3821 * @param {Object} [options]
3822 * @throws {Error}
3823 */
3824 Node.prototype._toTex = function (options) {
3825 //must be implemented by each of the Node implementations
3826 throw new Error('_toTex not implemented for ' + this.type);
3827 };
3828
3829 /**
3830 * Get identifier.
3831 * @return {string}
3832 */
3833 Node.prototype.getIdentifier = function () {
3834 return this.type;
3835 };
3836
3837 /**
3838 * Get the content of the current Node.
3839 * @return {Node} node
3840 **/
3841 Node.prototype.getContent = function () {
3842 return this;
3843 };
3844
3845 /**
3846 * Validate the symbol names of a scope.
3847 * Throws an error when the scope contains an illegal symbol.
3848 * @param {Object} scope
3849 */
3850 function _validateScope(scope) {
3851 for (var symbol in scope) {
3852 if (hasOwnProperty(scope, symbol)) {
3853 if (symbol in keywords) {
3854 throw new Error('Scope contains an illegal symbol, "' + symbol + '" is a reserved keyword');
3855 }
3856 }
3857 }
3858 }
3859
3860 return Node;
3861}
3862
3863exports.name = 'Node';
3864exports.path = 'expression.node';
3865exports.math = true; // request access to the math namespace as 5th argument of the factory function
3866exports.factory = factory;
3867
3868
3869/***/ }),
3870/* 16 */
3871/***/ (function(module, exports, __webpack_require__) {
3872
3873"use strict";
3874
3875
3876function factory(type, config, load, typed) {
3877
3878 /**
3879 * Add two scalar values, `x + y`.
3880 * This function is meant for internal use: it is used by the public function
3881 * `add`
3882 *
3883 * This function does not support collections (Array or Matrix), and does
3884 * not validate the number of of inputs.
3885 *
3886 * @param {number | BigNumber | Fraction | Complex | Unit} x First value to add
3887 * @param {number | BigNumber | Fraction | Complex} y Second value to add
3888 * @return {number | BigNumber | Fraction | Complex | Unit} Sum of `x` and `y`
3889 * @private
3890 */
3891 var add = typed('add', {
3892
3893 'number, number': function (x, y) {
3894 return x + y;
3895 },
3896
3897 'Complex, Complex': function (x, y) {
3898 return x.add(y);
3899 },
3900
3901 'BigNumber, BigNumber': function (x, y) {
3902 return x.plus(y);
3903 },
3904
3905 'Fraction, Fraction': function (x, y) {
3906 return x.add(y);
3907 },
3908
3909 'Unit, Unit': function (x, y) {
3910 if (x.value == null) throw new Error('Parameter x contains a unit with undefined value');
3911 if (y.value == null) throw new Error('Parameter y contains a unit with undefined value');
3912 if (!x.equalBase(y)) throw new Error('Units do not match');
3913
3914 var res = x.clone();
3915 res.value = add(res.value, y.value);
3916 res.fixPrefix = false;
3917 return res;
3918 }
3919 });
3920
3921 return add;
3922}
3923
3924exports.factory = factory;
3925
3926
3927/***/ }),
3928/* 17 */
3929/***/ (function(module, exports, __webpack_require__) {
3930
3931"use strict";
3932
3933
3934var DimensionError = __webpack_require__(11);
3935
3936function factory (type, config, load, typed) {
3937
3938 var DenseMatrix = type.DenseMatrix;
3939
3940 /**
3941 * Iterates over SparseMatrix items and invokes the callback function f(Dij, Sij).
3942 * Callback function invoked M*N times.
3943 *
3944 *
3945 * ┌ f(Dij, Sij) ; S(i,j) !== 0
3946 * C(i,j) = ┤
3947 * └ f(Dij, 0) ; otherwise
3948 *
3949 *
3950 * @param {Matrix} denseMatrix The DenseMatrix instance (D)
3951 * @param {Matrix} sparseMatrix The SparseMatrix instance (C)
3952 * @param {Function} callback The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j)
3953 * @param {boolean} inverse A true value indicates callback should be invoked f(Sij,Dij)
3954 *
3955 * @return {Matrix} DenseMatrix (C)
3956 *
3957 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571
3958 */
3959 var algorithm03 = function (denseMatrix, sparseMatrix, callback, inverse) {
3960 // dense matrix arrays
3961 var adata = denseMatrix._data;
3962 var asize = denseMatrix._size;
3963 var adt = denseMatrix._datatype;
3964 // sparse matrix arrays
3965 var bvalues = sparseMatrix._values;
3966 var bindex = sparseMatrix._index;
3967 var bptr = sparseMatrix._ptr;
3968 var bsize = sparseMatrix._size;
3969 var bdt = sparseMatrix._datatype;
3970
3971 // validate dimensions
3972 if (asize.length !== bsize.length)
3973 throw new DimensionError(asize.length, bsize.length);
3974
3975 // check rows & columns
3976 if (asize[0] !== bsize[0] || asize[1] !== bsize[1])
3977 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
3978
3979 // sparse matrix cannot be a Pattern matrix
3980 if (!bvalues)
3981 throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix');
3982
3983 // rows & columns
3984 var rows = asize[0];
3985 var columns = asize[1];
3986
3987 // datatype
3988 var dt;
3989 // zero value
3990 var zero = 0;
3991 // callback signature to use
3992 var cf = callback;
3993
3994 // process data types
3995 if (typeof adt === 'string' && adt === bdt) {
3996 // datatype
3997 dt = adt;
3998 // convert 0 to the same datatype
3999 zero = typed.convert(0, dt);
4000 // callback
4001 cf = typed.find(callback, [dt, dt]);
4002 }
4003
4004 // result (DenseMatrix)
4005 var cdata = [];
4006
4007 // initialize dense matrix
4008 for (var z = 0; z < rows; z++) {
4009 // initialize row
4010 cdata[z] = [];
4011 }
4012
4013 // workspace
4014 var x = [];
4015 // marks indicating we have a value in x for a given column
4016 var w = [];
4017
4018 // loop columns in b
4019 for (var j = 0; j < columns; j++) {
4020 // column mark
4021 var mark = j + 1;
4022 // values in column j
4023 for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
4024 // row
4025 var i = bindex[k];
4026 // update workspace
4027 x[i] = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]);
4028 w[i] = mark;
4029 }
4030 // process workspace
4031 for (var y = 0; y < rows; y++) {
4032 // check we have a calculated value for current row
4033 if (w[y] === mark) {
4034 // use calculated value
4035 cdata[y][j] = x[y];
4036 }
4037 else {
4038 // calculate value
4039 cdata[y][j] = inverse ? cf(zero, adata[y][j]) : cf(adata[y][j], zero);
4040 }
4041 }
4042 }
4043
4044 // return dense matrix
4045 return new DenseMatrix({
4046 data: cdata,
4047 size: [rows, columns],
4048 datatype: dt
4049 });
4050 };
4051
4052 return algorithm03;
4053}
4054
4055exports.name = 'algorithm03';
4056exports.factory = factory;
4057
4058
4059/***/ }),
4060/* 18 */
4061/***/ (function(module, exports, __webpack_require__) {
4062
4063"use strict";
4064
4065
4066function factory (type, config, load, typed) {
4067
4068 var DenseMatrix = type.DenseMatrix;
4069
4070 /**
4071 * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b).
4072 * Callback function invoked MxN times.
4073 *
4074 *
4075 * ┌ f(Sij, b) ; S(i,j) !== 0
4076 * C(i,j) = ┤
4077 * └ f(0, b) ; otherwise
4078 *
4079 *
4080 * @param {Matrix} s The SparseMatrix instance (S)
4081 * @param {Scalar} b The Scalar value
4082 * @param {Function} callback The f(Aij,b) operation to invoke
4083 * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij)
4084 *
4085 * @return {Matrix} DenseMatrix (C)
4086 *
4087 * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813
4088 */
4089 var algorithm12 = function (s, b, callback, inverse) {
4090 // sparse matrix arrays
4091 var avalues = s._values;
4092 var aindex = s._index;
4093 var aptr = s._ptr;
4094 var asize = s._size;
4095 var adt = s._datatype;
4096
4097 // sparse matrix cannot be a Pattern matrix
4098 if (!avalues)
4099 throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value');
4100
4101 // rows & columns
4102 var rows = asize[0];
4103 var columns = asize[1];
4104
4105 // datatype
4106 var dt;
4107 // callback signature to use
4108 var cf = callback;
4109
4110 // process data types
4111 if (typeof adt === 'string') {
4112 // datatype
4113 dt = adt;
4114 // convert b to the same datatype
4115 b = typed.convert(b, dt);
4116 // callback
4117 cf = typed.find(callback, [dt, dt]);
4118 }
4119
4120 // result arrays
4121 var cdata = [];
4122 // matrix
4123 var c = new DenseMatrix({
4124 data: cdata,
4125 size: [rows, columns],
4126 datatype: dt
4127 });
4128
4129 // workspaces
4130 var x = [];
4131 // marks indicating we have a value in x for a given column
4132 var w = [];
4133
4134 // loop columns
4135 for (var j = 0; j < columns; j++) {
4136 // columns mark
4137 var mark = j + 1;
4138 // values in j
4139 for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
4140 // row
4141 var r = aindex[k];
4142 // update workspace
4143 x[r] = avalues[k];
4144 w[r] = mark;
4145 }
4146 // loop rows
4147 for (var i = 0; i < rows; i++) {
4148 // initialize C on first column
4149 if (j === 0) {
4150 // create row array
4151 cdata[i] = [];
4152 }
4153 // check sparse matrix has a value @ i,j
4154 if (w[i] === mark) {
4155 // invoke callback, update C
4156 cdata[i][j] = inverse ? cf(b, x[i]) : cf(x[i], b);
4157 }
4158 else {
4159 // dense matrix value @ i, j
4160 cdata[i][j] = inverse ? cf(b, 0) : cf(0, b);
4161 }
4162 }
4163 }
4164
4165 // return sparse matrix
4166 return c;
4167 };
4168
4169 return algorithm12;
4170}
4171
4172exports.name = 'algorithm12';
4173exports.factory = factory;
4174
4175
4176/***/ }),
4177/* 19 */
4178/***/ (function(module, exports, __webpack_require__) {
4179
4180"use strict";
4181
4182
4183function factory (type, config, load, typed) {
4184
4185 var equalScalar = load(__webpack_require__(10));
4186
4187 var SparseMatrix = type.SparseMatrix;
4188
4189 /**
4190 * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b).
4191 * Callback function invoked NZ times (number of nonzero items in S).
4192 *
4193 *
4194 * ┌ f(Sij, b) ; S(i,j) !== 0
4195 * C(i,j) = ┤
4196 * └ 0 ; otherwise
4197 *
4198 *
4199 * @param {Matrix} s The SparseMatrix instance (S)
4200 * @param {Scalar} b The Scalar value
4201 * @param {Function} callback The f(Aij,b) operation to invoke
4202 * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij)
4203 *
4204 * @return {Matrix} SparseMatrix (C)
4205 *
4206 * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813
4207 */
4208 var algorithm11 = function (s, b, callback, inverse) {
4209 // sparse matrix arrays
4210 var avalues = s._values;
4211 var aindex = s._index;
4212 var aptr = s._ptr;
4213 var asize = s._size;
4214 var adt = s._datatype;
4215
4216 // sparse matrix cannot be a Pattern matrix
4217 if (!avalues)
4218 throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value');
4219
4220 // rows & columns
4221 var rows = asize[0];
4222 var columns = asize[1];
4223
4224 // datatype
4225 var dt;
4226 // equal signature to use
4227 var eq = equalScalar;
4228 // zero value
4229 var zero = 0;
4230 // callback signature to use
4231 var cf = callback;
4232
4233 // process data types
4234 if (typeof adt === 'string') {
4235 // datatype
4236 dt = adt;
4237 // find signature that matches (dt, dt)
4238 eq = typed.find(equalScalar, [dt, dt]);
4239 // convert 0 to the same datatype
4240 zero = typed.convert(0, dt);
4241 // convert b to the same datatype
4242 b = typed.convert(b, dt);
4243 // callback
4244 cf = typed.find(callback, [dt, dt]);
4245 }
4246
4247 // result arrays
4248 var cvalues = [];
4249 var cindex = [];
4250 var cptr = [];
4251 // matrix
4252 var c = new SparseMatrix({
4253 values: cvalues,
4254 index: cindex,
4255 ptr: cptr,
4256 size: [rows, columns],
4257 datatype: dt
4258 });
4259
4260 // loop columns
4261 for (var j = 0; j < columns; j++) {
4262 // initialize ptr
4263 cptr[j] = cindex.length;
4264 // values in j
4265 for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
4266 // row
4267 var i = aindex[k];
4268 // invoke callback
4269 var v = inverse ? cf(b, avalues[k]) : cf(avalues[k], b);
4270 // check value is zero
4271 if (!eq(v, zero)) {
4272 // push index & value
4273 cindex.push(i);
4274 cvalues.push(v);
4275 }
4276 }
4277 }
4278 // update ptr
4279 cptr[columns] = cindex.length;
4280
4281 // return sparse matrix
4282 return c;
4283 };
4284
4285 return algorithm11;
4286}
4287
4288exports.name = 'algorithm11';
4289exports.factory = factory;
4290
4291
4292/***/ }),
4293/* 20 */
4294/***/ (function(module, exports, __webpack_require__) {
4295
4296"use strict";
4297
4298
4299var extend = __webpack_require__(5).extend;
4300
4301function factory (type, config, load, typed) {
4302
4303 var matrix = load(__webpack_require__(0));
4304 var addScalar = load(__webpack_require__(16));
4305 var latex = __webpack_require__(4);
4306
4307 var algorithm01 = load(__webpack_require__(33));
4308 var algorithm04 = load(__webpack_require__(73));
4309 var algorithm10 = load(__webpack_require__(38));
4310 var algorithm13 = load(__webpack_require__(8));
4311 var algorithm14 = load(__webpack_require__(6));
4312
4313 /**
4314 * Add two or more values, `x + y`.
4315 * For matrices, the function is evaluated element wise.
4316 *
4317 * Syntax:
4318 *
4319 * math.add(x, y)
4320 * math.add(x, y, z, ...)
4321 *
4322 * Examples:
4323 *
4324 * math.add(2, 3); // returns number 5
4325 * math.add(2, 3, 4); // returns number 9
4326 *
4327 * var a = math.complex(2, 3);
4328 * var b = math.complex(-4, 1);
4329 * math.add(a, b); // returns Complex -2 + 4i
4330 *
4331 * math.add([1, 2, 3], 4); // returns Array [5, 6, 7]
4332 *
4333 * var c = math.unit('5 cm');
4334 * var d = math.unit('2.1 mm');
4335 * math.add(c, d); // returns Unit 52.1 mm
4336 *
4337 * math.add("2.3", "4"); // returns number 6.3
4338 *
4339 * See also:
4340 *
4341 * subtract, sum
4342 *
4343 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First value to add
4344 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second value to add
4345 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Sum of `x` and `y`
4346 */
4347 var add = typed('add', extend({
4348 // we extend the signatures of addScalar with signatures dealing with matrices
4349
4350 'Matrix, Matrix': function (x, y) {
4351 // result
4352 var c;
4353
4354 // process matrix storage
4355 switch (x.storage()) {
4356 case 'sparse':
4357 switch (y.storage()) {
4358 case 'sparse':
4359 // sparse + sparse
4360 c = algorithm04(x, y, addScalar);
4361 break;
4362 default:
4363 // sparse + dense
4364 c = algorithm01(y, x, addScalar, true);
4365 break;
4366 }
4367 break;
4368 default:
4369 switch (y.storage()) {
4370 case 'sparse':
4371 // dense + sparse
4372 c = algorithm01(x, y, addScalar, false);
4373 break;
4374 default:
4375 // dense + dense
4376 c = algorithm13(x, y, addScalar);
4377 break;
4378 }
4379 break;
4380 }
4381 return c;
4382 },
4383
4384 'Array, Array': function (x, y) {
4385 // use matrix implementation
4386 return add(matrix(x), matrix(y)).valueOf();
4387 },
4388
4389 'Array, Matrix': function (x, y) {
4390 // use matrix implementation
4391 return add(matrix(x), y);
4392 },
4393
4394 'Matrix, Array': function (x, y) {
4395 // use matrix implementation
4396 return add(x, matrix(y));
4397 },
4398
4399 'Matrix, any': function (x, y) {
4400 // result
4401 var c;
4402 // check storage format
4403 switch (x.storage()) {
4404 case 'sparse':
4405 c = algorithm10(x, y, addScalar, false);
4406 break;
4407 default:
4408 c = algorithm14(x, y, addScalar, false);
4409 break;
4410 }
4411 return c;
4412 },
4413
4414 'any, Matrix': function (x, y) {
4415 // result
4416 var c;
4417 // check storage format
4418 switch (y.storage()) {
4419 case 'sparse':
4420 c = algorithm10(y, x, addScalar, true);
4421 break;
4422 default:
4423 c = algorithm14(y, x, addScalar, true);
4424 break;
4425 }
4426 return c;
4427 },
4428
4429 'Array, any': function (x, y) {
4430 // use matrix implementation
4431 return algorithm14(matrix(x), y, addScalar, false).valueOf();
4432 },
4433
4434 'any, Array': function (x, y) {
4435 // use matrix implementation
4436 return algorithm14(matrix(y), x, addScalar, true).valueOf();
4437 },
4438
4439 'any, any': addScalar,
4440
4441 'Array | Matrix | any, Array | Matrix | any, ...any': function (x, y, rest) {
4442 var result = add(x, y);
4443
4444 for (var i = 0; i < rest.length; i++) {
4445 result = add(result, rest[i]);
4446 }
4447
4448 return result;
4449 }
4450 }, addScalar.signatures));
4451
4452 add.toTex = {
4453 2: '\\left(${args[0]}' + latex.operators['add'] + '${args[1]}\\right)'
4454 };
4455
4456 return add;
4457}
4458
4459exports.name = 'add';
4460exports.factory = factory;
4461
4462
4463/***/ }),
4464/* 21 */
4465/***/ (function(module, exports, __webpack_require__) {
4466
4467"use strict";
4468
4469
4470var DimensionError = __webpack_require__(11);
4471
4472function factory (type, config, load, typed) {
4473 var latex = __webpack_require__(4);
4474
4475 var matrix = load(__webpack_require__(0));
4476 var addScalar = load(__webpack_require__(16));
4477 var unaryMinus = load(__webpack_require__(35));
4478
4479 var algorithm01 = load(__webpack_require__(33));
4480 var algorithm03 = load(__webpack_require__(17));
4481 var algorithm05 = load(__webpack_require__(61));
4482 var algorithm10 = load(__webpack_require__(38));
4483 var algorithm13 = load(__webpack_require__(8));
4484 var algorithm14 = load(__webpack_require__(6));
4485
4486 // TODO: split function subtract in two: subtract and subtractScalar
4487
4488 /**
4489 * Subtract two values, `x - y`.
4490 * For matrices, the function is evaluated element wise.
4491 *
4492 * Syntax:
4493 *
4494 * math.subtract(x, y)
4495 *
4496 * Examples:
4497 *
4498 * math.subtract(5.3, 2); // returns number 3.3
4499 *
4500 * var a = math.complex(2, 3);
4501 * var b = math.complex(4, 1);
4502 * math.subtract(a, b); // returns Complex -2 + 2i
4503 *
4504 * math.subtract([5, 7, 4], 4); // returns Array [1, 3, 0]
4505 *
4506 * var c = math.unit('2.1 km');
4507 * var d = math.unit('500m');
4508 * math.subtract(c, d); // returns Unit 1.6 km
4509 *
4510 * See also:
4511 *
4512 * add
4513 *
4514 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x
4515 * Initial value
4516 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y
4517 * Value to subtract from `x`
4518 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix}
4519 * Subtraction of `x` and `y`
4520 */
4521 var subtract = typed('subtract', {
4522
4523 'number, number': function (x, y) {
4524 return x - y;
4525 },
4526
4527 'Complex, Complex': function (x, y) {
4528 return x.sub(y);
4529 },
4530
4531 'BigNumber, BigNumber': function (x, y) {
4532 return x.minus(y);
4533 },
4534
4535 'Fraction, Fraction': function (x, y) {
4536 return x.sub(y);
4537 },
4538
4539 'Unit, Unit': function (x, y) {
4540 if (x.value == null) {
4541 throw new Error('Parameter x contains a unit with undefined value');
4542 }
4543
4544 if (y.value == null) {
4545 throw new Error('Parameter y contains a unit with undefined value');
4546 }
4547
4548 if (!x.equalBase(y)) {
4549 throw new Error('Units do not match');
4550 }
4551
4552 var res = x.clone();
4553 res.value = subtract(res.value, y.value);
4554 res.fixPrefix = false;
4555
4556 return res;
4557 },
4558
4559 'Matrix, Matrix': function (x, y) {
4560 // matrix sizes
4561 var xsize = x.size();
4562 var ysize = y.size();
4563
4564 // check dimensions
4565 if (xsize.length !== ysize.length)
4566 throw new DimensionError(xsize.length, ysize.length);
4567
4568 // result
4569 var c;
4570
4571 // process matrix storage
4572 switch (x.storage()) {
4573 case 'sparse':
4574 switch (y.storage()) {
4575 case 'sparse':
4576 // sparse - sparse
4577 c = algorithm05(x, y, subtract);
4578 break;
4579 default:
4580 // sparse - dense
4581 c = algorithm03(y, x, subtract, true);
4582 break;
4583 }
4584 break;
4585 default:
4586 switch (y.storage()) {
4587 case 'sparse':
4588 // dense - sparse
4589 c = algorithm01(x, y, subtract, false);
4590 break;
4591 default:
4592 // dense - dense
4593 c = algorithm13(x, y, subtract);
4594 break;
4595 }
4596 break;
4597 }
4598 return c;
4599 },
4600
4601 'Array, Array': function (x, y) {
4602 // use matrix implementation
4603 return subtract(matrix(x), matrix(y)).valueOf();
4604 },
4605
4606 'Array, Matrix': function (x, y) {
4607 // use matrix implementation
4608 return subtract(matrix(x), y);
4609 },
4610
4611 'Matrix, Array': function (x, y) {
4612 // use matrix implementation
4613 return subtract(x, matrix(y));
4614 },
4615
4616 'Matrix, any': function (x, y) {
4617 // result
4618 var c;
4619 // check storage format
4620 switch (x.storage()) {
4621 case 'sparse':
4622 // algorithm 7 is faster than 9 since it calls f() for nonzero items only!
4623 c = algorithm10(x, unaryMinus(y), addScalar);
4624 break;
4625 default:
4626 c = algorithm14(x, y, subtract);
4627 break;
4628 }
4629 return c;
4630 },
4631
4632 'any, Matrix': function (x, y) {
4633 // result
4634 var c;
4635 // check storage format
4636 switch (y.storage()) {
4637 case 'sparse':
4638 c = algorithm10(y, x, subtract, true);
4639 break;
4640 default:
4641 c = algorithm14(y, x, subtract, true);
4642 break;
4643 }
4644 return c;
4645 },
4646
4647 'Array, any': function (x, y) {
4648 // use matrix implementation
4649 return algorithm14(matrix(x), y, subtract, false).valueOf();
4650 },
4651
4652 'any, Array': function (x, y) {
4653 // use matrix implementation
4654 return algorithm14(matrix(y), x, subtract, true).valueOf();
4655 }
4656 });
4657
4658 subtract.toTex = {
4659 2: '\\left(${args[0]}' + latex.operators['subtract'] + '${args[1]}\\right)'
4660 };
4661
4662 return subtract;
4663}
4664
4665exports.name = 'subtract';
4666exports.factory = factory;
4667
4668
4669/***/ }),
4670/* 22 */
4671/***/ (function(module, exports, __webpack_require__) {
4672
4673"use strict";
4674
4675
4676function factory(type, config, load, typed) {
4677
4678 /**
4679 * Multiply two scalar values, `x * y`.
4680 * This function is meant for internal use: it is used by the public function
4681 * `multiply`
4682 *
4683 * This function does not support collections (Array or Matrix), and does
4684 * not validate the number of of inputs.
4685 *
4686 * @param {number | BigNumber | Fraction | Complex | Unit} x First value to multiply
4687 * @param {number | BigNumber | Fraction | Complex} y Second value to multiply
4688 * @return {number | BigNumber | Fraction | Complex | Unit} Multiplication of `x` and `y`
4689 * @private
4690 */
4691 var multiplyScalar = typed('multiplyScalar', {
4692
4693 'number, number': function (x, y) {
4694 return x * y;
4695 },
4696
4697 'Complex, Complex': function (x, y) {
4698 return x.mul(y);
4699 },
4700
4701 'BigNumber, BigNumber': function (x, y) {
4702 return x.times(y);
4703 },
4704
4705 'Fraction, Fraction': function (x, y) {
4706 return x.mul(y);
4707 },
4708
4709 'number | Fraction | BigNumber | Complex, Unit': function (x, y) {
4710 var res = y.clone();
4711 res.value = (res.value === null) ? res._normalize(x) : multiplyScalar(res.value, x);
4712 return res;
4713 },
4714
4715 'Unit, number | Fraction | BigNumber | Complex': function (x, y) {
4716 var res = x.clone();
4717 res.value = (res.value === null) ? res._normalize(y) : multiplyScalar(res.value, y);
4718 return res;
4719 },
4720
4721 'Unit, Unit': function (x, y) {
4722 return x.multiply(y);
4723 }
4724
4725 });
4726
4727 return multiplyScalar;
4728}
4729
4730exports.factory = factory;
4731
4732
4733/***/ }),
4734/* 23 */
4735/***/ (function(module, exports, __webpack_require__) {
4736
4737"use strict";
4738
4739
4740var clone = __webpack_require__(5).clone;
4741var validateIndex = __webpack_require__(2).validateIndex;
4742var getSafeProperty = __webpack_require__(13).getSafeProperty;
4743var setSafeProperty = __webpack_require__(13).setSafeProperty;
4744var DimensionError = __webpack_require__(11);
4745
4746function factory (type, config, load, typed) {
4747 var matrix = load(__webpack_require__(0));
4748
4749 /**
4750 * Get or set a subset of a matrix or string.
4751 *
4752 * Syntax:
4753 * math.subset(value, index) // retrieve a subset
4754 * math.subset(value, index, replacement [, defaultValue]) // replace a subset
4755 *
4756 * Examples:
4757 *
4758 * // get a subset
4759 * var d = [[1, 2], [3, 4]];
4760 * math.subset(d, math.index(1, 0)); // returns 3
4761 * math.subset(d, math.index([0, 2], 1)); // returns [[2], [4]]
4762 *
4763 * // replace a subset
4764 * var e = [];
4765 * var f = math.subset(e, math.index(0, [0, 2]), [5, 6]); // f = [[5, 6]]
4766 * var g = math.subset(f, math.index(1, 1), 7, 0); // g = [[5, 6], [0, 7]]
4767 *
4768 * See also:
4769 *
4770 * size, resize, squeeze, index
4771 *
4772 * @param {Array | Matrix | string} matrix An array, matrix, or string
4773 * @param {Index} index An index containing ranges for each
4774 * dimension
4775 * @param {*} [replacement] An array, matrix, or scalar.
4776 * If provided, the subset is replaced with replacement.
4777 * If not provided, the subset is returned
4778 * @param {*} [defaultValue=undefined] Default value, filled in on new entries when
4779 * the matrix is resized. If not provided,
4780 * math.matrix elements will be left undefined.
4781 * @return {Array | Matrix | string} Either the retrieved subset or the updated matrix.
4782 */
4783 var subset = typed('subset', {
4784 // get subset
4785 'Array, Index': function (value, index) {
4786 var m = matrix(value);
4787 var subset = m.subset(index); // returns a Matrix
4788 return index.isScalar()
4789 ? subset
4790 : subset.valueOf(); // return an Array (like the input)
4791 },
4792
4793 'Matrix, Index': function (value, index) {
4794 return value.subset(index);
4795 },
4796
4797 'Object, Index': _getObjectProperty,
4798
4799 'string, Index': _getSubstring,
4800
4801 // set subset
4802 'Array, Index, any': function (value, index, replacement) {
4803 return matrix(clone(value))
4804 .subset(index, replacement, undefined)
4805 .valueOf();
4806 },
4807
4808 'Array, Index, any, any': function (value, index, replacement, defaultValue) {
4809 return matrix(clone(value))
4810 .subset(index, replacement, defaultValue)
4811 .valueOf();
4812 },
4813
4814 'Matrix, Index, any': function (value, index, replacement) {
4815 return value.clone().subset(index, replacement);
4816 },
4817
4818 'Matrix, Index, any, any': function (value, index, replacement, defaultValue) {
4819 return value.clone().subset(index, replacement, defaultValue);
4820 },
4821
4822 'string, Index, string': _setSubstring,
4823 'string, Index, string, string': _setSubstring,
4824 'Object, Index, any': _setObjectProperty
4825 });
4826
4827 subset.toTex = undefined; // use default template
4828
4829 return subset;
4830
4831 /**
4832 * Retrieve a subset of a string
4833 * @param {string} str string from which to get a substring
4834 * @param {Index} index An index containing ranges for each dimension
4835 * @returns {string} substring
4836 * @private
4837 */
4838 function _getSubstring(str, index) {
4839 if (!type.isIndex(index)) {
4840 // TODO: better error message
4841 throw new TypeError('Index expected');
4842 }
4843 if (index.size().length != 1) {
4844 throw new DimensionError(index.size().length, 1);
4845 }
4846
4847 // validate whether the range is out of range
4848 var strLen = str.length;
4849 validateIndex(index.min()[0], strLen);
4850 validateIndex(index.max()[0], strLen);
4851
4852 var range = index.dimension(0);
4853
4854 var substr = '';
4855 range.forEach(function (v) {
4856 substr += str.charAt(v);
4857 });
4858
4859 return substr;
4860 }
4861
4862 /**
4863 * Replace a substring in a string
4864 * @param {string} str string to be replaced
4865 * @param {Index} index An index containing ranges for each dimension
4866 * @param {string} replacement Replacement string
4867 * @param {string} [defaultValue] Default value to be uses when resizing
4868 * the string. is ' ' by default
4869 * @returns {string} result
4870 * @private
4871 */
4872 function _setSubstring(str, index, replacement, defaultValue) {
4873 if (!index || index.isIndex !== true) {
4874 // TODO: better error message
4875 throw new TypeError('Index expected');
4876 }
4877 if (index.size().length != 1) {
4878 throw new DimensionError(index.size().length, 1);
4879 }
4880 if (defaultValue !== undefined) {
4881 if (typeof defaultValue !== 'string' || defaultValue.length !== 1) {
4882 throw new TypeError('Single character expected as defaultValue');
4883 }
4884 }
4885 else {
4886 defaultValue = ' ';
4887 }
4888
4889 var range = index.dimension(0);
4890 var len = range.size()[0];
4891
4892 if (len != replacement.length) {
4893 throw new DimensionError(range.size()[0], replacement.length);
4894 }
4895
4896 // validate whether the range is out of range
4897 var strLen = str.length;
4898 validateIndex(index.min()[0]);
4899 validateIndex(index.max()[0]);
4900
4901 // copy the string into an array with characters
4902 var chars = [];
4903 for (var i = 0; i < strLen; i++) {
4904 chars[i] = str.charAt(i);
4905 }
4906
4907 range.forEach(function (v, i) {
4908 chars[v] = replacement.charAt(i[0]);
4909 });
4910
4911 // initialize undefined characters with a space
4912 if (chars.length > strLen) {
4913 for (i = strLen - 1, len = chars.length; i < len; i++) {
4914 if (!chars[i]) {
4915 chars[i] = defaultValue;
4916 }
4917 }
4918 }
4919
4920 return chars.join('');
4921 }
4922}
4923
4924/**
4925 * Retrieve a property from an object
4926 * @param {Object} object
4927 * @param {Index} index
4928 * @return {*} Returns the value of the property
4929 * @private
4930 */
4931function _getObjectProperty (object, index) {
4932 if (index.size().length !== 1) {
4933 throw new DimensionError(index.size(), 1);
4934 }
4935
4936 var key = index.dimension(0);
4937 if (typeof key !== 'string') {
4938 throw new TypeError('String expected as index to retrieve an object property');
4939 }
4940
4941 return getSafeProperty(object, key);
4942}
4943
4944/**
4945 * Set a property on an object
4946 * @param {Object} object
4947 * @param {Index} index
4948 * @param {*} replacement
4949 * @return {*} Returns the updated object
4950 * @private
4951 */
4952function _setObjectProperty (object, index, replacement) {
4953 if (index.size().length !== 1) {
4954 throw new DimensionError(index.size(), 1);
4955 }
4956
4957 var key = index.dimension(0);
4958 if (typeof key !== 'string') {
4959 throw new TypeError('String expected as index to retrieve an object property');
4960 }
4961
4962 // clone the object, and apply the property to the clone
4963 var updated = clone(object);
4964 setSafeProperty(updated, key, replacement);
4965
4966 return updated;
4967}
4968
4969exports.name = 'subset';
4970exports.factory = factory;
4971
4972
4973/***/ }),
4974/* 24 */
4975/***/ (function(module, exports, __webpack_require__) {
4976
4977"use strict";
4978
4979
4980var DimensionError = __webpack_require__(11);
4981
4982function factory (type, config, load, typed) {
4983
4984 var equalScalar = load(__webpack_require__(10));
4985
4986 var SparseMatrix = type.SparseMatrix;
4987
4988 /**
4989 * Iterates over SparseMatrix nonzero items and invokes the callback function f(Dij, Sij).
4990 * Callback function invoked NNZ times (number of nonzero items in SparseMatrix).
4991 *
4992 *
4993 * ┌ f(Dij, Sij) ; S(i,j) !== 0
4994 * C(i,j) = ┤
4995 * └ 0 ; otherwise
4996 *
4997 *
4998 * @param {Matrix} denseMatrix The DenseMatrix instance (D)
4999 * @param {Matrix} sparseMatrix The SparseMatrix instance (S)
5000 * @param {Function} callback The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j)
5001 * @param {boolean} inverse A true value indicates callback should be invoked f(Sij,Dij)
5002 *
5003 * @return {Matrix} SparseMatrix (C)
5004 *
5005 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571
5006 */
5007 var algorithm02 = function (denseMatrix, sparseMatrix, callback, inverse) {
5008 // dense matrix arrays
5009 var adata = denseMatrix._data;
5010 var asize = denseMatrix._size;
5011 var adt = denseMatrix._datatype;
5012 // sparse matrix arrays
5013 var bvalues = sparseMatrix._values;
5014 var bindex = sparseMatrix._index;
5015 var bptr = sparseMatrix._ptr;
5016 var bsize = sparseMatrix._size;
5017 var bdt = sparseMatrix._datatype;
5018
5019 // validate dimensions
5020 if (asize.length !== bsize.length)
5021 throw new DimensionError(asize.length, bsize.length);
5022
5023 // check rows & columns
5024 if (asize[0] !== bsize[0] || asize[1] !== bsize[1])
5025 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
5026
5027 // sparse matrix cannot be a Pattern matrix
5028 if (!bvalues)
5029 throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix');
5030
5031 // rows & columns
5032 var rows = asize[0];
5033 var columns = asize[1];
5034
5035 // datatype
5036 var dt;
5037 // equal signature to use
5038 var eq = equalScalar;
5039 // zero value
5040 var zero = 0;
5041 // callback signature to use
5042 var cf = callback;
5043
5044 // process data types
5045 if (typeof adt === 'string' && adt === bdt) {
5046 // datatype
5047 dt = adt;
5048 // find signature that matches (dt, dt)
5049 eq = typed.find(equalScalar, [dt, dt]);
5050 // convert 0 to the same datatype
5051 zero = typed.convert(0, dt);
5052 // callback
5053 cf = typed.find(callback, [dt, dt]);
5054 }
5055
5056 // result (SparseMatrix)
5057 var cvalues = [];
5058 var cindex = [];
5059 var cptr = [];
5060
5061 // loop columns in b
5062 for (var j = 0; j < columns; j++) {
5063 // update cptr
5064 cptr[j] = cindex.length;
5065 // values in column j
5066 for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
5067 // row
5068 var i = bindex[k];
5069 // update C(i,j)
5070 var cij = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]);
5071 // check for nonzero
5072 if (!eq(cij, zero)) {
5073 // push i & v
5074 cindex.push(i);
5075 cvalues.push(cij);
5076 }
5077 }
5078 }
5079 // update cptr
5080 cptr[columns] = cindex.length;
5081
5082 // return sparse matrix
5083 return new SparseMatrix({
5084 values: cvalues,
5085 index: cindex,
5086 ptr: cptr,
5087 size: [rows, columns],
5088 datatype: dt
5089 });
5090 };
5091
5092 return algorithm02;
5093}
5094
5095exports.name = 'algorithm02';
5096exports.factory = factory;
5097
5098
5099/***/ }),
5100/* 25 */
5101/***/ (function(module, exports, __webpack_require__) {
5102
5103"use strict";
5104
5105
5106exports.array = __webpack_require__(2);
5107exports['boolean'] = __webpack_require__(178);
5108exports['function'] = __webpack_require__(32);
5109exports.number = __webpack_require__(3);
5110exports.object = __webpack_require__(5);
5111exports.string = __webpack_require__(9);
5112exports.types = __webpack_require__(60);
5113exports.emitter = __webpack_require__(91);
5114
5115
5116/***/ }),
5117/* 26 */
5118/***/ (function(module, exports, __webpack_require__) {
5119
5120"use strict";
5121
5122
5123var DimensionError = __webpack_require__(11);
5124
5125function factory (type, config, load, typed) {
5126
5127 var DenseMatrix = type.DenseMatrix;
5128
5129 /**
5130 * Iterates over SparseMatrix A and SparseMatrix B items (zero and nonzero) and invokes the callback function f(Aij, Bij).
5131 * Callback function invoked MxN times.
5132 *
5133 * C(i,j) = f(Aij, Bij)
5134 *
5135 * @param {Matrix} a The SparseMatrix instance (A)
5136 * @param {Matrix} b The SparseMatrix instance (B)
5137 * @param {Function} callback The f(Aij,Bij) operation to invoke
5138 *
5139 * @return {Matrix} DenseMatrix (C)
5140 *
5141 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
5142 */
5143 var algorithm07 = function (a, b, callback) {
5144 // sparse matrix arrays
5145 var asize = a._size;
5146 var adt = a._datatype;
5147 // sparse matrix arrays
5148 var bsize = b._size;
5149 var bdt = b._datatype;
5150
5151 // validate dimensions
5152 if (asize.length !== bsize.length)
5153 throw new DimensionError(asize.length, bsize.length);
5154
5155 // check rows & columns
5156 if (asize[0] !== bsize[0] || asize[1] !== bsize[1])
5157 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
5158
5159 // rows & columns
5160 var rows = asize[0];
5161 var columns = asize[1];
5162
5163 // datatype
5164 var dt;
5165 // zero value
5166 var zero = 0;
5167 // callback signature to use
5168 var cf = callback;
5169
5170 // process data types
5171 if (typeof adt === 'string' && adt === bdt) {
5172 // datatype
5173 dt = adt;
5174 // convert 0 to the same datatype
5175 zero = typed.convert(0, dt);
5176 // callback
5177 cf = typed.find(callback, [dt, dt]);
5178 }
5179
5180 // vars
5181 var i, j;
5182
5183 // result arrays
5184 var cdata = [];
5185 // initialize c
5186 for (i = 0; i < rows; i++)
5187 cdata[i] = [];
5188
5189 // matrix
5190 var c = new DenseMatrix({
5191 data: cdata,
5192 size: [rows, columns],
5193 datatype: dt
5194 });
5195
5196 // workspaces
5197 var xa = [];
5198 var xb = [];
5199 // marks indicating we have a value in x for a given column
5200 var wa = [];
5201 var wb = [];
5202
5203 // loop columns
5204 for (j = 0; j < columns; j++) {
5205 // columns mark
5206 var mark = j + 1;
5207 // scatter the values of A(:,j) into workspace
5208 _scatter(a, j, wa, xa, mark);
5209 // scatter the values of B(:,j) into workspace
5210 _scatter(b, j, wb, xb, mark);
5211 // loop rows
5212 for (i = 0; i < rows; i++) {
5213 // matrix values @ i,j
5214 var va = wa[i] === mark ? xa[i] : zero;
5215 var vb = wb[i] === mark ? xb[i] : zero;
5216 // invoke callback
5217 cdata[i][j] = cf(va, vb);
5218 }
5219 }
5220
5221 // return sparse matrix
5222 return c;
5223 };
5224
5225 var _scatter = function (m, j, w, x, mark) {
5226 // a arrays
5227 var values = m._values;
5228 var index = m._index;
5229 var ptr = m._ptr;
5230 // loop values in column j
5231 for (var k = ptr[j], k1 = ptr[j + 1]; k < k1; k++) {
5232 // row
5233 var i = index[k];
5234 // update workspace
5235 w[i] = mark;
5236 x[i] = values[k];
5237 }
5238 };
5239
5240 return algorithm07;
5241}
5242
5243exports.name = 'algorithm07';
5244exports.factory = factory;
5245
5246
5247/***/ }),
5248/* 27 */
5249/***/ (function(module, exports, __webpack_require__) {
5250
5251"use strict";
5252
5253
5254var clone = __webpack_require__(5).clone;
5255var isInteger = __webpack_require__(3).isInteger;
5256
5257function factory (type) {
5258
5259 /**
5260 * Create an index. An Index can store ranges and sets for multiple dimensions.
5261 * Matrix.get, Matrix.set, and math.subset accept an Index as input.
5262 *
5263 * Usage:
5264 * var index = new Index(range1, range2, matrix1, array1, ...);
5265 *
5266 * Where each parameter can be any of:
5267 * A number
5268 * A string (containing a name of an object property)
5269 * An instance of Range
5270 * An Array with the Set values
5271 * A Matrix with the Set values
5272 *
5273 * The parameters start, end, and step must be integer numbers.
5274 *
5275 * @class Index
5276 * @Constructor Index
5277 * @param {...*} ranges
5278 */
5279 function Index(ranges) {
5280 if (!(this instanceof Index)) {
5281 throw new SyntaxError('Constructor must be called with the new operator');
5282 }
5283
5284 this._dimensions = [];
5285 this._isScalar = true;
5286
5287 for (var i = 0, ii = arguments.length; i < ii; i++) {
5288 var arg = arguments[i];
5289
5290 if (type.isRange(arg)) {
5291 this._dimensions.push(arg);
5292 this._isScalar = false;
5293 }
5294 else if (Array.isArray(arg) || type.isMatrix(arg)) {
5295 // create matrix
5296 var m = _createImmutableMatrix(arg.valueOf());
5297 this._dimensions.push(m);
5298 // size
5299 var size = m.size();
5300 // scalar
5301 if (size.length !== 1 || size[0] !== 1) {
5302 this._isScalar = false;
5303 }
5304 }
5305 else if (typeof arg === 'number') {
5306 this._dimensions.push(_createImmutableMatrix([arg]));
5307 }
5308 else if (typeof arg === 'string') {
5309 // object property (arguments.count should be 1)
5310 this._dimensions.push(arg);
5311 }
5312 // TODO: implement support for wildcard '*'
5313 else {
5314 throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range');
5315 }
5316 }
5317 }
5318
5319 /**
5320 * Attach type information
5321 */
5322 Index.prototype.type = 'Index';
5323 Index.prototype.isIndex = true;
5324
5325 function _createImmutableMatrix(arg) {
5326 // loop array elements
5327 for (var i = 0, l = arg.length; i < l; i++) {
5328 if (typeof arg[i] !== 'number' || !isInteger(arg[i])) {
5329 throw new TypeError('Index parameters must be positive integer numbers');
5330 }
5331 }
5332 // create matrix
5333 return new type.ImmutableDenseMatrix(arg);
5334 }
5335
5336 /**
5337 * Create a clone of the index
5338 * @memberof Index
5339 * @return {Index} clone
5340 */
5341 Index.prototype.clone = function () {
5342 var index = new Index();
5343 index._dimensions = clone(this._dimensions);
5344 index._isScalar = this._isScalar;
5345 return index;
5346 };
5347
5348 /**
5349 * Create an index from an array with ranges/numbers
5350 * @memberof Index
5351 * @param {Array.<Array | number>} ranges
5352 * @return {Index} index
5353 * @private
5354 */
5355 Index.create = function (ranges) {
5356 var index = new Index();
5357 Index.apply(index, ranges);
5358 return index;
5359 };
5360
5361 /**
5362 * Retrieve the size of the index, the number of elements for each dimension.
5363 * @memberof Index
5364 * @returns {number[]} size
5365 */
5366 Index.prototype.size = function () {
5367 var size = [];
5368
5369 for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
5370 var d = this._dimensions[i];
5371 size[i] = (typeof d === 'string') ? 1 : d.size()[0];
5372 }
5373
5374 return size;
5375 };
5376
5377 /**
5378 * Get the maximum value for each of the indexes ranges.
5379 * @memberof Index
5380 * @returns {number[]} max
5381 */
5382 Index.prototype.max = function () {
5383 var values = [];
5384
5385 for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
5386 var range = this._dimensions[i];
5387 values[i] = (typeof range === 'string') ? range : range.max();
5388 }
5389
5390 return values;
5391 };
5392
5393 /**
5394 * Get the minimum value for each of the indexes ranges.
5395 * @memberof Index
5396 * @returns {number[]} min
5397 */
5398 Index.prototype.min = function () {
5399 var values = [];
5400
5401 for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
5402 var range = this._dimensions[i];
5403 values[i] = (typeof range === 'string') ? range : range.min();
5404 }
5405
5406 return values;
5407 };
5408
5409 /**
5410 * Loop over each of the ranges of the index
5411 * @memberof Index
5412 * @param {Function} callback Called for each range with a Range as first
5413 * argument, the dimension as second, and the
5414 * index object as third.
5415 */
5416 Index.prototype.forEach = function (callback) {
5417 for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
5418 callback(this._dimensions[i], i, this);
5419 }
5420 };
5421
5422 /**
5423 * Retrieve the dimension for the given index
5424 * @memberof Index
5425 * @param {Number} dim Number of the dimension
5426 * @returns {Range | null} range
5427 */
5428 Index.prototype.dimension = function (dim) {
5429 return this._dimensions[dim] || null;
5430 };
5431
5432 /**
5433 * Test whether this index contains an object property
5434 * @returns {boolean} Returns true if the index is an object property
5435 */
5436 Index.prototype.isObjectProperty = function () {
5437 return this._dimensions.length === 1 && typeof this._dimensions[0] === 'string';
5438 };
5439
5440 /**
5441 * Returns the object property name when the Index holds a single object property,
5442 * else returns null
5443 * @returns {string | null}
5444 */
5445 Index.prototype.getObjectProperty = function () {
5446 return this.isObjectProperty() ? this._dimensions[0] : null;
5447 };
5448
5449 /**
5450 * Test whether this index contains only a single value.
5451 *
5452 * This is the case when the index is created with only scalar values as ranges,
5453 * not for ranges resolving into a single value.
5454 * @memberof Index
5455 * @return {boolean} isScalar
5456 */
5457 Index.prototype.isScalar = function () {
5458 return this._isScalar;
5459 };
5460
5461 /**
5462 * Expand the Index into an array.
5463 * For example new Index([0,3], [2,7]) returns [[0,1,2], [2,3,4,5,6]]
5464 * @memberof Index
5465 * @returns {Array} array
5466 */
5467 Index.prototype.toArray = function () {
5468 var array = [];
5469 for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
5470 var dimension = this._dimensions[i];
5471 array.push((typeof dimension === 'string') ? dimension : dimension.toArray());
5472 }
5473 return array;
5474 };
5475
5476 /**
5477 * Get the primitive value of the Index, a two dimensional array.
5478 * Equivalent to Index.toArray().
5479 * @memberof Index
5480 * @returns {Array} array
5481 */
5482 Index.prototype.valueOf = Index.prototype.toArray;
5483
5484 /**
5485 * Get the string representation of the index, for example '[2:6]' or '[0:2:10, 4:7, [1,2,3]]'
5486 * @memberof Index
5487 * @returns {String} str
5488 */
5489 Index.prototype.toString = function () {
5490 var strings = [];
5491
5492 for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
5493 var dimension = this._dimensions[i];
5494 if (typeof dimension === 'string') {
5495 strings.push(JSON.stringify(dimension));
5496 }
5497 else {
5498 strings.push(dimension.toString());
5499 }
5500 }
5501
5502 return '[' + strings.join(', ') + ']';
5503 };
5504
5505 /**
5506 * Get a JSON representation of the Index
5507 * @memberof Index
5508 * @returns {Object} Returns a JSON object structured as:
5509 * `{"mathjs": "Index", "ranges": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}`
5510 */
5511 Index.prototype.toJSON = function () {
5512 return {
5513 mathjs: 'Index',
5514 dimensions: this._dimensions
5515 };
5516 };
5517
5518 /**
5519 * Instantiate an Index from a JSON object
5520 * @memberof Index
5521 * @param {Object} json A JSON object structured as:
5522 * `{"mathjs": "Index", "dimensions": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}`
5523 * @return {Index}
5524 */
5525 Index.fromJSON = function (json) {
5526 return Index.create(json.dimensions);
5527 };
5528
5529 return Index;
5530}
5531
5532exports.name = 'Index';
5533exports.path = 'type';
5534exports.factory = factory;
5535
5536
5537/***/ }),
5538/* 28 */
5539/***/ (function(module, exports, __webpack_require__) {
5540
5541"use strict";
5542
5543
5544var deepMap = __webpack_require__(1);
5545
5546function factory (type, config, load, typed) {
5547 /**
5548 * Calculate the absolute value of a number. For matrices, the function is
5549 * evaluated element wise.
5550 *
5551 * Syntax:
5552 *
5553 * math.abs(x)
5554 *
5555 * Examples:
5556 *
5557 * math.abs(3.5); // returns number 3.5
5558 * math.abs(-4.2); // returns number 4.2
5559 *
5560 * math.abs([3, -5, -1, 0, 2]); // returns Array [3, 5, 1, 0, 2]
5561 *
5562 * See also:
5563 *
5564 * sign
5565 *
5566 * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x
5567 * A number or matrix for which to get the absolute value
5568 * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit}
5569 * Absolute value of `x`
5570 */
5571 var abs = typed('abs', {
5572 'number': Math.abs,
5573
5574 'Complex': function (x) {
5575 return x.abs();
5576 },
5577
5578 'BigNumber': function (x) {
5579 return x.abs();
5580 },
5581
5582 'Fraction': function (x) {
5583 return x.abs();
5584 },
5585
5586 'Array | Matrix': function (x) {
5587 // deep map collection, skip zeros since abs(0) = 0
5588 return deepMap(x, abs, true);
5589 },
5590
5591 'Unit': function(x) {
5592 return x.abs();
5593 }
5594 });
5595
5596 abs.toTex = {1: '\\left|${args[0]}\\right|'};
5597
5598 return abs;
5599}
5600
5601exports.name = 'abs';
5602exports.factory = factory;
5603
5604
5605/***/ }),
5606/* 29 */
5607/***/ (function(module, exports, __webpack_require__) {
5608
5609"use strict";
5610
5611
5612var array = __webpack_require__(2);
5613
5614function factory (type, config, load, typed) {
5615 var matrix = load(__webpack_require__(0));
5616
5617 /**
5618 * Calculate the size of a matrix or scalar.
5619 *
5620 * Syntax:
5621 *
5622 * math.size(x)
5623 *
5624 * Examples:
5625 *
5626 * math.size(2.3); // returns []
5627 * math.size('hello world'); // returns [11]
5628 *
5629 * var A = [[1, 2, 3], [4, 5, 6]];
5630 * math.size(A); // returns [2, 3]
5631 * math.size(math.range(1,6)); // returns [5]
5632 *
5633 * See also:
5634 *
5635 * resize, squeeze, subset
5636 *
5637 * @param {boolean | number | Complex | Unit | string | Array | Matrix} x A matrix
5638 * @return {Array | Matrix} A vector with size of `x`.
5639 */
5640 var size = typed('size', {
5641 'Matrix': function (x) {
5642 // TODO: return the same matrix type as the input
5643 return matrix(x.size());
5644 },
5645
5646 'Array': array.size,
5647
5648 'string': function (x) {
5649 return (config.matrix === 'Array') ? [x.length] : matrix([x.length]);
5650 },
5651
5652 'number | Complex | BigNumber | Unit | boolean | null': function (x) {
5653 // scalar
5654 return (config.matrix === 'Array') ? [] : matrix([]);
5655 }
5656 });
5657
5658 size.toTex = undefined; // use default template
5659
5660 return size;
5661}
5662
5663exports.name = 'size';
5664exports.factory = factory;
5665
5666
5667/***/ }),
5668/* 30 */
5669/***/ (function(module, exports, __webpack_require__) {
5670
5671"use strict";
5672
5673
5674function factory (type, config, load, typed) {
5675
5676 var matrix = load(__webpack_require__(0));
5677 var equalScalar = load(__webpack_require__(10));
5678
5679 var algorithm03 = load(__webpack_require__(17));
5680 var algorithm07 = load(__webpack_require__(26));
5681 var algorithm12 = load(__webpack_require__(18));
5682 var algorithm13 = load(__webpack_require__(8));
5683 var algorithm14 = load(__webpack_require__(6));
5684
5685 var latex = __webpack_require__(4);
5686
5687 /**
5688 * Test whether two values are equal.
5689 *
5690 * The function tests whether the relative difference between x and y is
5691 * smaller than the configured epsilon. The function cannot be used to
5692 * compare values smaller than approximately 2.22e-16.
5693 *
5694 * For matrices, the function is evaluated element wise.
5695 * In case of complex numbers, x.re must equal y.re, and x.im must equal y.im.
5696 *
5697 * Values `null` and `undefined` are compared strictly, thus `null` is only
5698 * equal to `null` and nothing else, and `undefined` is only equal to
5699 * `undefined` and nothing else.
5700 *
5701 * Syntax:
5702 *
5703 * math.equal(x, y)
5704 *
5705 * Examples:
5706 *
5707 * math.equal(2 + 2, 3); // returns false
5708 * math.equal(2 + 2, 4); // returns true
5709 *
5710 * var a = math.unit('50 cm');
5711 * var b = math.unit('5 m');
5712 * math.equal(a, b); // returns true
5713 *
5714 * var c = [2, 5, 1];
5715 * var d = [2, 7, 1];
5716 *
5717 * math.equal(c, d); // returns [true, false, true]
5718 * math.deepEqual(c, d); // returns false
5719 *
5720 * math.equal(0, null); // returns false
5721 *
5722 * See also:
5723 *
5724 * unequal, smaller, smallerEq, larger, largerEq, compare, deepEqual
5725 *
5726 * @param {number | BigNumber | boolean | Complex | Unit | string | Array | Matrix} x First value to compare
5727 * @param {number | BigNumber | boolean | Complex | Unit | string | Array | Matrix} y Second value to compare
5728 * @return {boolean | Array | Matrix} Returns true when the compared values are equal, else returns false
5729 */
5730 var equal = typed('equal', {
5731
5732 'any, any': function (x, y) {
5733 // strict equality for null and undefined?
5734 if (x === null) { return y === null; }
5735 if (y === null) { return x === null; }
5736 if (x === undefined) { return y === undefined; }
5737 if (y === undefined) { return x === undefined; }
5738
5739 return equalScalar(x, y);
5740 },
5741
5742 'Matrix, Matrix': function (x, y) {
5743 // result
5744 var c;
5745
5746 // process matrix storage
5747 switch (x.storage()) {
5748 case 'sparse':
5749 switch (y.storage()) {
5750 case 'sparse':
5751 // sparse + sparse
5752 c = algorithm07(x, y, equalScalar);
5753 break;
5754 default:
5755 // sparse + dense
5756 c = algorithm03(y, x, equalScalar, true);
5757 break;
5758 }
5759 break;
5760 default:
5761 switch (y.storage()) {
5762 case 'sparse':
5763 // dense + sparse
5764 c = algorithm03(x, y, equalScalar, false);
5765 break;
5766 default:
5767 // dense + dense
5768 c = algorithm13(x, y, equalScalar);
5769 break;
5770 }
5771 break;
5772 }
5773 return c;
5774 },
5775
5776 'Array, Array': function (x, y) {
5777 // use matrix implementation
5778 return equal(matrix(x), matrix(y)).valueOf();
5779 },
5780
5781 'Array, Matrix': function (x, y) {
5782 // use matrix implementation
5783 return equal(matrix(x), y);
5784 },
5785
5786 'Matrix, Array': function (x, y) {
5787 // use matrix implementation
5788 return equal(x, matrix(y));
5789 },
5790
5791 'Matrix, any': function (x, y) {
5792 // result
5793 var c;
5794 // check storage format
5795 switch (x.storage()) {
5796 case 'sparse':
5797 c = algorithm12(x, y, equalScalar, false);
5798 break;
5799 default:
5800 c = algorithm14(x, y, equalScalar, false);
5801 break;
5802 }
5803 return c;
5804 },
5805
5806 'any, Matrix': function (x, y) {
5807 // result
5808 var c;
5809 // check storage format
5810 switch (y.storage()) {
5811 case 'sparse':
5812 c = algorithm12(y, x, equalScalar, true);
5813 break;
5814 default:
5815 c = algorithm14(y, x, equalScalar, true);
5816 break;
5817 }
5818 return c;
5819 },
5820
5821 'Array, any': function (x, y) {
5822 // use matrix implementation
5823 return algorithm14(matrix(x), y, equalScalar, false).valueOf();
5824 },
5825
5826 'any, Array': function (x, y) {
5827 // use matrix implementation
5828 return algorithm14(matrix(y), x, equalScalar, true).valueOf();
5829 }
5830 });
5831
5832 equal.toTex = {
5833 2: '\\left(${args[0]}' + latex.operators['equal'] + '${args[1]}\\right)'
5834 };
5835
5836 return equal;
5837}
5838
5839exports.name = 'equal';
5840exports.factory = factory;
5841
5842
5843/***/ }),
5844/* 31 */
5845/***/ (function(module, exports, __webpack_require__) {
5846
5847"use strict";
5848
5849
5850var naturalSort = __webpack_require__(486);
5851
5852function factory (type, config, load, typed) {
5853 var getTypeOf = load(__webpack_require__(76));
5854 var matrix = load(__webpack_require__(0));
5855 var compare = load(__webpack_require__(52));
5856
5857 var compareBooleans = compare.signatures['boolean,boolean']
5858
5859 /**
5860 * Compare two values of any type in a deterministic, natural way.
5861 *
5862 * For numeric values, the function works the same as `math.compare`.
5863 * For types of values that can't be compared mathematically,
5864 * the function compares in a natural way.
5865 *
5866 * For numeric values, x and y are considered equal when the relative
5867 * difference between x and y is smaller than the configured epsilon.
5868 * The function cannot be used to compare values smaller than
5869 * approximately 2.22e-16.
5870 *
5871 * For Complex numbers, first the real parts are compared. If equal,
5872 * the imaginary parts are compared.
5873 *
5874 * Arrays and Matrices are compared value by value until there is an
5875 * unequal pair of values encountered. Objects are compared by sorted
5876 * keys until the keys or their values are unequal.
5877 *
5878 * Syntax:
5879 *
5880 * math.compareNatural(x, y)
5881 *
5882 * Examples:
5883 *
5884 * math.compareNatural(6, 1); // returns 1
5885 * math.compareNatural(2, 3); // returns -1
5886 * math.compareNatural(7, 7); // returns 0
5887 *
5888 * math.compareNatural('10', '2'); // returns 1
5889 *
5890 * var a = math.unit('5 cm');
5891 * var b = math.unit('40 mm');
5892 * math.compareNatural(a, b); // returns 1
5893 *
5894 * var c = math.complex('2 + 3i');
5895 * var d = math.complex('2 + 4i');
5896 * math.compareNatural(c, d); // returns -1
5897 *
5898 * math.compareNatural([1, 2, 4], [1, 2, 3]); // returns 1
5899 * math.compareNatural([1, 2, 3], [1, 2]); // returns 1
5900 * math.compareNatural([1, 5], [1, 2, 3]); // returns 1
5901 * math.compareNatural([1, 2], [1, 2]); // returns 0
5902 *
5903 * math.compareNatural({a: 2}, {a: 4}); // returns -1
5904 *
5905 * See also:
5906 *
5907 * equal, unequal, smaller, smallerEq, larger, largerEq, compare
5908 *
5909 * @param {*} x First value to compare
5910 * @param {*} y Second value to compare
5911 * @return {number} Returns the result of the comparison: 1, 0 or -1.
5912 */
5913 var compareNatural = typed('compareNatural', {
5914 'any, any': function (x, y) {
5915 var typeX = getTypeOf(x);
5916 var typeY = getTypeOf(y);
5917 var c;
5918
5919 // numeric types
5920 if ((typeX === 'number' || typeX === 'BigNumber' || typeX === 'Fraction') &&
5921 (typeY === 'number' || typeY === 'BigNumber' || typeY === 'Fraction')) {
5922 c = compare(x, y);
5923 if (c.toString() !== '0') {
5924 // c can be number, BigNumber, or Fraction
5925 return c > 0 ? 1 : -1; // return a number
5926 }
5927 else {
5928 return naturalSort(typeX, typeY);
5929 }
5930 }
5931
5932 // matrix types
5933 if (typeX === 'Array' || typeX === 'Matrix' ||
5934 typeY === 'Array' || typeY === 'Matrix') {
5935 c = compareMatricesAndArrays (x, y);
5936 if (c !== 0) {
5937 return c;
5938 }
5939 else {
5940 return naturalSort(typeX, typeY);
5941 }
5942 }
5943
5944 // in case of different types, order by name of type, i.e. 'BigNumber' < 'Complex'
5945 if (typeX !== typeY) {
5946 return naturalSort(typeX, typeY);
5947 }
5948
5949 if (typeX === 'Complex') {
5950 return compareComplexNumbers(x, y);
5951 }
5952
5953 if (typeX === 'Unit') {
5954 if (x.equalBase(y)) {
5955 return compareNatural(x.value, y.value);
5956 }
5957
5958 // compare by units
5959 return compareArrays(x.formatUnits(), y.formatUnits());
5960 }
5961
5962 if (typeX === 'boolean') {
5963 return compareBooleans(x, y);
5964 }
5965
5966 if (typeX === 'string') {
5967 return naturalSort(x, y);
5968 }
5969
5970 if (typeX === 'Object') {
5971 return compareObjects(x, y);
5972 }
5973
5974 if (typeX === 'null') {
5975 return 0;
5976 }
5977
5978 if (typeX === 'undefined') {
5979 return 0;
5980 }
5981
5982 // this should not occur...
5983 throw new TypeError('Unsupported type of value "' + typeX + '"');
5984 }
5985 });
5986
5987 compareNatural.toTex = undefined; // use default template
5988
5989 /**
5990 * Compare mixed matrix/array types, by converting to same-shaped array.
5991 * This comparator is non-deterministic regarding input types.
5992 * @param {Array | SparseMatrix | DenseMatrix | *} x
5993 * @param {Array | SparseMatrix | DenseMatrix | *} y
5994 * @returns {number} Returns the comparison result: -1, 0, or 1
5995 */
5996 function compareMatricesAndArrays (x, y) {
5997 if (type.isSparseMatrix(x) && type.isSparseMatrix(y)) {
5998 return compareArrays(x.toJSON().values, y.toJSON().values);
5999 }
6000 if (type.isSparseMatrix(x)) {
6001 // note: convert to array is expensive
6002 return compareMatricesAndArrays(x.toArray(), y);
6003 }
6004 if (type.isSparseMatrix(y)) {
6005 // note: convert to array is expensive
6006 return compareMatricesAndArrays(x, y.toArray());
6007 }
6008
6009 // convert DenseArray into Array
6010 if (type.isDenseMatrix(x)) {
6011 return compareMatricesAndArrays(x.toJSON().data, y);
6012 }
6013 if (type.isDenseMatrix(y)) {
6014 return compareMatricesAndArrays(x, y.toJSON().data);
6015 }
6016
6017 // convert scalars to array
6018 if (!Array.isArray(x)) {
6019 return compareMatricesAndArrays([x], y);
6020 }
6021 if (!Array.isArray(y)) {
6022 return compareMatricesAndArrays(x, [y]);
6023 }
6024
6025 return compareArrays(x, y);
6026 }
6027
6028 /**
6029 * Compare two Arrays
6030 *
6031 * - First, compares value by value
6032 * - Next, if all corresponding values are equal,
6033 * look at the length: longest array will be considered largest
6034 *
6035 * @param {Array} x
6036 * @param {Array} y
6037 * @returns {number} Returns the comparison result: -1, 0, or 1
6038 */
6039 function compareArrays (x, y) {
6040 // compare each value
6041 for (var i = 0, ii = Math.min(x.length, y.length); i < ii; i++) {
6042 var v = compareNatural(x[i], y[i]);
6043 if (v !== 0) {
6044 return v;
6045 }
6046 }
6047
6048 // compare the size of the arrays
6049 if (x.length > y.length) { return 1; }
6050 if (x.length < y.length) { return -1; }
6051
6052 // both Arrays have equal size and content
6053 return 0;
6054 }
6055
6056 /**
6057 * Compare two objects
6058 *
6059 * - First, compare sorted property names
6060 * - Next, compare the property values
6061 *
6062 * @param {Object} x
6063 * @param {Object} y
6064 * @returns {number} Returns the comparison result: -1, 0, or 1
6065 */
6066 function compareObjects (x, y) {
6067 var keysX = Object.keys(x);
6068 var keysY = Object.keys(y);
6069
6070 // compare keys
6071 keysX.sort(naturalSort)
6072 keysY.sort(naturalSort)
6073 var c = compareArrays(keysX, keysY);
6074 if (c !== 0) {
6075 return c;
6076 }
6077
6078 // compare values
6079 for (var i = 0; i < keysX.length; i++) {
6080 var v = compareNatural(x[keysX[i]], y[keysY[i]]);
6081 if (v !== 0) {
6082 return v;
6083 }
6084 }
6085
6086 return 0;
6087 }
6088
6089 return compareNatural;
6090}
6091
6092/**
6093 * Compare two complex numbers, `x` and `y`:
6094 *
6095 * - First, compare the real values of `x` and `y`
6096 * - If equal, compare the imaginary values of `x` and `y`
6097 *
6098 * @params {Complex} x
6099 * @params {Complex} y
6100 * @returns {number} Returns the comparison result: -1, 0, or 1
6101 */
6102function compareComplexNumbers (x, y) {
6103 if (x.re > y.re) { return 1; }
6104 if (x.re < y.re) { return -1; }
6105
6106 if (x.im > y.im) { return 1; }
6107 if (x.im < y.im) { return -1; }
6108
6109 return 0;
6110}
6111
6112exports.name = 'compareNatural';
6113exports.factory = factory;
6114
6115
6116/***/ }),
6117/* 32 */
6118/***/ (function(module, exports) {
6119
6120// function utils
6121
6122/**
6123 * Memoize a given function by caching the computed result.
6124 * The cache of a memoized function can be cleared by deleting the `cache`
6125 * property of the function.
6126 *
6127 * @param {function} fn The function to be memoized.
6128 * Must be a pure function.
6129 * @param {function(args: Array)} [hasher] A custom hash builder.
6130 * Is JSON.stringify by default.
6131 * @return {function} Returns the memoized function
6132 */
6133exports.memoize = function(fn, hasher) {
6134 return function memoize() {
6135 if (typeof memoize.cache !== 'object') {
6136 memoize.cache = {};
6137 }
6138
6139 var args = [];
6140 for (var i = 0; i < arguments.length; i++) {
6141 args[i] = arguments[i];
6142 }
6143
6144 var hash = hasher ? hasher(args) : JSON.stringify(args);
6145 if (!(hash in memoize.cache)) {
6146 return memoize.cache[hash] = fn.apply(fn, args);
6147 }
6148 return memoize.cache[hash];
6149 };
6150};
6151
6152/**
6153 * Find the maximum number of arguments expected by a typed function.
6154 * @param {function} fn A typed function
6155 * @return {number} Returns the maximum number of expected arguments.
6156 * Returns -1 when no signatures where found on the function.
6157 */
6158exports.maxArgumentCount = function (fn) {
6159 return Object.keys(fn.signatures || {})
6160 .reduce(function (args, signature) {
6161 var count = (signature.match(/,/g) || []).length + 1;
6162 return Math.max(args, count);
6163 }, -1);
6164};
6165
6166/**
6167 * Call a typed function with the
6168 * @param {function} fn A function or typed function
6169 * @return {number} Returns the maximum number of expected arguments.
6170 * Returns -1 when no signatures where found on the function.
6171 */
6172exports.callWithRightArgumentCount = function (fn, args, argCount) {
6173 return Object.keys(fn.signatures || {})
6174 .reduce(function (args, signature) {
6175 var count = (signature.match(/,/g) || []).length + 1;
6176 return Math.max(args, count);
6177 }, -1);
6178};
6179
6180
6181/***/ }),
6182/* 33 */
6183/***/ (function(module, exports, __webpack_require__) {
6184
6185"use strict";
6186
6187
6188var DimensionError = __webpack_require__(11);
6189
6190function factory (type, config, load, typed) {
6191
6192 var DenseMatrix = type.DenseMatrix;
6193
6194 /**
6195 * Iterates over SparseMatrix nonzero items and invokes the callback function f(Dij, Sij).
6196 * Callback function invoked NNZ times (number of nonzero items in SparseMatrix).
6197 *
6198 *
6199 * ┌ f(Dij, Sij) ; S(i,j) !== 0
6200 * C(i,j) = ┤
6201 * └ Dij ; otherwise
6202 *
6203 *
6204 * @param {Matrix} denseMatrix The DenseMatrix instance (D)
6205 * @param {Matrix} sparseMatrix The SparseMatrix instance (S)
6206 * @param {Function} callback The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j)
6207 * @param {boolean} inverse A true value indicates callback should be invoked f(Sij,Dij)
6208 *
6209 * @return {Matrix} DenseMatrix (C)
6210 *
6211 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571
6212 */
6213 var algorithm01 = function (denseMatrix, sparseMatrix, callback, inverse) {
6214 // dense matrix arrays
6215 var adata = denseMatrix._data;
6216 var asize = denseMatrix._size;
6217 var adt = denseMatrix._datatype;
6218 // sparse matrix arrays
6219 var bvalues = sparseMatrix._values;
6220 var bindex = sparseMatrix._index;
6221 var bptr = sparseMatrix._ptr;
6222 var bsize = sparseMatrix._size;
6223 var bdt = sparseMatrix._datatype;
6224
6225 // validate dimensions
6226 if (asize.length !== bsize.length)
6227 throw new DimensionError(asize.length, bsize.length);
6228
6229 // check rows & columns
6230 if (asize[0] !== bsize[0] || asize[1] !== bsize[1])
6231 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
6232
6233 // sparse matrix cannot be a Pattern matrix
6234 if (!bvalues)
6235 throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix');
6236
6237 // rows & columns
6238 var rows = asize[0];
6239 var columns = asize[1];
6240
6241 // process data types
6242 var dt = typeof adt === 'string' && adt === bdt ? adt : undefined;
6243 // callback function
6244 var cf = dt ? typed.find(callback, [dt, dt]) : callback;
6245
6246 // vars
6247 var i, j;
6248
6249 // result (DenseMatrix)
6250 var cdata = [];
6251 // initialize c
6252 for (i = 0; i < rows; i++)
6253 cdata[i] = [];
6254
6255 // workspace
6256 var x = [];
6257 // marks indicating we have a value in x for a given column
6258 var w = [];
6259
6260 // loop columns in b
6261 for (j = 0; j < columns; j++) {
6262 // column mark
6263 var mark = j + 1;
6264 // values in column j
6265 for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
6266 // row
6267 i = bindex[k];
6268 // update workspace
6269 x[i] = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]);
6270 // mark i as updated
6271 w[i] = mark;
6272 }
6273 // loop rows
6274 for (i = 0; i < rows; i++) {
6275 // check row is in workspace
6276 if (w[i] === mark) {
6277 // c[i][j] was already calculated
6278 cdata[i][j] = x[i];
6279 }
6280 else {
6281 // item does not exist in S
6282 cdata[i][j] = adata[i][j];
6283 }
6284 }
6285 }
6286
6287 // return dense matrix
6288 return new DenseMatrix({
6289 data: cdata,
6290 size: [rows, columns],
6291 datatype: dt
6292 });
6293 };
6294
6295 return algorithm01;
6296}
6297
6298exports.name = 'algorithm01';
6299exports.factory = factory;
6300
6301
6302/***/ }),
6303/* 34 */
6304/***/ (function(module, exports, __webpack_require__) {
6305
6306"use strict";
6307
6308
6309var nearlyEqual = __webpack_require__(3).nearlyEqual;
6310var bigNearlyEqual = __webpack_require__(37);
6311
6312function factory (type, config, load, typed) {
6313
6314 var matrix = load(__webpack_require__(0));
6315
6316 var algorithm03 = load(__webpack_require__(17));
6317 var algorithm07 = load(__webpack_require__(26));
6318 var algorithm12 = load(__webpack_require__(18));
6319 var algorithm13 = load(__webpack_require__(8));
6320 var algorithm14 = load(__webpack_require__(6));
6321
6322 var latex = __webpack_require__(4);
6323
6324 /**
6325 * Test whether value x is larger than y.
6326 *
6327 * The function returns true when x is larger than y and the relative
6328 * difference between x and y is larger than the configured epsilon. The
6329 * function cannot be used to compare values smaller than approximately 2.22e-16.
6330 *
6331 * For matrices, the function is evaluated element wise.
6332 *
6333 * Syntax:
6334 *
6335 * math.larger(x, y)
6336 *
6337 * Examples:
6338 *
6339 * math.larger(2, 3); // returns false
6340 * math.larger(5, 2 + 2); // returns true
6341 *
6342 * var a = math.unit('5 cm');
6343 * var b = math.unit('2 inch');
6344 * math.larger(a, b); // returns false
6345 *
6346 * See also:
6347 *
6348 * equal, unequal, smaller, smallerEq, largerEq, compare
6349 *
6350 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
6351 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
6352 * @return {boolean | Array | Matrix} Returns true when the x is larger than y, else returns false
6353 */
6354 var larger = typed('larger', {
6355
6356 'boolean, boolean': function (x, y) {
6357 return x > y;
6358 },
6359
6360 'number, number': function (x, y) {
6361 return x > y && !nearlyEqual(x, y, config.epsilon);
6362 },
6363
6364 'BigNumber, BigNumber': function (x, y) {
6365 return x.gt(y) && !bigNearlyEqual(x, y, config.epsilon);
6366 },
6367
6368 'Fraction, Fraction': function (x, y) {
6369 return x.compare(y) === 1;
6370 },
6371
6372 'Complex, Complex': function () {
6373 throw new TypeError('No ordering relation is defined for complex numbers');
6374 },
6375
6376 'Unit, Unit': function (x, y) {
6377 if (!x.equalBase(y)) {
6378 throw new Error('Cannot compare units with different base');
6379 }
6380 return larger(x.value, y.value);
6381 },
6382
6383 'string, string': function (x, y) {
6384 return x > y;
6385 },
6386
6387 'Matrix, Matrix': function (x, y) {
6388 // result
6389 var c;
6390
6391 // process matrix storage
6392 switch (x.storage()) {
6393 case 'sparse':
6394 switch (y.storage()) {
6395 case 'sparse':
6396 // sparse + sparse
6397 c = algorithm07(x, y, larger);
6398 break;
6399 default:
6400 // sparse + dense
6401 c = algorithm03(y, x, larger, true);
6402 break;
6403 }
6404 break;
6405 default:
6406 switch (y.storage()) {
6407 case 'sparse':
6408 // dense + sparse
6409 c = algorithm03(x, y, larger, false);
6410 break;
6411 default:
6412 // dense + dense
6413 c = algorithm13(x, y, larger);
6414 break;
6415 }
6416 break;
6417 }
6418 return c;
6419 },
6420
6421 'Array, Array': function (x, y) {
6422 // use matrix implementation
6423 return larger(matrix(x), matrix(y)).valueOf();
6424 },
6425
6426 'Array, Matrix': function (x, y) {
6427 // use matrix implementation
6428 return larger(matrix(x), y);
6429 },
6430
6431 'Matrix, Array': function (x, y) {
6432 // use matrix implementation
6433 return larger(x, matrix(y));
6434 },
6435
6436 'Matrix, any': function (x, y) {
6437 // result
6438 var c;
6439 // check storage format
6440 switch (x.storage()) {
6441 case 'sparse':
6442 c = algorithm12(x, y, larger, false);
6443 break;
6444 default:
6445 c = algorithm14(x, y, larger, false);
6446 break;
6447 }
6448 return c;
6449 },
6450
6451 'any, Matrix': function (x, y) {
6452 // result
6453 var c;
6454 // check storage format
6455 switch (y.storage()) {
6456 case 'sparse':
6457 c = algorithm12(y, x, larger, true);
6458 break;
6459 default:
6460 c = algorithm14(y, x, larger, true);
6461 break;
6462 }
6463 return c;
6464 },
6465
6466 'Array, any': function (x, y) {
6467 // use matrix implementation
6468 return algorithm14(matrix(x), y, larger, false).valueOf();
6469 },
6470
6471 'any, Array': function (x, y) {
6472 // use matrix implementation
6473 return algorithm14(matrix(y), x, larger, true).valueOf();
6474 }
6475 });
6476
6477 larger.toTex = {
6478 2: '\\left(${args[0]}' + latex.operators['larger'] + '${args[1]}\\right)'
6479 };
6480
6481 return larger;
6482}
6483
6484exports.name = 'larger';
6485exports.factory = factory;
6486
6487
6488/***/ }),
6489/* 35 */
6490/***/ (function(module, exports, __webpack_require__) {
6491
6492"use strict";
6493
6494
6495var deepMap = __webpack_require__(1);
6496
6497function factory (type, config, load, typed) {
6498 var latex = __webpack_require__(4);
6499
6500 /**
6501 * Inverse the sign of a value, apply a unary minus operation.
6502 *
6503 * For matrices, the function is evaluated element wise. Boolean values and
6504 * strings will be converted to a number. For complex numbers, both real and
6505 * complex value are inverted.
6506 *
6507 * Syntax:
6508 *
6509 * math.unaryMinus(x)
6510 *
6511 * Examples:
6512 *
6513 * math.unaryMinus(3.5); // returns -3.5
6514 * math.unaryMinus(-4.2); // returns 4.2
6515 *
6516 * See also:
6517 *
6518 * add, subtract, unaryPlus
6519 *
6520 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Number to be inverted.
6521 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Returns the value with inverted sign.
6522 */
6523 var unaryMinus = typed('unaryMinus', {
6524 'number': function (x) {
6525 return -x;
6526 },
6527
6528 'Complex': function (x) {
6529 return x.neg();
6530 },
6531
6532 'BigNumber': function (x) {
6533 return x.neg();
6534 },
6535
6536 'Fraction': function (x) {
6537 return x.neg();
6538 },
6539
6540 'Unit': function (x) {
6541 var res = x.clone();
6542 res.value = unaryMinus(x.value);
6543 return res;
6544 },
6545
6546 'Array | Matrix': function (x) {
6547 // deep map collection, skip zeros since unaryMinus(0) = 0
6548 return deepMap(x, unaryMinus, true);
6549 }
6550
6551 // TODO: add support for string
6552 });
6553
6554 unaryMinus.toTex = {
6555 1: latex.operators['unaryMinus'] + '\\left(${args[0]}\\right)'
6556 };
6557
6558 return unaryMinus;
6559}
6560
6561exports.name = 'unaryMinus';
6562exports.factory = factory;
6563
6564
6565/***/ }),
6566/* 36 */
6567/***/ (function(module, exports, __webpack_require__) {
6568
6569"use strict";
6570
6571
6572var latex = __webpack_require__(4);
6573var stringify = __webpack_require__(9).stringify;
6574var escape = __webpack_require__(9).escape;
6575var hasOwnProperty = __webpack_require__(5).hasOwnProperty;
6576var getSafeProperty = __webpack_require__(13).getSafeProperty;
6577
6578function factory (type, config, load, typed, math) {
6579 var register = load(__webpack_require__(7)).register;
6580 var compile = load(__webpack_require__(7)).compile;
6581 var Node = load(__webpack_require__(15));
6582
6583 /**
6584 * Check whether some name is a valueless unit like "inch".
6585 * @param {string} name
6586 * @return {boolean}
6587 */
6588 function isValuelessUnit (name) {
6589 return type.Unit ? type.Unit.isValuelessUnit(name) : false;
6590 }
6591
6592 /**
6593 * @constructor SymbolNode
6594 * @extends {Node}
6595 * A symbol node can hold and resolve a symbol
6596 * @param {string} name
6597 * @extends {Node}
6598 */
6599 function SymbolNode(name) {
6600 if (!(this instanceof SymbolNode)) {
6601 throw new SyntaxError('Constructor must be called with the new operator');
6602 }
6603
6604 // validate input
6605 if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"');
6606
6607 this.name = name;
6608 }
6609
6610 SymbolNode.prototype = new Node();
6611
6612 SymbolNode.prototype.type = 'SymbolNode';
6613
6614 SymbolNode.prototype.isSymbolNode = true;
6615
6616 /**
6617 * Compile the node to javascript code
6618 * @param {SymbolNode} node The node to be compiled
6619 * @param {Object} defs Object which can be used to define functions
6620 * or constants globally available for the compiled
6621 * expression
6622 * @param {Object} args Object with local function arguments, the key is
6623 * the name of the argument, and the value is `true`.
6624 * The object may not be mutated, but must be
6625 * extended instead.
6626 * @return {string} js
6627 * @private
6628 */
6629 function compileSymbolNode(node, defs, args) {
6630 if (!(node instanceof SymbolNode)) {
6631 throw new TypeError('No valid SymbolNode')
6632 }
6633
6634 // add a function to the definitions
6635 defs['undef'] = undef;
6636 defs['Unit'] = type.Unit;
6637 defs.getSafeProperty = getSafeProperty;
6638 defs.hasOwnProperty = hasOwnProperty;
6639
6640 var jsName = stringify(node.name); // escaped node name inside double quotes
6641
6642 if (hasOwnProperty(args, node.name)) {
6643 // this is a FunctionAssignment argument
6644 // (like an x when inside the expression of a function assignment `f(x) = ...`)
6645 return args[node.name];
6646 }
6647 else if (node.name in defs.math) {
6648 return '(' + jsName + ' in scope ' +
6649 '? getSafeProperty(scope, ' + jsName + ') ' +
6650 ': getSafeProperty(math, ' + jsName + '))';
6651 }
6652 else {
6653 return '(' +
6654 jsName + ' in scope ' +
6655 '? getSafeProperty(scope, ' + jsName + ') ' +
6656 ': ' + (isValuelessUnit(node.name)
6657 ? 'new Unit(null, ' + jsName + ')'
6658 : 'undef(' + jsName + ')') +
6659 ')';
6660 }
6661 }
6662
6663 // register the compile function
6664 register(SymbolNode.prototype.type, compileSymbolNode);
6665
6666 /**
6667 * Execute a callback for each of the child nodes of this node
6668 * @param {function(child: Node, path: string, parent: Node)} callback
6669 */
6670 SymbolNode.prototype.forEach = function (callback) {
6671 // nothing to do, we don't have childs
6672 };
6673
6674 /**
6675 * Create a new SymbolNode having it's childs be the results of calling
6676 * the provided callback function for each of the childs of the original node.
6677 * @param {function(child: Node, path: string, parent: Node) : Node} callback
6678 * @returns {SymbolNode} Returns a clone of the node
6679 */
6680 SymbolNode.prototype.map = function (callback) {
6681 return this.clone();
6682 };
6683
6684 /**
6685 * Throws an error 'Undefined symbol {name}'
6686 * @param {string} name
6687 */
6688 function undef (name) {
6689 throw new Error('Undefined symbol ' + name);
6690 }
6691
6692 /**
6693 * Create a clone of this node, a shallow copy
6694 * @return {SymbolNode}
6695 */
6696 SymbolNode.prototype.clone = function() {
6697 return new SymbolNode(this.name);
6698 };
6699
6700 /**
6701 * Get string representation
6702 * @param {Object} options
6703 * @return {string} str
6704 * @override
6705 */
6706 SymbolNode.prototype._toString = function(options) {
6707 return this.name;
6708 };
6709
6710 /**
6711 * Get HTML representation
6712 * @param {Object} options
6713 * @return {string} str
6714 * @override
6715 */
6716 SymbolNode.prototype.toHTML = function(options) {
6717 var name = escape(this.name);
6718
6719 if (name == "true" || name == "false") {
6720 return '<span class="math-symbol math-boolean">' + name + '</span>';
6721 }
6722 else if (name == "i") {
6723 return '<span class="math-symbol math-imaginary-symbol">' + name + '</span>';
6724 }
6725 else if (name == "Infinity") {
6726 return '<span class="math-symbol math-infinity-symbol">' + name + '</span>';
6727 }
6728 else if (name == "NaN") {
6729 return '<span class="math-symbol math-nan-symbol">' + name + '</span>';
6730 }
6731 else if (name == "null") {
6732 return '<span class="math-symbol math-null-symbol">' + name + '</span>';
6733 }
6734 else if (name == "uninitialized") {
6735 return '<span class="math-symbol math-uninitialized-symbol">' + name + '</span>';
6736 }
6737
6738 return '<span class="math-symbol">' + name + '</span>';
6739 };
6740
6741 /**
6742 * Get LaTeX representation
6743 * @param {Object} options
6744 * @return {string} str
6745 * @override
6746 */
6747 SymbolNode.prototype._toTex = function(options) {
6748 var isUnit = false;
6749 if ((typeof math[this.name] === 'undefined') && isValuelessUnit(this.name)) {
6750 isUnit = true;
6751 }
6752 var symbol = latex.toSymbol(this.name, isUnit);
6753 if (symbol[0] === '\\') {
6754 //no space needed if the symbol starts with '\'
6755 return symbol;
6756 }
6757 //the space prevents symbols from breaking stuff like '\cdot' if it's written right before the symbol
6758 return ' ' + symbol;
6759 };
6760
6761 return SymbolNode;
6762}
6763
6764exports.name = 'SymbolNode';
6765exports.path = 'expression.node';
6766exports.math = true; // request access to the math namespace as 5th argument of the factory function
6767exports.factory = factory;
6768
6769
6770/***/ }),
6771/* 37 */
6772/***/ (function(module, exports, __webpack_require__) {
6773
6774"use strict";
6775
6776
6777/**
6778 * Compares two BigNumbers.
6779 * @param {BigNumber} x First value to compare
6780 * @param {BigNumber} y Second value to compare
6781 * @param {number} [epsilon] The maximum relative difference between x and y
6782 * If epsilon is undefined or null, the function will
6783 * test whether x and y are exactly equal.
6784 * @return {boolean} whether the two numbers are nearly equal
6785 */
6786module.exports = function nearlyEqual(x, y, epsilon) {
6787 // if epsilon is null or undefined, test whether x and y are exactly equal
6788 if (epsilon == null) {
6789 return x.eq(y);
6790 }
6791
6792
6793 // use "==" operator, handles infinities
6794 if (x.eq(y)) {
6795 return true;
6796 }
6797
6798 // NaN
6799 if (x.isNaN() || y.isNaN()) {
6800 return false;
6801 }
6802
6803 // at this point x and y should be finite
6804 if(x.isFinite() && y.isFinite()) {
6805 // check numbers are very close, needed when comparing numbers near zero
6806 var diff = x.minus(y).abs();
6807 if (diff.isZero()) {
6808 return true;
6809 }
6810 else {
6811 // use relative error
6812 var max = x.constructor.max(x.abs(), y.abs());
6813 return diff.lte(max.times(epsilon));
6814 }
6815 }
6816
6817 // Infinite and Number or negative Infinite and positive Infinite cases
6818 return false;
6819};
6820
6821
6822/***/ }),
6823/* 38 */
6824/***/ (function(module, exports, __webpack_require__) {
6825
6826"use strict";
6827
6828
6829function factory (type, config, load, typed) {
6830
6831 var DenseMatrix = type.DenseMatrix;
6832
6833 /**
6834 * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b).
6835 * Callback function invoked NZ times (number of nonzero items in S).
6836 *
6837 *
6838 * ┌ f(Sij, b) ; S(i,j) !== 0
6839 * C(i,j) = ┤
6840 * └ b ; otherwise
6841 *
6842 *
6843 * @param {Matrix} s The SparseMatrix instance (S)
6844 * @param {Scalar} b The Scalar value
6845 * @param {Function} callback The f(Aij,b) operation to invoke
6846 * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij)
6847 *
6848 * @return {Matrix} DenseMatrix (C)
6849 *
6850 * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813
6851 */
6852 var algorithm10 = function (s, b, callback, inverse) {
6853 // sparse matrix arrays
6854 var avalues = s._values;
6855 var aindex = s._index;
6856 var aptr = s._ptr;
6857 var asize = s._size;
6858 var adt = s._datatype;
6859
6860 // sparse matrix cannot be a Pattern matrix
6861 if (!avalues)
6862 throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value');
6863
6864 // rows & columns
6865 var rows = asize[0];
6866 var columns = asize[1];
6867
6868 // datatype
6869 var dt;
6870 // callback signature to use
6871 var cf = callback;
6872
6873 // process data types
6874 if (typeof adt === 'string') {
6875 // datatype
6876 dt = adt;
6877 // convert b to the same datatype
6878 b = typed.convert(b, dt);
6879 // callback
6880 cf = typed.find(callback, [dt, dt]);
6881 }
6882
6883 // result arrays
6884 var cdata = [];
6885 // matrix
6886 var c = new DenseMatrix({
6887 data: cdata,
6888 size: [rows, columns],
6889 datatype: dt
6890 });
6891
6892 // workspaces
6893 var x = [];
6894 // marks indicating we have a value in x for a given column
6895 var w = [];
6896
6897 // loop columns
6898 for (var j = 0; j < columns; j++) {
6899 // columns mark
6900 var mark = j + 1;
6901 // values in j
6902 for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
6903 // row
6904 var r = aindex[k];
6905 // update workspace
6906 x[r] = avalues[k];
6907 w[r] = mark;
6908 }
6909 // loop rows
6910 for (var i = 0; i < rows; i++) {
6911 // initialize C on first column
6912 if (j === 0) {
6913 // create row array
6914 cdata[i] = [];
6915 }
6916 // check sparse matrix has a value @ i,j
6917 if (w[i] === mark) {
6918 // invoke callback, update C
6919 cdata[i][j] = inverse ? cf(b, x[i]) : cf(x[i], b);
6920 }
6921 else {
6922 // dense matrix value @ i, j
6923 cdata[i][j] = b;
6924 }
6925 }
6926 }
6927
6928 // return sparse matrix
6929 return c;
6930 };
6931
6932 return algorithm10;
6933}
6934
6935exports.name = 'algorithm10';
6936exports.factory = factory;
6937
6938
6939/***/ }),
6940/* 39 */
6941/***/ (function(module, exports, __webpack_require__) {
6942
6943"use strict";
6944
6945
6946var nearlyEqual = __webpack_require__(3).nearlyEqual;
6947var bigNearlyEqual = __webpack_require__(37);
6948
6949function factory (type, config, load, typed) {
6950
6951 var matrix = load(__webpack_require__(0));
6952
6953 var algorithm03 = load(__webpack_require__(17));
6954 var algorithm07 = load(__webpack_require__(26));
6955 var algorithm12 = load(__webpack_require__(18));
6956 var algorithm13 = load(__webpack_require__(8));
6957 var algorithm14 = load(__webpack_require__(6));
6958
6959 var latex = __webpack_require__(4);
6960
6961 /**
6962 * Test whether value x is smaller than y.
6963 *
6964 * The function returns true when x is smaller than y and the relative
6965 * difference between x and y is smaller than the configured epsilon. The
6966 * function cannot be used to compare values smaller than approximately 2.22e-16.
6967 *
6968 * For matrices, the function is evaluated element wise.
6969 *
6970 * Syntax:
6971 *
6972 * math.smaller(x, y)
6973 *
6974 * Examples:
6975 *
6976 * math.smaller(2, 3); // returns true
6977 * math.smaller(5, 2 * 2); // returns false
6978 *
6979 * var a = math.unit('5 cm');
6980 * var b = math.unit('2 inch');
6981 * math.smaller(a, b); // returns true
6982 *
6983 * See also:
6984 *
6985 * equal, unequal, smallerEq, smaller, smallerEq, compare
6986 *
6987 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
6988 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
6989 * @return {boolean | Array | Matrix} Returns true when the x is smaller than y, else returns false
6990 */
6991 var smaller = typed('smaller', {
6992
6993 'boolean, boolean': function (x, y) {
6994 return x < y;
6995 },
6996
6997 'number, number': function (x, y) {
6998 return x < y && !nearlyEqual(x, y, config.epsilon);
6999 },
7000
7001 'BigNumber, BigNumber': function (x, y) {
7002 return x.lt(y) && !bigNearlyEqual(x, y, config.epsilon);
7003 },
7004
7005 'Fraction, Fraction': function (x, y) {
7006 return x.compare(y) === -1;
7007 },
7008
7009 'Complex, Complex': function (x, y) {
7010 throw new TypeError('No ordering relation is defined for complex numbers');
7011 },
7012
7013 'Unit, Unit': function (x, y) {
7014 if (!x.equalBase(y)) {
7015 throw new Error('Cannot compare units with different base');
7016 }
7017 return smaller(x.value, y.value);
7018 },
7019
7020 'string, string': function (x, y) {
7021 return x < y;
7022 },
7023
7024 'Matrix, Matrix': function (x, y) {
7025 // result
7026 var c;
7027
7028 // process matrix storage
7029 switch (x.storage()) {
7030 case 'sparse':
7031 switch (y.storage()) {
7032 case 'sparse':
7033 // sparse + sparse
7034 c = algorithm07(x, y, smaller);
7035 break;
7036 default:
7037 // sparse + dense
7038 c = algorithm03(y, x, smaller, true);
7039 break;
7040 }
7041 break;
7042 default:
7043 switch (y.storage()) {
7044 case 'sparse':
7045 // dense + sparse
7046 c = algorithm03(x, y, smaller, false);
7047 break;
7048 default:
7049 // dense + dense
7050 c = algorithm13(x, y, smaller);
7051 break;
7052 }
7053 break;
7054 }
7055 return c;
7056 },
7057
7058 'Array, Array': function (x, y) {
7059 // use matrix implementation
7060 return smaller(matrix(x), matrix(y)).valueOf();
7061 },
7062
7063 'Array, Matrix': function (x, y) {
7064 // use matrix implementation
7065 return smaller(matrix(x), y);
7066 },
7067
7068 'Matrix, Array': function (x, y) {
7069 // use matrix implementation
7070 return smaller(x, matrix(y));
7071 },
7072
7073 'Matrix, any': function (x, y) {
7074 // result
7075 var c;
7076 // check storage format
7077 switch (x.storage()) {
7078 case 'sparse':
7079 c = algorithm12(x, y, smaller, false);
7080 break;
7081 default:
7082 c = algorithm14(x, y, smaller, false);
7083 break;
7084 }
7085 return c;
7086 },
7087
7088 'any, Matrix': function (x, y) {
7089 // result
7090 var c;
7091 // check storage format
7092 switch (y.storage()) {
7093 case 'sparse':
7094 c = algorithm12(y, x, smaller, true);
7095 break;
7096 default:
7097 c = algorithm14(y, x, smaller, true);
7098 break;
7099 }
7100 return c;
7101 },
7102
7103 'Array, any': function (x, y) {
7104 // use matrix implementation
7105 return algorithm14(matrix(x), y, smaller, false).valueOf();
7106 },
7107
7108 'any, Array': function (x, y) {
7109 // use matrix implementation
7110 return algorithm14(matrix(y), x, smaller, true).valueOf();
7111 }
7112 });
7113
7114 smaller.toTex = {
7115 2: '\\left(${args[0]}' + latex.operators['smaller'] + '${args[1]}\\right)'
7116 };
7117
7118 return smaller;
7119}
7120
7121exports.name = 'smaller';
7122exports.factory = factory;
7123
7124
7125/***/ }),
7126/* 40 */
7127/***/ (function(module, exports, __webpack_require__) {
7128
7129"use strict";
7130
7131
7132var isInteger = __webpack_require__(3).isInteger;
7133var resize = __webpack_require__(2).resize;
7134
7135function factory (type, config, load, typed) {
7136 var matrix = load(__webpack_require__(0));
7137
7138 /**
7139 * Create a matrix filled with zeros. The created matrix can have one or
7140 * multiple dimensions.
7141 *
7142 * Syntax:
7143 *
7144 * math.zeros(m)
7145 * math.zeros(m, format)
7146 * math.zeros(m, n)
7147 * math.zeros(m, n, format)
7148 * math.zeros([m, n])
7149 * math.zeros([m, n], format)
7150 *
7151 * Examples:
7152 *
7153 * math.zeros(3); // returns [0, 0, 0]
7154 * math.zeros(3, 2); // returns [[0, 0], [0, 0], [0, 0]]
7155 * math.zeros(3, 'dense'); // returns [0, 0, 0]
7156 *
7157 * var A = [[1, 2, 3], [4, 5, 6]];
7158 * math.zeros(math.size(A)); // returns [[0, 0, 0], [0, 0, 0]]
7159 *
7160 * See also:
7161 *
7162 * ones, eye, size, range
7163 *
7164 * @param {...number | Array} size The size of each dimension of the matrix
7165 * @param {string} [format] The Matrix storage format
7166 *
7167 * @return {Array | Matrix} A matrix filled with zeros
7168 */
7169 var zeros = typed('zeros', {
7170 '': function () {
7171 return (config.matrix === 'Array')
7172 ? _zeros([])
7173 : _zeros([], 'default');
7174 },
7175
7176 // math.zeros(m, n, p, ..., format)
7177 // TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this
7178 '...number | BigNumber | string': function (size) {
7179 var last = size[size.length - 1];
7180 if (typeof last === 'string') {
7181 var format = size.pop();
7182 return _zeros(size, format);
7183 }
7184 else if (config.matrix === 'Array') {
7185 return _zeros(size);
7186 }
7187 else {
7188 return _zeros(size, 'default');
7189 }
7190 },
7191
7192 'Array': _zeros,
7193
7194 'Matrix': function (size) {
7195 var format = size.storage();
7196 return _zeros(size.valueOf(), format);
7197 },
7198
7199 'Array | Matrix, string': function (size, format) {
7200 return _zeros (size.valueOf(), format);
7201 }
7202 });
7203
7204 zeros.toTex = undefined; // use default template
7205
7206 return zeros;
7207
7208 /**
7209 * Create an Array or Matrix with zeros
7210 * @param {Array} size
7211 * @param {string} [format='default']
7212 * @return {Array | Matrix}
7213 * @private
7214 */
7215 function _zeros(size, format) {
7216 var hasBigNumbers = _normalize(size);
7217 var defaultValue = hasBigNumbers ? new type.BigNumber(0) : 0;
7218 _validate(size);
7219
7220 if (format) {
7221 // return a matrix
7222 var m = matrix(format);
7223 if (size.length > 0) {
7224 return m.resize(size, defaultValue);
7225 }
7226 return m;
7227 }
7228 else {
7229 // return an Array
7230 var arr = [];
7231 if (size.length > 0) {
7232 return resize(arr, size, defaultValue);
7233 }
7234 return arr;
7235 }
7236 }
7237
7238 // replace BigNumbers with numbers, returns true if size contained BigNumbers
7239 function _normalize(size) {
7240 var hasBigNumbers = false;
7241 size.forEach(function (value, index, arr) {
7242 if (type.isBigNumber(value)) {
7243 hasBigNumbers = true;
7244 arr[index] = value.toNumber();
7245 }
7246 });
7247 return hasBigNumbers;
7248 }
7249
7250 // validate arguments
7251 function _validate (size) {
7252 size.forEach(function (value) {
7253 if (typeof value !== 'number' || !isInteger(value) || value < 0) {
7254 throw new Error('Parameters in function zeros must be positive integers');
7255 }
7256 });
7257 }
7258}
7259
7260// TODO: zeros contains almost the same code as ones. Reuse this?
7261
7262exports.name = 'zeros';
7263exports.factory = factory;
7264
7265
7266/***/ }),
7267/* 41 */
7268/***/ (function(module, exports, __webpack_require__) {
7269
7270"use strict";
7271
7272
7273var ArgumentsError = __webpack_require__(44);
7274var deepMap = __webpack_require__(1);
7275
7276function factory (type, config, load, typed) {
7277 var AccessorNode = load(__webpack_require__(103));
7278 var ArrayNode = load(__webpack_require__(80));
7279 var AssignmentNode = load(__webpack_require__(105));
7280 var BlockNode = load(__webpack_require__(106));
7281 var ConditionalNode = load(__webpack_require__(107));
7282 var ConstantNode = load(__webpack_require__(47));
7283 var FunctionAssignmentNode = load(__webpack_require__(108));
7284 var IndexNode = load(__webpack_require__(78));
7285 var ObjectNode = load(__webpack_require__(110));
7286 var OperatorNode = load(__webpack_require__(55));
7287 var ParenthesisNode = load(__webpack_require__(63));
7288 var FunctionNode = load(__webpack_require__(56));
7289 var RangeNode = load(__webpack_require__(79));
7290 var SymbolNode = load(__webpack_require__(36));
7291
7292
7293 /**
7294 * Parse an expression. Returns a node tree, which can be evaluated by
7295 * invoking node.eval();
7296 *
7297 * Syntax:
7298 *
7299 * parse(expr)
7300 * parse(expr, options)
7301 * parse([expr1, expr2, expr3, ...])
7302 * parse([expr1, expr2, expr3, ...], options)
7303 *
7304 * Example:
7305 *
7306 * var node = parse('sqrt(3^2 + 4^2)');
7307 * node.compile(math).eval(); // 5
7308 *
7309 * var scope = {a:3, b:4}
7310 * var node = parse('a * b'); // 12
7311 * var code = node.compile(math);
7312 * code.eval(scope); // 12
7313 * scope.a = 5;
7314 * code.eval(scope); // 20
7315 *
7316 * var nodes = math.parse(['a = 3', 'b = 4', 'a * b']);
7317 * nodes[2].compile(math).eval(); // 12
7318 *
7319 * @param {string | string[] | Matrix} expr
7320 * @param {{nodes: Object<string, Node>}} [options] Available options:
7321 * - `nodes` a set of custom nodes
7322 * @return {Node | Node[]} node
7323 * @throws {Error}
7324 */
7325 function parse (expr, options) {
7326 if (arguments.length != 1 && arguments.length != 2) {
7327 throw new ArgumentsError('parse', arguments.length, 1, 2);
7328 }
7329
7330 // pass extra nodes
7331 extra_nodes = (options && options.nodes) ? options.nodes : {};
7332
7333 if (typeof expr === 'string') {
7334 // parse a single expression
7335 expression = expr;
7336 return parseStart();
7337 }
7338 else if (Array.isArray(expr) || expr instanceof type.Matrix) {
7339 // parse an array or matrix with expressions
7340 return deepMap(expr, function (elem) {
7341 if (typeof elem !== 'string') throw new TypeError('String expected');
7342
7343 expression = elem;
7344 return parseStart();
7345 });
7346 }
7347 else {
7348 // oops
7349 throw new TypeError('String or matrix expected');
7350 }
7351 }
7352
7353 // token types enumeration
7354 var TOKENTYPE = {
7355 NULL : 0,
7356 DELIMITER : 1,
7357 NUMBER : 2,
7358 SYMBOL : 3,
7359 UNKNOWN : 4
7360 };
7361
7362 // map with all delimiters
7363 var DELIMITERS = {
7364 ',': true,
7365 '(': true,
7366 ')': true,
7367 '[': true,
7368 ']': true,
7369 '{': true,
7370 '}': true,
7371 '\"': true,
7372 ';': true,
7373
7374 '+': true,
7375 '-': true,
7376 '*': true,
7377 '.*': true,
7378 '/': true,
7379 './': true,
7380 '%': true,
7381 '^': true,
7382 '.^': true,
7383 '~': true,
7384 '!': true,
7385 '&': true,
7386 '|': true,
7387 '^|': true,
7388 '\'': true,
7389 '=': true,
7390 ':': true,
7391 '?': true,
7392
7393 '==': true,
7394 '!=': true,
7395 '<': true,
7396 '>': true,
7397 '<=': true,
7398 '>=': true,
7399
7400 '<<': true,
7401 '>>': true,
7402 '>>>': true
7403 };
7404
7405 // map with all named delimiters
7406 var NAMED_DELIMITERS = {
7407 'mod': true,
7408 'to': true,
7409 'in': true,
7410 'and': true,
7411 'xor': true,
7412 'or': true,
7413 'not': true
7414 };
7415
7416 var extra_nodes = {}; // current extra nodes
7417 var expression = ''; // current expression
7418 var comment = ''; // last parsed comment
7419 var index = 0; // current index in expr
7420 var c = ''; // current token character in expr
7421 var token = ''; // current token
7422 var token_type = TOKENTYPE.NULL; // type of the token
7423 var nesting_level = 0; // level of nesting inside parameters, used to ignore newline characters
7424 var conditional_level = null; // when a conditional is being parsed, the level of the conditional is stored here
7425
7426 /**
7427 * Get the first character from the expression.
7428 * The character is stored into the char c. If the end of the expression is
7429 * reached, the function puts an empty string in c.
7430 * @private
7431 */
7432 function first() {
7433 index = 0;
7434 c = expression.charAt(0);
7435 nesting_level = 0;
7436 conditional_level = null;
7437 }
7438
7439 /**
7440 * Get the next character from the expression.
7441 * The character is stored into the char c. If the end of the expression is
7442 * reached, the function puts an empty string in c.
7443 * @private
7444 */
7445 function next() {
7446 index++;
7447 c = expression.charAt(index);
7448 }
7449
7450 /**
7451 * Preview the previous character from the expression.
7452 * @return {string} cNext
7453 * @private
7454 */
7455 function prevPreview() {
7456 return expression.charAt(index - 1);
7457 }
7458
7459 /**
7460 * Preview the next character from the expression.
7461 * @return {string} cNext
7462 * @private
7463 */
7464 function nextPreview() {
7465 return expression.charAt(index + 1);
7466 }
7467
7468 /**
7469 * Preview the second next character from the expression.
7470 * @return {string} cNext
7471 * @private
7472 */
7473 function nextNextPreview() {
7474 return expression.charAt(index + 2);
7475 }
7476
7477 /**
7478 * Get next token in the current string expr.
7479 * The token and token type are available as token and token_type
7480 * @private
7481 */
7482 function getToken() {
7483 token_type = TOKENTYPE.NULL;
7484 token = '';
7485 comment = '';
7486
7487 // skip over whitespaces
7488 // space, tab, and newline when inside parameters
7489 while (parse.isWhitespace(c, nesting_level)) {
7490 next();
7491 }
7492
7493 // skip comment
7494 if (c == '#') {
7495 while (c != '\n' && c != '') {
7496 comment += c;
7497 next();
7498 }
7499 }
7500
7501 // check for end of expression
7502 if (c == '') {
7503 // token is still empty
7504 token_type = TOKENTYPE.DELIMITER;
7505 return;
7506 }
7507
7508 // check for new line character
7509 if (c == '\n' && !nesting_level) {
7510 token_type = TOKENTYPE.DELIMITER;
7511 token = c;
7512 next();
7513 return;
7514 }
7515
7516 // check for delimiters consisting of 3 characters
7517 var c2 = c + nextPreview();
7518 var c3 = c2 + nextNextPreview();
7519 if (c3.length == 3 && DELIMITERS[c3]) {
7520 token_type = TOKENTYPE.DELIMITER;
7521 token = c3;
7522 next();
7523 next();
7524 next();
7525 return;
7526 }
7527
7528 // check for delimiters consisting of 2 characters
7529 if (c2.length == 2 && DELIMITERS[c2]) {
7530 token_type = TOKENTYPE.DELIMITER;
7531 token = c2;
7532 next();
7533 next();
7534 return;
7535 }
7536
7537 // check for delimiters consisting of 1 character
7538 if (DELIMITERS[c]) {
7539 token_type = TOKENTYPE.DELIMITER;
7540 token = c;
7541 next();
7542 return;
7543 }
7544
7545 // check for a number
7546 if (parse.isDigitDot(c)) {
7547 token_type = TOKENTYPE.NUMBER;
7548
7549 // get number, can have a single dot
7550 if (c == '.') {
7551 token += c;
7552 next();
7553
7554 if (!parse.isDigit(c)) {
7555 // this is no number, it is just a dot (can be dot notation)
7556 token_type = TOKENTYPE.DELIMITER;
7557 }
7558 }
7559 else {
7560 while (parse.isDigit(c)) {
7561 token += c;
7562 next();
7563 }
7564 if (parse.isDecimalMark(c, nextPreview())) {
7565 token += c;
7566 next();
7567 }
7568 }
7569 while (parse.isDigit(c)) {
7570 token += c;
7571 next();
7572 }
7573
7574 // check for exponential notation like "2.3e-4", "1.23e50" or "2e+4"
7575 c2 = nextPreview();
7576 if (c == 'E' || c == 'e') {
7577 if (parse.isDigit(c2) || c2 == '-' || c2 == '+') {
7578 token += c;
7579 next();
7580
7581 if (c == '+' || c == '-') {
7582 token += c;
7583 next();
7584 }
7585
7586 // Scientific notation MUST be followed by an exponent
7587 if (!parse.isDigit(c)) {
7588 throw createSyntaxError('Digit expected, got "' + c + '"');
7589 }
7590
7591 while (parse.isDigit(c)) {
7592 token += c;
7593 next();
7594 }
7595
7596 if (parse.isDecimalMark(c, nextPreview())) {
7597 throw createSyntaxError('Digit expected, got "' + c + '"');
7598 }
7599 }
7600 else if (c2 == '.') {
7601 next();
7602 throw createSyntaxError('Digit expected, got "' + c + '"');
7603 }
7604 }
7605
7606 return;
7607 }
7608
7609 // check for variables, functions, named operators
7610 if (parse.isAlpha(c, prevPreview(), nextPreview())) {
7611 while (parse.isAlpha(c, prevPreview(), nextPreview()) || parse.isDigit(c)) {
7612 token += c;
7613 next();
7614 }
7615
7616 if (NAMED_DELIMITERS.hasOwnProperty(token)) {
7617 token_type = TOKENTYPE.DELIMITER;
7618 }
7619 else {
7620 token_type = TOKENTYPE.SYMBOL;
7621 }
7622
7623 return;
7624 }
7625
7626 // something unknown is found, wrong characters -> a syntax error
7627 token_type = TOKENTYPE.UNKNOWN;
7628 while (c != '') {
7629 token += c;
7630 next();
7631 }
7632 throw createSyntaxError('Syntax error in part "' + token + '"');
7633 }
7634
7635 /**
7636 * Get next token and skip newline tokens
7637 */
7638 function getTokenSkipNewline () {
7639 do {
7640 getToken();
7641 }
7642 while (token == '\n');
7643 }
7644
7645 /**
7646 * Open parameters.
7647 * New line characters will be ignored until closeParams() is called
7648 */
7649 function openParams() {
7650 nesting_level++;
7651 }
7652
7653 /**
7654 * Close parameters.
7655 * New line characters will no longer be ignored
7656 */
7657 function closeParams() {
7658 nesting_level--;
7659 }
7660
7661 /**
7662 * Checks whether the current character `c` is a valid alpha character:
7663 *
7664 * - A latin letter (upper or lower case) Ascii: a-z, A-Z
7665 * - An underscore Ascii: _
7666 * - A dollar sign Ascii: $
7667 * - A latin letter with accents Unicode: \u00C0 - \u02AF
7668 * - A greek letter Unicode: \u0370 - \u03FF
7669 * - A mathematical alphanumeric symbol Unicode: \u{1D400} - \u{1D7FF} excluding invalid code points
7670 *
7671 * The previous and next characters are needed to determine whether
7672 * this character is part of a unicode surrogate pair.
7673 *
7674 * @param {string} c Current character in the expression
7675 * @param {string} cPrev Previous character
7676 * @param {string} cNext Next character
7677 * @return {boolean}
7678 */
7679 parse.isAlpha = function isAlpha (c, cPrev, cNext) {
7680 return parse.isValidLatinOrGreek(c)
7681 || parse.isValidMathSymbol(c, cNext)
7682 || parse.isValidMathSymbol(cPrev, c);
7683 };
7684
7685 /**
7686 * Test whether a character is a valid latin, greek, or letter-like character
7687 * @param {string} c
7688 * @return {boolean}
7689 */
7690 parse.isValidLatinOrGreek = function isValidLatinOrGreek (c) {
7691 return /^[a-zA-Z_$\u00C0-\u02AF\u0370-\u03FF\u2100-\u214F]$/.test(c);
7692 };
7693
7694 /**
7695 * Test whether two given 16 bit characters form a surrogate pair of a
7696 * unicode math symbol.
7697 *
7698 * http://unicode-table.com/en/
7699 * http://www.wikiwand.com/en/Mathematical_operators_and_symbols_in_Unicode
7700 *
7701 * Note: In ES6 will be unicode aware:
7702 * http://stackoverflow.com/questions/280712/javascript-unicode-regexes
7703 * https://mathiasbynens.be/notes/es6-unicode-regex
7704 *
7705 * @param {string} high
7706 * @param {string} low
7707 * @return {boolean}
7708 */
7709 parse.isValidMathSymbol = function isValidMathSymbol (high, low) {
7710 return /^[\uD835]$/.test(high) &&
7711 /^[\uDC00-\uDFFF]$/.test(low) &&
7712 /^[^\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);
7713 };
7714
7715 /**
7716 * Check whether given character c is a white space character: space, tab, or enter
7717 * @param {string} c
7718 * @param {number} nestingLevel
7719 * @return {boolean}
7720 */
7721 parse.isWhitespace = function isWhitespace (c, nestingLevel) {
7722 // TODO: also take '\r' carriage return as newline? Or does that give problems on mac?
7723 return c == ' ' || c == '\t' || (c == '\n' && nestingLevel > 0);
7724 };
7725
7726 /**
7727 * Test whether the character c is a decimal mark (dot).
7728 * This is the case when it's not the start of a delimiter '.*', './', or '.^'
7729 * @param {string} c
7730 * @param {string} cNext
7731 * @return {boolean}
7732 */
7733 parse.isDecimalMark = function isDecimalMark (c, cNext) {
7734 return c == '.' && cNext !== '/' && cNext !== '*' && cNext !== '^';
7735 };
7736
7737 /**
7738 * checks if the given char c is a digit or dot
7739 * @param {string} c a string with one character
7740 * @return {boolean}
7741 */
7742 parse.isDigitDot = function isDigitDot (c) {
7743 return ((c >= '0' && c <= '9') || c == '.');
7744 };
7745
7746 /**
7747 * checks if the given char c is a digit
7748 * @param {string} c a string with one character
7749 * @return {boolean}
7750 */
7751 parse.isDigit = function isDigit (c) {
7752 return (c >= '0' && c <= '9');
7753 };
7754
7755 /**
7756 * Start of the parse levels below, in order of precedence
7757 * @return {Node} node
7758 * @private
7759 */
7760 function parseStart () {
7761 // get the first character in expression
7762 first();
7763
7764 getToken();
7765
7766 var node = parseBlock();
7767
7768 // check for garbage at the end of the expression
7769 // an expression ends with a empty character '' and token_type DELIMITER
7770 if (token != '') {
7771 if (token_type == TOKENTYPE.DELIMITER) {
7772 // user entered a not existing operator like "//"
7773
7774 // TODO: give hints for aliases, for example with "<>" give as hint " did you mean != ?"
7775 throw createError('Unexpected operator ' + token);
7776 }
7777 else {
7778 throw createSyntaxError('Unexpected part "' + token + '"');
7779 }
7780 }
7781
7782 return node;
7783 }
7784
7785 /**
7786 * Parse a block with expressions. Expressions can be separated by a newline
7787 * character '\n', or by a semicolon ';'. In case of a semicolon, no output
7788 * of the preceding line is returned.
7789 * @return {Node} node
7790 * @private
7791 */
7792 function parseBlock () {
7793 var node;
7794 var blocks = [];
7795 var visible;
7796
7797 if (token != '' && token != '\n' && token != ';') {
7798 node = parseAssignment();
7799 node.comment = comment;
7800 }
7801
7802 // TODO: simplify this loop
7803 while (token == '\n' || token == ';') {
7804 if (blocks.length == 0 && node) {
7805 visible = (token != ';');
7806 blocks.push({
7807 node: node,
7808 visible: visible
7809 });
7810 }
7811
7812 getToken();
7813 if (token != '\n' && token != ';' && token != '') {
7814 node = parseAssignment();
7815 node.comment = comment;
7816
7817 visible = (token != ';');
7818 blocks.push({
7819 node: node,
7820 visible: visible
7821 });
7822 }
7823 }
7824
7825 if (blocks.length > 0) {
7826 return new BlockNode(blocks);
7827 }
7828 else {
7829 if (!node) {
7830 node = new ConstantNode('undefined', 'undefined');
7831 node.comment = comment;
7832 }
7833
7834 return node
7835 }
7836 }
7837
7838 /**
7839 * Assignment of a function or variable,
7840 * - can be a variable like 'a=2.3'
7841 * - or a updating an existing variable like 'matrix(2,3:5)=[6,7,8]'
7842 * - defining a function like 'f(x) = x^2'
7843 * @return {Node} node
7844 * @private
7845 */
7846 function parseAssignment () {
7847 var name, args, value, valid;
7848
7849 var node = parseConditional();
7850
7851 if (token == '=') {
7852 if (type.isSymbolNode(node)) {
7853 // parse a variable assignment like 'a = 2/3'
7854 name = node.name;
7855 getTokenSkipNewline();
7856 value = parseAssignment();
7857 return new AssignmentNode(new SymbolNode(name), value);
7858 }
7859 else if (type.isAccessorNode(node)) {
7860 // parse a matrix subset assignment like 'A[1,2] = 4'
7861 getTokenSkipNewline();
7862 value = parseAssignment();
7863 return new AssignmentNode(node.object, node.index, value);
7864 }
7865 else if (type.isFunctionNode(node) && type.isSymbolNode(node.fn)) {
7866 // parse function assignment like 'f(x) = x^2'
7867 valid = true;
7868 args = [];
7869
7870 name = node.name;
7871 node.args.forEach(function (arg, index) {
7872 if (type.isSymbolNode(arg)) {
7873 args[index] = arg.name;
7874 }
7875 else {
7876 valid = false;
7877 }
7878 });
7879
7880 if (valid) {
7881 getTokenSkipNewline();
7882 value = parseAssignment();
7883 return new FunctionAssignmentNode(name, args, value);
7884 }
7885 }
7886
7887 throw createSyntaxError('Invalid left hand side of assignment operator =');
7888 }
7889
7890 return node;
7891 }
7892
7893 /**
7894 * conditional operation
7895 *
7896 * condition ? truePart : falsePart
7897 *
7898 * Note: conditional operator is right-associative
7899 *
7900 * @return {Node} node
7901 * @private
7902 */
7903 function parseConditional () {
7904 var node = parseLogicalOr();
7905
7906 while (token == '?') {
7907 // set a conditional level, the range operator will be ignored as long
7908 // as conditional_level == nesting_level.
7909 var prev = conditional_level;
7910 conditional_level = nesting_level;
7911 getTokenSkipNewline();
7912
7913 var condition = node;
7914 var trueExpr = parseAssignment();
7915
7916 if (token != ':') throw createSyntaxError('False part of conditional expression expected');
7917
7918 conditional_level = null;
7919 getTokenSkipNewline();
7920
7921 var falseExpr = parseAssignment(); // Note: check for conditional operator again, right associativity
7922
7923 node = new ConditionalNode(condition, trueExpr, falseExpr);
7924
7925 // restore the previous conditional level
7926 conditional_level = prev;
7927 }
7928
7929 return node;
7930 }
7931
7932 /**
7933 * logical or, 'x or y'
7934 * @return {Node} node
7935 * @private
7936 */
7937 function parseLogicalOr() {
7938 var node = parseLogicalXor();
7939
7940 while (token == 'or') {
7941 getTokenSkipNewline();
7942 node = new OperatorNode('or', 'or', [node, parseLogicalXor()]);
7943 }
7944
7945 return node;
7946 }
7947
7948 /**
7949 * logical exclusive or, 'x xor y'
7950 * @return {Node} node
7951 * @private
7952 */
7953 function parseLogicalXor() {
7954 var node = parseLogicalAnd();
7955
7956 while (token == 'xor') {
7957 getTokenSkipNewline();
7958 node = new OperatorNode('xor', 'xor', [node, parseLogicalAnd()]);
7959 }
7960
7961 return node;
7962 }
7963
7964 /**
7965 * logical and, 'x and y'
7966 * @return {Node} node
7967 * @private
7968 */
7969 function parseLogicalAnd() {
7970 var node = parseBitwiseOr();
7971
7972 while (token == 'and') {
7973 getTokenSkipNewline();
7974 node = new OperatorNode('and', 'and', [node, parseBitwiseOr()]);
7975 }
7976
7977 return node;
7978 }
7979
7980 /**
7981 * bitwise or, 'x | y'
7982 * @return {Node} node
7983 * @private
7984 */
7985 function parseBitwiseOr() {
7986 var node = parseBitwiseXor();
7987
7988 while (token == '|') {
7989 getTokenSkipNewline();
7990 node = new OperatorNode('|', 'bitOr', [node, parseBitwiseXor()]);
7991 }
7992
7993 return node;
7994 }
7995
7996 /**
7997 * bitwise exclusive or (xor), 'x ^| y'
7998 * @return {Node} node
7999 * @private
8000 */
8001 function parseBitwiseXor() {
8002 var node = parseBitwiseAnd();
8003
8004 while (token == '^|') {
8005 getTokenSkipNewline();
8006 node = new OperatorNode('^|', 'bitXor', [node, parseBitwiseAnd()]);
8007 }
8008
8009 return node;
8010 }
8011
8012 /**
8013 * bitwise and, 'x & y'
8014 * @return {Node} node
8015 * @private
8016 */
8017 function parseBitwiseAnd () {
8018 var node = parseRelational();
8019
8020 while (token == '&') {
8021 getTokenSkipNewline();
8022 node = new OperatorNode('&', 'bitAnd', [node, parseRelational()]);
8023 }
8024
8025 return node;
8026 }
8027
8028 /**
8029 * relational operators
8030 * @return {Node} node
8031 * @private
8032 */
8033 function parseRelational () {
8034 var node, operators, name, fn, params;
8035
8036 node = parseShift();
8037
8038 operators = {
8039 '==': 'equal',
8040 '!=': 'unequal',
8041 '<': 'smaller',
8042 '>': 'larger',
8043 '<=': 'smallerEq',
8044 '>=': 'largerEq'
8045 };
8046 while (operators.hasOwnProperty(token)) {
8047 name = token;
8048 fn = operators[name];
8049
8050 getTokenSkipNewline();
8051 params = [node, parseShift()];
8052 node = new OperatorNode(name, fn, params);
8053 }
8054
8055 return node;
8056 }
8057
8058 /**
8059 * Bitwise left shift, bitwise right arithmetic shift, bitwise right logical shift
8060 * @return {Node} node
8061 * @private
8062 */
8063 function parseShift () {
8064 var node, operators, name, fn, params;
8065
8066 node = parseConversion();
8067
8068 operators = {
8069 '<<' : 'leftShift',
8070 '>>' : 'rightArithShift',
8071 '>>>' : 'rightLogShift'
8072 };
8073
8074 while (operators.hasOwnProperty(token)) {
8075 name = token;
8076 fn = operators[name];
8077
8078 getTokenSkipNewline();
8079 params = [node, parseConversion()];
8080 node = new OperatorNode(name, fn, params);
8081 }
8082
8083 return node;
8084 }
8085
8086 /**
8087 * conversion operators 'to' and 'in'
8088 * @return {Node} node
8089 * @private
8090 */
8091 function parseConversion () {
8092 var node, operators, name, fn, params;
8093
8094 node = parseRange();
8095
8096 operators = {
8097 'to' : 'to',
8098 'in' : 'to' // alias of 'to'
8099 };
8100
8101 while (operators.hasOwnProperty(token)) {
8102 name = token;
8103 fn = operators[name];
8104
8105 getTokenSkipNewline();
8106
8107 if (name === 'in' && token === '') {
8108 // end of expression -> this is the unit 'in' ('inch')
8109 node = new OperatorNode('*', 'multiply', [node, new SymbolNode('in')], true);
8110 }
8111 else {
8112 // operator 'a to b' or 'a in b'
8113 params = [node, parseRange()];
8114 node = new OperatorNode(name, fn, params);
8115 }
8116 }
8117
8118 return node;
8119 }
8120
8121 /**
8122 * parse range, "start:end", "start:step:end", ":", "start:", ":end", etc
8123 * @return {Node} node
8124 * @private
8125 */
8126 function parseRange () {
8127 var node, params = [];
8128
8129 if (token == ':') {
8130 // implicit start=1 (one-based)
8131 node = new ConstantNode('1', 'number');
8132 }
8133 else {
8134 // explicit start
8135 node = parseAddSubtract();
8136 }
8137
8138 if (token == ':' && (conditional_level !== nesting_level)) {
8139 // we ignore the range operator when a conditional operator is being processed on the same level
8140 params.push(node);
8141
8142 // parse step and end
8143 while (token == ':' && params.length < 3) {
8144 getTokenSkipNewline();
8145
8146 if (token == ')' || token == ']' || token == ',' || token == '') {
8147 // implicit end
8148 params.push(new SymbolNode('end'));
8149 }
8150 else {
8151 // explicit end
8152 params.push(parseAddSubtract());
8153 }
8154 }
8155
8156 if (params.length == 3) {
8157 // params = [start, step, end]
8158 node = new RangeNode(params[0], params[2], params[1]); // start, end, step
8159 }
8160 else { // length == 2
8161 // params = [start, end]
8162 node = new RangeNode(params[0], params[1]); // start, end
8163 }
8164 }
8165
8166 return node;
8167 }
8168
8169 /**
8170 * add or subtract
8171 * @return {Node} node
8172 * @private
8173 */
8174 function parseAddSubtract () {
8175 var node, operators, name, fn, params;
8176
8177 node = parseMultiplyDivide();
8178
8179 operators = {
8180 '+': 'add',
8181 '-': 'subtract'
8182 };
8183 while (operators.hasOwnProperty(token)) {
8184 name = token;
8185 fn = operators[name];
8186
8187 getTokenSkipNewline();
8188 params = [node, parseMultiplyDivide()];
8189 node = new OperatorNode(name, fn, params);
8190 }
8191
8192 return node;
8193 }
8194
8195 /**
8196 * multiply, divide, modulus
8197 * @return {Node} node
8198 * @private
8199 */
8200 function parseMultiplyDivide () {
8201 var node, last, operators, name, fn;
8202
8203 node = parseUnary();
8204 last = node;
8205
8206 operators = {
8207 '*': 'multiply',
8208 '.*': 'dotMultiply',
8209 '/': 'divide',
8210 './': 'dotDivide',
8211 '%': 'mod',
8212 'mod': 'mod'
8213 };
8214
8215 while (true) {
8216 if (operators.hasOwnProperty(token)) {
8217 // explicit operators
8218 name = token;
8219 fn = operators[name];
8220
8221 getTokenSkipNewline();
8222
8223 last = parseUnary();
8224 node = new OperatorNode(name, fn, [node, last]);
8225 }
8226 else if ((token_type === TOKENTYPE.SYMBOL) ||
8227 (token === 'in' && type.isConstantNode(node)) ||
8228 (token_type === TOKENTYPE.NUMBER &&
8229 !type.isConstantNode(last) &&
8230 (!type.isOperatorNode(last) || last.op === '!')) ||
8231 (token === '(')) {
8232 // parse implicit multiplication
8233 //
8234 // symbol: implicit multiplication like '2a', '(2+3)a', 'a b'
8235 // number: implicit multiplication like '(2+3)2'
8236 // parenthesis: implicit multiplication like '2(3+4)', '(3+4)(1+2)'
8237 last = parseUnary();
8238 node = new OperatorNode('*', 'multiply', [node, last], true /*implicit*/);
8239 }
8240 else {
8241 break;
8242 }
8243 }
8244
8245 return node;
8246 }
8247
8248 /**
8249 * Unary plus and minus, and logical and bitwise not
8250 * @return {Node} node
8251 * @private
8252 */
8253 function parseUnary () {
8254 var name, params, fn;
8255 var operators = {
8256 '-': 'unaryMinus',
8257 '+': 'unaryPlus',
8258 '~': 'bitNot',
8259 'not': 'not'
8260 };
8261
8262 if (operators.hasOwnProperty(token)) {
8263 fn = operators[token];
8264 name = token;
8265
8266 getTokenSkipNewline();
8267 params = [parseUnary()];
8268
8269 return new OperatorNode(name, fn, params);
8270 }
8271
8272 return parsePow();
8273 }
8274
8275 /**
8276 * power
8277 * Note: power operator is right associative
8278 * @return {Node} node
8279 * @private
8280 */
8281 function parsePow () {
8282 var node, name, fn, params;
8283
8284 node = parseLeftHandOperators();
8285
8286 if (token == '^' || token == '.^') {
8287 name = token;
8288 fn = (name == '^') ? 'pow' : 'dotPow';
8289
8290 getTokenSkipNewline();
8291 params = [node, parseUnary()]; // Go back to unary, we can have '2^-3'
8292 node = new OperatorNode(name, fn, params);
8293 }
8294
8295 return node;
8296 }
8297
8298 /**
8299 * Left hand operators: factorial x!, transpose x'
8300 * @return {Node} node
8301 * @private
8302 */
8303 function parseLeftHandOperators () {
8304 var node, operators, name, fn, params;
8305
8306 node = parseCustomNodes();
8307
8308 operators = {
8309 '!': 'factorial',
8310 '\'': 'transpose'
8311 };
8312
8313 while (operators.hasOwnProperty(token)) {
8314 name = token;
8315 fn = operators[name];
8316
8317 getToken();
8318 params = [node];
8319
8320 node = new OperatorNode(name, fn, params);
8321 node = parseAccessors(node);
8322 }
8323
8324 return node;
8325 }
8326
8327 /**
8328 * Parse a custom node handler. A node handler can be used to process
8329 * nodes in a custom way, for example for handling a plot.
8330 *
8331 * A handler must be passed as second argument of the parse function.
8332 * - must extend math.expression.node.Node
8333 * - must contain a function _compile(defs: Object) : string
8334 * - must contain a function find(filter: Object) : Node[]
8335 * - must contain a function toString() : string
8336 * - the constructor is called with a single argument containing all parameters
8337 *
8338 * For example:
8339 *
8340 * nodes = {
8341 * 'plot': PlotHandler
8342 * };
8343 *
8344 * The constructor of the handler is called as:
8345 *
8346 * node = new PlotHandler(params);
8347 *
8348 * The handler will be invoked when evaluating an expression like:
8349 *
8350 * node = math.parse('plot(sin(x), x)', nodes);
8351 *
8352 * @return {Node} node
8353 * @private
8354 */
8355 function parseCustomNodes () {
8356 var params = [];
8357
8358 if (token_type == TOKENTYPE.SYMBOL && extra_nodes.hasOwnProperty(token)) {
8359 var CustomNode = extra_nodes[token];
8360
8361 getToken();
8362
8363 // parse parameters
8364 if (token == '(') {
8365 params = [];
8366
8367 openParams();
8368 getToken();
8369
8370 if (token != ')') {
8371 params.push(parseAssignment());
8372
8373 // parse a list with parameters
8374 while (token == ',') {
8375 getToken();
8376 params.push(parseAssignment());
8377 }
8378 }
8379
8380 if (token != ')') {
8381 throw createSyntaxError('Parenthesis ) expected');
8382 }
8383 closeParams();
8384 getToken();
8385 }
8386
8387 // create a new custom node
8388 //noinspection JSValidateTypes
8389 return new CustomNode(params);
8390 }
8391
8392 return parseSymbol();
8393 }
8394
8395 /**
8396 * parse symbols: functions, variables, constants, units
8397 * @return {Node} node
8398 * @private
8399 */
8400 function parseSymbol () {
8401 var node, name;
8402
8403 if (token_type == TOKENTYPE.SYMBOL ||
8404 (token_type == TOKENTYPE.DELIMITER && token in NAMED_DELIMITERS)) {
8405 name = token;
8406
8407 getToken();
8408
8409 // parse function parameters and matrix index
8410 node = new SymbolNode(name);
8411 node = parseAccessors(node);
8412 return node;
8413 }
8414
8415 return parseString();
8416 }
8417
8418 /**
8419 * parse accessors:
8420 * - function invocation in round brackets (...), for example sqrt(2)
8421 * - index enclosed in square brackets [...], for example A[2,3]
8422 * - dot notation for properties, like foo.bar
8423 * @param {Node} node Node on which to apply the parameters. If there
8424 * are no parameters in the expression, the node
8425 * itself is returned
8426 * @param {string[]} [types] Filter the types of notations
8427 * can be ['(', '[', '.']
8428 * @return {Node} node
8429 * @private
8430 */
8431 function parseAccessors (node, types) {
8432 var params;
8433
8434 while ((token === '(' || token === '[' || token === '.') &&
8435 (!types || types.indexOf(token) !== -1)) {
8436 params = [];
8437
8438 if (token === '(') {
8439 if (type.isSymbolNode(node) || type.isAccessorNode(node) || type.isFunctionNode(node)) {
8440 // function invocation like fn(2, 3)
8441 openParams();
8442 getToken();
8443
8444 if (token !== ')') {
8445 params.push(parseAssignment());
8446
8447 // parse a list with parameters
8448 while (token === ',') {
8449 getToken();
8450 params.push(parseAssignment());
8451 }
8452 }
8453
8454 if (token !== ')') {
8455 throw createSyntaxError('Parenthesis ) expected');
8456 }
8457 closeParams();
8458 getToken();
8459
8460 node = new FunctionNode(node, params);
8461 }
8462 else {
8463 // implicit multiplication like (2+3)(4+5)
8464 // don't parse it here but let it be handled by parseMultiplyDivide
8465 // with correct precedence
8466 return node;
8467 }
8468 }
8469 else if (token === '[') {
8470 // index notation like variable[2, 3]
8471 openParams();
8472 getToken();
8473
8474 if (token !== ']') {
8475 params.push(parseAssignment());
8476
8477 // parse a list with parameters
8478 while (token === ',') {
8479 getToken();
8480 params.push(parseAssignment());
8481 }
8482 }
8483
8484 if (token !== ']') {
8485 throw createSyntaxError('Parenthesis ] expected');
8486 }
8487 closeParams();
8488 getToken();
8489
8490 node = new AccessorNode(node, new IndexNode(params));
8491 }
8492 else {
8493 // dot notation like variable.prop
8494 getToken();
8495
8496 if (token_type !== TOKENTYPE.SYMBOL) {
8497 throw createSyntaxError('Property name expected after dot');
8498 }
8499 params.push(new ConstantNode(token));
8500 getToken();
8501
8502 var dotNotation = true;
8503 node = new AccessorNode(node, new IndexNode(params, dotNotation));
8504 }
8505 }
8506
8507 return node;
8508 }
8509
8510 /**
8511 * parse a string.
8512 * A string is enclosed by double quotes
8513 * @return {Node} node
8514 * @private
8515 */
8516 function parseString () {
8517 var node, str;
8518
8519 if (token == '"') {
8520 str = parseStringToken();
8521
8522 // create constant
8523 node = new ConstantNode(str, 'string');
8524
8525 // parse index parameters
8526 node = parseAccessors(node);
8527
8528 return node;
8529 }
8530
8531 return parseMatrix();
8532 }
8533
8534 /**
8535 * Parse a string surrounded by double quotes "..."
8536 * @return {string}
8537 */
8538 function parseStringToken () {
8539 var str = '';
8540
8541 while (c != '' && c != '\"') {
8542 if (c == '\\') {
8543 // escape character
8544 str += c;
8545 next();
8546 }
8547
8548 str += c;
8549 next();
8550 }
8551
8552 getToken();
8553 if (token != '"') {
8554 throw createSyntaxError('End of string " expected');
8555 }
8556 getToken();
8557
8558 return str;
8559 }
8560
8561 /**
8562 * parse the matrix
8563 * @return {Node} node
8564 * @private
8565 */
8566 function parseMatrix () {
8567 var array, params, rows, cols;
8568
8569 if (token == '[') {
8570 // matrix [...]
8571 openParams();
8572 getToken();
8573
8574 if (token != ']') {
8575 // this is a non-empty matrix
8576 var row = parseRow();
8577
8578 if (token == ';') {
8579 // 2 dimensional array
8580 rows = 1;
8581 params = [row];
8582
8583 // the rows of the matrix are separated by dot-comma's
8584 while (token == ';') {
8585 getToken();
8586
8587 params[rows] = parseRow();
8588 rows++;
8589 }
8590
8591 if (token != ']') {
8592 throw createSyntaxError('End of matrix ] expected');
8593 }
8594 closeParams();
8595 getToken();
8596
8597 // check if the number of columns matches in all rows
8598 cols = params[0].items.length;
8599 for (var r = 1; r < rows; r++) {
8600 if (params[r].items.length != cols) {
8601 throw createError('Column dimensions mismatch ' +
8602 '(' + params[r].items.length + ' != ' + cols + ')');
8603 }
8604 }
8605
8606 array = new ArrayNode(params);
8607 }
8608 else {
8609 // 1 dimensional vector
8610 if (token != ']') {
8611 throw createSyntaxError('End of matrix ] expected');
8612 }
8613 closeParams();
8614 getToken();
8615
8616 array = row;
8617 }
8618 }
8619 else {
8620 // this is an empty matrix "[ ]"
8621 closeParams();
8622 getToken();
8623 array = new ArrayNode([]);
8624 }
8625
8626 return parseAccessors(array);
8627 }
8628
8629 return parseObject();
8630 }
8631
8632 /**
8633 * Parse a single comma-separated row from a matrix, like 'a, b, c'
8634 * @return {ArrayNode} node
8635 */
8636 function parseRow () {
8637 var params = [parseAssignment()];
8638 var len = 1;
8639
8640 while (token == ',') {
8641 getToken();
8642
8643 // parse expression
8644 params[len] = parseAssignment();
8645 len++;
8646 }
8647
8648 return new ArrayNode(params);
8649 }
8650
8651 /**
8652 * parse an object, enclosed in angle brackets{...}, for example {value: 2}
8653 * @return {Node} node
8654 * @private
8655 */
8656 function parseObject () {
8657 if (token == '{') {
8658 var key;
8659
8660 var properties = {};
8661 do {
8662 getToken();
8663
8664 if (token != '}') {
8665 // parse key
8666 if (token == '"') {
8667 key = parseStringToken();
8668 }
8669 else if (token_type == TOKENTYPE.SYMBOL) {
8670 key = token;
8671 getToken();
8672 }
8673 else {
8674 throw createSyntaxError('Symbol or string expected as object key');
8675 }
8676
8677 // parse key/value separator
8678 if (token != ':') {
8679 throw createSyntaxError('Colon : expected after object key');
8680 }
8681 getToken();
8682
8683 // parse key
8684 properties[key] = parseAssignment();
8685 }
8686 }
8687 while (token == ',');
8688
8689 if (token != '}') {
8690 throw createSyntaxError('Comma , or bracket } expected after object value');
8691 }
8692 getToken();
8693
8694 var node = new ObjectNode(properties);
8695
8696 // parse index parameters
8697 node = parseAccessors(node);
8698
8699 return node;
8700 }
8701
8702 return parseNumber();
8703 }
8704
8705 /**
8706 * parse a number
8707 * @return {Node} node
8708 * @private
8709 */
8710 function parseNumber () {
8711 var number;
8712
8713 if (token_type == TOKENTYPE.NUMBER) {
8714 // this is a number
8715 number = token;
8716 getToken();
8717
8718 return new ConstantNode(number, 'number');
8719 }
8720
8721 return parseParentheses();
8722 }
8723
8724 /**
8725 * parentheses
8726 * @return {Node} node
8727 * @private
8728 */
8729 function parseParentheses () {
8730 var node;
8731
8732 // check if it is a parenthesized expression
8733 if (token == '(') {
8734 // parentheses (...)
8735 openParams();
8736 getToken();
8737
8738 node = parseAssignment(); // start again
8739
8740 if (token != ')') {
8741 throw createSyntaxError('Parenthesis ) expected');
8742 }
8743 closeParams();
8744 getToken();
8745
8746 node = new ParenthesisNode(node);
8747 node = parseAccessors(node);
8748 return node;
8749 }
8750
8751 return parseEnd();
8752 }
8753
8754 /**
8755 * Evaluated when the expression is not yet ended but expected to end
8756 * @return {Node} res
8757 * @private
8758 */
8759 function parseEnd () {
8760 if (token == '') {
8761 // syntax error or unexpected end of expression
8762 throw createSyntaxError('Unexpected end of expression');
8763 } else if (token === "'") {
8764 throw createSyntaxError('Value expected. Note: strings must be enclosed by double quotes');
8765 } else {
8766 throw createSyntaxError('Value expected');
8767 }
8768 }
8769
8770 /**
8771 * Shortcut for getting the current row value (one based)
8772 * Returns the line of the currently handled expression
8773 * @private
8774 */
8775 /* TODO: implement keeping track on the row number
8776 function row () {
8777 return null;
8778 }
8779 */
8780
8781 /**
8782 * Shortcut for getting the current col value (one based)
8783 * Returns the column (position) where the last token starts
8784 * @private
8785 */
8786 function col () {
8787 return index - token.length + 1;
8788 }
8789
8790 /**
8791 * Create an error
8792 * @param {string} message
8793 * @return {SyntaxError} instantiated error
8794 * @private
8795 */
8796 function createSyntaxError (message) {
8797 var c = col();
8798 var error = new SyntaxError(message + ' (char ' + c + ')');
8799 error['char'] = c;
8800
8801 return error;
8802 }
8803
8804 /**
8805 * Create an error
8806 * @param {string} message
8807 * @return {Error} instantiated error
8808 * @private
8809 */
8810 function createError (message) {
8811 var c = col();
8812 var error = new SyntaxError(message + ' (char ' + c + ')');
8813 error['char'] = c;
8814
8815 return error;
8816 }
8817
8818 return parse;
8819}
8820
8821exports.name = 'parse';
8822exports.path = 'expression';
8823exports.factory = factory;
8824
8825
8826/***/ }),
8827/* 42 */
8828/***/ (function(module, exports, __webpack_require__) {
8829
8830var IndexError = __webpack_require__(53);
8831
8832/**
8833 * Transform zero-based indices to one-based indices in errors
8834 * @param {Error} err
8835 * @returns {Error} Returns the transformed error
8836 */
8837exports.transform = function (err) {
8838 if (err && err.isIndexError) {
8839 return new IndexError(
8840 err.index + 1,
8841 err.min + 1,
8842 err.max !== undefined ? err.max + 1 : undefined);
8843 }
8844
8845 return err;
8846};
8847
8848
8849/***/ }),
8850/* 43 */
8851/***/ (function(module, exports, __webpack_require__) {
8852
8853"use strict";
8854
8855
8856var isMatrix = __webpack_require__(59);
8857
8858/**
8859 * Recursively loop over all elements in a given multi dimensional array
8860 * and invoke the callback on each of the elements.
8861 * @param {Array | Matrix} array
8862 * @param {Function} callback The callback method is invoked with one
8863 * parameter: the current element in the array
8864 */
8865module.exports = function deepForEach (array, callback) {
8866 if (isMatrix(array)) {
8867 array = array.valueOf();
8868 }
8869
8870 for (var i = 0, ii = array.length; i < ii; i++) {
8871 var value = array[i];
8872
8873 if (Array.isArray(value)) {
8874 deepForEach(value, callback);
8875 }
8876 else {
8877 callback(value);
8878 }
8879 }
8880};
8881
8882
8883/***/ }),
8884/* 44 */
8885/***/ (function(module, exports, __webpack_require__) {
8886
8887"use strict";
8888
8889
8890/**
8891 * Create a syntax error with the message:
8892 * 'Wrong number of arguments in function <fn> (<count> provided, <min>-<max> expected)'
8893 * @param {string} fn Function name
8894 * @param {number} count Actual argument count
8895 * @param {number} min Minimum required argument count
8896 * @param {number} [max] Maximum required argument count
8897 * @extends Error
8898 */
8899function ArgumentsError(fn, count, min, max) {
8900 if (!(this instanceof ArgumentsError)) {
8901 throw new SyntaxError('Constructor must be called with the new operator');
8902 }
8903
8904 this.fn = fn;
8905 this.count = count;
8906 this.min = min;
8907 this.max = max;
8908
8909 this.message = 'Wrong number of arguments in function ' + fn +
8910 ' (' + count + ' provided, ' +
8911 min + ((max != undefined) ? ('-' + max) : '') + ' expected)';
8912
8913 this.stack = (new Error()).stack;
8914}
8915
8916ArgumentsError.prototype = new Error();
8917ArgumentsError.prototype.constructor = Error;
8918ArgumentsError.prototype.name = 'ArgumentsError';
8919ArgumentsError.prototype.isArgumentsError = true;
8920
8921module.exports = ArgumentsError;
8922
8923
8924/***/ }),
8925/* 45 */
8926/***/ (function(module, exports, __webpack_require__) {
8927
8928"use strict";
8929
8930
8931var util = __webpack_require__(25);
8932var DimensionError = __webpack_require__(11);
8933var getSafeProperty = __webpack_require__(13).getSafeProperty;
8934var setSafeProperty = __webpack_require__(13).setSafeProperty;
8935
8936var string = util.string;
8937var array = util.array;
8938var object = util.object;
8939var number = util.number;
8940
8941var isArray = Array.isArray;
8942var isNumber = number.isNumber;
8943var isInteger = number.isInteger;
8944var isString = string.isString;
8945
8946var validateIndex = array.validateIndex;
8947
8948function factory (type, config, load, typed) {
8949 var Matrix = load(__webpack_require__(72)); // force loading Matrix (do not use via type.Matrix)
8950
8951 /**
8952 * Dense Matrix implementation. A regular, dense matrix, supporting multi-dimensional matrices. This is the default matrix type.
8953 * @class DenseMatrix
8954 */
8955 function DenseMatrix(data, datatype) {
8956 if (!(this instanceof DenseMatrix))
8957 throw new SyntaxError('Constructor must be called with the new operator');
8958 if (datatype && !isString(datatype))
8959 throw new Error('Invalid datatype: ' + datatype);
8960
8961 if (type.isMatrix(data)) {
8962 // check data is a DenseMatrix
8963 if (data.type === 'DenseMatrix') {
8964 // clone data & size
8965 this._data = object.clone(data._data);
8966 this._size = object.clone(data._size);
8967 this._datatype = datatype || data._datatype;
8968 }
8969 else {
8970 // build data from existing matrix
8971 this._data = data.toArray();
8972 this._size = data.size();
8973 this._datatype = datatype || data._datatype;
8974 }
8975 }
8976 else if (data && isArray(data.data) && isArray(data.size)) {
8977 // initialize fields from JSON representation
8978 this._data = data.data;
8979 this._size = data.size;
8980 this._datatype = datatype || data.datatype;
8981 }
8982 else if (isArray(data)) {
8983 // replace nested Matrices with Arrays
8984 this._data = preprocess(data);
8985 // get the dimensions of the array
8986 this._size = array.size(this._data);
8987 // verify the dimensions of the array, TODO: compute size while processing array
8988 array.validate(this._data, this._size);
8989 // data type unknown
8990 this._datatype = datatype;
8991 }
8992 else if (data) {
8993 // unsupported type
8994 throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')');
8995 }
8996 else {
8997 // nothing provided
8998 this._data = [];
8999 this._size = [0];
9000 this._datatype = datatype;
9001 }
9002 }
9003
9004 DenseMatrix.prototype = new Matrix();
9005
9006 /**
9007 * Attach type information
9008 */
9009 DenseMatrix.prototype.type = 'DenseMatrix';
9010 DenseMatrix.prototype.isDenseMatrix = true;
9011
9012 /**
9013 * Get the storage format used by the matrix.
9014 *
9015 * Usage:
9016 * var format = matrix.storage() // retrieve storage format
9017 *
9018 * @memberof DenseMatrix
9019 * @return {string} The storage format.
9020 */
9021 DenseMatrix.prototype.storage = function () {
9022 return 'dense';
9023 };
9024
9025 /**
9026 * Get the datatype of the data stored in the matrix.
9027 *
9028 * Usage:
9029 * var format = matrix.datatype() // retrieve matrix datatype
9030 *
9031 * @memberof DenseMatrix
9032 * @return {string} The datatype.
9033 */
9034 DenseMatrix.prototype.datatype = function () {
9035 return this._datatype;
9036 };
9037
9038 /**
9039 * Create a new DenseMatrix
9040 * @memberof DenseMatrix
9041 * @param {Array} data
9042 * @param {string} [datatype]
9043 */
9044 DenseMatrix.prototype.create = function (data, datatype) {
9045 return new DenseMatrix(data, datatype);
9046 };
9047
9048 /**
9049 * Get a subset of the matrix, or replace a subset of the matrix.
9050 *
9051 * Usage:
9052 * var subset = matrix.subset(index) // retrieve subset
9053 * var value = matrix.subset(index, replacement) // replace subset
9054 *
9055 * @memberof DenseMatrix
9056 * @param {Index} index
9057 * @param {Array | DenseMatrix | *} [replacement]
9058 * @param {*} [defaultValue=0] Default value, filled in on new entries when
9059 * the matrix is resized. If not provided,
9060 * new matrix elements will be filled with zeros.
9061 */
9062 DenseMatrix.prototype.subset = function (index, replacement, defaultValue) {
9063 switch (arguments.length) {
9064 case 1:
9065 return _get(this, index);
9066
9067 // intentional fall through
9068 case 2:
9069 case 3:
9070 return _set(this, index, replacement, defaultValue);
9071
9072 default:
9073 throw new SyntaxError('Wrong number of arguments');
9074 }
9075 };
9076
9077 /**
9078 * Get a single element from the matrix.
9079 * @memberof DenseMatrix
9080 * @param {number[]} index Zero-based index
9081 * @return {*} value
9082 */
9083 DenseMatrix.prototype.get = function (index) {
9084 if (!isArray(index))
9085 throw new TypeError('Array expected');
9086 if (index.length != this._size.length)
9087 throw new DimensionError(index.length, this._size.length);
9088
9089 // check index
9090 for (var x = 0; x < index.length; x++)
9091 validateIndex(index[x], this._size[x]);
9092
9093 var data = this._data;
9094 for (var i = 0, ii = index.length; i < ii; i++) {
9095 var index_i = index[i];
9096 validateIndex(index_i, data.length);
9097 data = data[index_i];
9098 }
9099
9100 return data;
9101 };
9102
9103 /**
9104 * Replace a single element in the matrix.
9105 * @memberof DenseMatrix
9106 * @param {number[]} index Zero-based index
9107 * @param {*} value
9108 * @param {*} [defaultValue] Default value, filled in on new entries when
9109 * the matrix is resized. If not provided,
9110 * new matrix elements will be left undefined.
9111 * @return {DenseMatrix} self
9112 */
9113 DenseMatrix.prototype.set = function (index, value, defaultValue) {
9114 if (!isArray(index))
9115 throw new TypeError('Array expected');
9116 if (index.length < this._size.length)
9117 throw new DimensionError(index.length, this._size.length, '<');
9118
9119 var i, ii, index_i;
9120
9121 // enlarge matrix when needed
9122 var size = index.map(function (i) {
9123 return i + 1;
9124 });
9125 _fit(this, size, defaultValue);
9126
9127 // traverse over the dimensions
9128 var data = this._data;
9129 for (i = 0, ii = index.length - 1; i < ii; i++) {
9130 index_i = index[i];
9131 validateIndex(index_i, data.length);
9132 data = data[index_i];
9133 }
9134
9135 // set new value
9136 index_i = index[index.length - 1];
9137 validateIndex(index_i, data.length);
9138 data[index_i] = value;
9139
9140 return this;
9141 };
9142
9143 /**
9144 * Get a submatrix of this matrix
9145 * @memberof DenseMatrix
9146 * @param {DenseMatrix} matrix
9147 * @param {Index} index Zero-based index
9148 * @private
9149 */
9150 function _get (matrix, index) {
9151 if (!type.isIndex(index)) {
9152 throw new TypeError('Invalid index');
9153 }
9154
9155 var isScalar = index.isScalar();
9156 if (isScalar) {
9157 // return a scalar
9158 return matrix.get(index.min());
9159 }
9160 else {
9161 // validate dimensions
9162 var size = index.size();
9163 if (size.length != matrix._size.length) {
9164 throw new DimensionError(size.length, matrix._size.length);
9165 }
9166
9167 // validate if any of the ranges in the index is out of range
9168 var min = index.min();
9169 var max = index.max();
9170 for (var i = 0, ii = matrix._size.length; i < ii; i++) {
9171 validateIndex(min[i], matrix._size[i]);
9172 validateIndex(max[i], matrix._size[i]);
9173 }
9174
9175 // retrieve submatrix
9176 // TODO: more efficient when creating an empty matrix and setting _data and _size manually
9177 return new DenseMatrix(_getSubmatrix(matrix._data, index, size.length, 0), matrix._datatype);
9178 }
9179 }
9180
9181 /**
9182 * Recursively get a submatrix of a multi dimensional matrix.
9183 * Index is not checked for correct number or length of dimensions.
9184 * @memberof DenseMatrix
9185 * @param {Array} data
9186 * @param {Index} index
9187 * @param {number} dims Total number of dimensions
9188 * @param {number} dim Current dimension
9189 * @return {Array} submatrix
9190 * @private
9191 */
9192 function _getSubmatrix (data, index, dims, dim) {
9193 var last = (dim === dims - 1);
9194 var range = index.dimension(dim);
9195
9196 if (last) {
9197 return range.map(function (i) {
9198 validateIndex(i, data.length);
9199 return data[i];
9200 }).valueOf();
9201 }
9202 else {
9203 return range.map(function (i) {
9204 validateIndex(i, data.length);
9205 var child = data[i];
9206 return _getSubmatrix(child, index, dims, dim + 1);
9207 }).valueOf();
9208 }
9209 }
9210
9211 /**
9212 * Replace a submatrix in this matrix
9213 * Indexes are zero-based.
9214 * @memberof DenseMatrix
9215 * @param {DenseMatrix} matrix
9216 * @param {Index} index
9217 * @param {DenseMatrix | Array | *} submatrix
9218 * @param {*} defaultValue Default value, filled in on new entries when
9219 * the matrix is resized.
9220 * @return {DenseMatrix} matrix
9221 * @private
9222 */
9223 function _set (matrix, index, submatrix, defaultValue) {
9224 if (!index || index.isIndex !== true) {
9225 throw new TypeError('Invalid index');
9226 }
9227
9228 // get index size and check whether the index contains a single value
9229 var iSize = index.size(),
9230 isScalar = index.isScalar();
9231
9232 // calculate the size of the submatrix, and convert it into an Array if needed
9233 var sSize;
9234 if (type.isMatrix(submatrix)) {
9235 sSize = submatrix.size();
9236 submatrix = submatrix.valueOf();
9237 }
9238 else {
9239 sSize = array.size(submatrix);
9240 }
9241
9242 if (isScalar) {
9243 // set a scalar
9244
9245 // check whether submatrix is a scalar
9246 if (sSize.length !== 0) {
9247 throw new TypeError('Scalar expected');
9248 }
9249
9250 matrix.set(index.min(), submatrix, defaultValue);
9251 }
9252 else {
9253 // set a submatrix
9254
9255 // validate dimensions
9256 if (iSize.length < matrix._size.length) {
9257 throw new DimensionError(iSize.length, matrix._size.length, '<');
9258 }
9259
9260 if (sSize.length < iSize.length) {
9261 // calculate number of missing outer dimensions
9262 var i = 0;
9263 var outer = 0;
9264 while (iSize[i] === 1 && sSize[i] === 1) {
9265 i++;
9266 }
9267 while (iSize[i] === 1) {
9268 outer++;
9269 i++;
9270 }
9271
9272 // unsqueeze both outer and inner dimensions
9273 submatrix = array.unsqueeze(submatrix, iSize.length, outer, sSize);
9274 }
9275
9276 // check whether the size of the submatrix matches the index size
9277 if (!object.deepEqual(iSize, sSize)) {
9278 throw new DimensionError(iSize, sSize, '>');
9279 }
9280
9281 // enlarge matrix when needed
9282 var size = index.max().map(function (i) {
9283 return i + 1;
9284 });
9285 _fit(matrix, size, defaultValue);
9286
9287 // insert the sub matrix
9288 var dims = iSize.length,
9289 dim = 0;
9290 _setSubmatrix (matrix._data, index, submatrix, dims, dim);
9291 }
9292
9293 return matrix;
9294 }
9295
9296 /**
9297 * Replace a submatrix of a multi dimensional matrix.
9298 * @memberof DenseMatrix
9299 * @param {Array} data
9300 * @param {Index} index
9301 * @param {Array} submatrix
9302 * @param {number} dims Total number of dimensions
9303 * @param {number} dim
9304 * @private
9305 */
9306 function _setSubmatrix (data, index, submatrix, dims, dim) {
9307 var last = (dim === dims - 1),
9308 range = index.dimension(dim);
9309
9310 if (last) {
9311 range.forEach(function (dataIndex, subIndex) {
9312 validateIndex(dataIndex);
9313 data[dataIndex] = submatrix[subIndex[0]];
9314 });
9315 }
9316 else {
9317 range.forEach(function (dataIndex, subIndex) {
9318 validateIndex(dataIndex);
9319 _setSubmatrix(data[dataIndex], index, submatrix[subIndex[0]], dims, dim + 1);
9320 });
9321 }
9322 }
9323
9324 /**
9325 * Resize the matrix to the given size. Returns a copy of the matrix when
9326 * `copy=true`, otherwise return the matrix itself (resize in place).
9327 *
9328 * @memberof DenseMatrix
9329 * @param {number[]} size The new size the matrix should have.
9330 * @param {*} [defaultValue=0] Default value, filled in on new entries.
9331 * If not provided, the matrix elements will
9332 * be filled with zeros.
9333 * @param {boolean} [copy] Return a resized copy of the matrix
9334 *
9335 * @return {Matrix} The resized matrix
9336 */
9337 DenseMatrix.prototype.resize = function (size, defaultValue, copy) {
9338 // validate arguments
9339 if (!isArray(size))
9340 throw new TypeError('Array expected');
9341
9342 // matrix to resize
9343 var m = copy ? this.clone() : this;
9344 // resize matrix
9345 return _resize(m, size, defaultValue);
9346 };
9347
9348 var _resize = function (matrix, size, defaultValue) {
9349 // check size
9350 if (size.length === 0) {
9351 // first value in matrix
9352 var v = matrix._data;
9353 // go deep
9354 while (isArray(v)) {
9355 v = v[0];
9356 }
9357 return v;
9358 }
9359 // resize matrix
9360 matrix._size = size.slice(0); // copy the array
9361 matrix._data = array.resize(matrix._data, matrix._size, defaultValue);
9362 // return matrix
9363 return matrix;
9364 };
9365
9366 /**
9367 * Reshape the matrix to the given size. Returns a copy of the matrix when
9368 * `copy=true`, otherwise return the matrix itself (reshape in place).
9369 *
9370 * NOTE: This might be better suited to copy by default, instead of modifying
9371 * in place. For now, it operates in place to remain consistent with
9372 * resize().
9373 *
9374 * @memberof DenseMatrix
9375 * @param {number[]} size The new size the matrix should have.
9376 * @param {boolean} [copy] Return a reshaped copy of the matrix
9377 *
9378 * @return {Matrix} The reshaped matrix
9379 */
9380 DenseMatrix.prototype.reshape = function (size, copy) {
9381 var m = copy ? this.clone() : this;
9382
9383 m._data = array.reshape(m._data, size);
9384 m._size = size.slice(0);
9385 return m;
9386 };
9387
9388 /**
9389 * Enlarge the matrix when it is smaller than given size.
9390 * If the matrix is larger or equal sized, nothing is done.
9391 * @memberof DenseMatrix
9392 * @param {DenseMatrix} matrix The matrix to be resized
9393 * @param {number[]} size
9394 * @param {*} defaultValue Default value, filled in on new entries.
9395 * @private
9396 */
9397 function _fit(matrix, size, defaultValue) {
9398 var newSize = matrix._size.slice(0), // copy the array
9399 changed = false;
9400
9401 // add dimensions when needed
9402 while (newSize.length < size.length) {
9403 newSize.push(0);
9404 changed = true;
9405 }
9406
9407 // enlarge size when needed
9408 for (var i = 0, ii = size.length; i < ii; i++) {
9409 if (size[i] > newSize[i]) {
9410 newSize[i] = size[i];
9411 changed = true;
9412 }
9413 }
9414
9415 if (changed) {
9416 // resize only when size is changed
9417 _resize(matrix, newSize, defaultValue);
9418 }
9419 }
9420
9421 /**
9422 * Create a clone of the matrix
9423 * @memberof DenseMatrix
9424 * @return {DenseMatrix} clone
9425 */
9426 DenseMatrix.prototype.clone = function () {
9427 var m = new DenseMatrix({
9428 data: object.clone(this._data),
9429 size: object.clone(this._size),
9430 datatype: this._datatype
9431 });
9432 return m;
9433 };
9434
9435 /**
9436 * Retrieve the size of the matrix.
9437 * @memberof DenseMatrix
9438 * @returns {number[]} size
9439 */
9440 DenseMatrix.prototype.size = function() {
9441 return this._size.slice(0); // return a clone of _size
9442 };
9443
9444 /**
9445 * Create a new matrix with the results of the callback function executed on
9446 * each entry of the matrix.
9447 * @memberof DenseMatrix
9448 * @param {Function} callback The callback function is invoked with three
9449 * parameters: the value of the element, the index
9450 * of the element, and the Matrix being traversed.
9451 *
9452 * @return {DenseMatrix} matrix
9453 */
9454 DenseMatrix.prototype.map = function (callback) {
9455 // matrix instance
9456 var me = this;
9457 var recurse = function (value, index) {
9458 if (isArray(value)) {
9459 return value.map(function (child, i) {
9460 return recurse(child, index.concat(i));
9461 });
9462 }
9463 else {
9464 return callback(value, index, me);
9465 }
9466 };
9467 // return dense format
9468 return new DenseMatrix({
9469 data: recurse(this._data, []),
9470 size: object.clone(this._size),
9471 datatype: this._datatype
9472 });
9473 };
9474
9475 /**
9476 * Execute a callback function on each entry of the matrix.
9477 * @memberof DenseMatrix
9478 * @param {Function} callback The callback function is invoked with three
9479 * parameters: the value of the element, the index
9480 * of the element, and the Matrix being traversed.
9481 */
9482 DenseMatrix.prototype.forEach = function (callback) {
9483 // matrix instance
9484 var me = this;
9485 var recurse = function (value, index) {
9486 if (isArray(value)) {
9487 value.forEach(function (child, i) {
9488 recurse(child, index.concat(i));
9489 });
9490 }
9491 else {
9492 callback(value, index, me);
9493 }
9494 };
9495 recurse(this._data, []);
9496 };
9497
9498 /**
9499 * Create an Array with a copy of the data of the DenseMatrix
9500 * @memberof DenseMatrix
9501 * @returns {Array} array
9502 */
9503 DenseMatrix.prototype.toArray = function () {
9504 return object.clone(this._data);
9505 };
9506
9507 /**
9508 * Get the primitive value of the DenseMatrix: a multidimensional array
9509 * @memberof DenseMatrix
9510 * @returns {Array} array
9511 */
9512 DenseMatrix.prototype.valueOf = function () {
9513 return this._data;
9514 };
9515
9516 /**
9517 * Get a string representation of the matrix, with optional formatting options.
9518 * @memberof DenseMatrix
9519 * @param {Object | number | Function} [options] Formatting options. See
9520 * lib/utils/number:format for a
9521 * description of the available
9522 * options.
9523 * @returns {string} str
9524 */
9525 DenseMatrix.prototype.format = function (options) {
9526 return string.format(this._data, options);
9527 };
9528
9529 /**
9530 * Get a string representation of the matrix
9531 * @memberof DenseMatrix
9532 * @returns {string} str
9533 */
9534 DenseMatrix.prototype.toString = function () {
9535 return string.format(this._data);
9536 };
9537
9538 /**
9539 * Get a JSON representation of the matrix
9540 * @memberof DenseMatrix
9541 * @returns {Object}
9542 */
9543 DenseMatrix.prototype.toJSON = function () {
9544 return {
9545 mathjs: 'DenseMatrix',
9546 data: this._data,
9547 size: this._size,
9548 datatype: this._datatype
9549 };
9550 };
9551
9552 /**
9553 * Get the kth Matrix diagonal.
9554 *
9555 * @memberof DenseMatrix
9556 * @param {number | BigNumber} [k=0] The kth diagonal where the vector will retrieved.
9557 *
9558 * @returns {Array} The array vector with the diagonal values.
9559 */
9560 DenseMatrix.prototype.diagonal = function(k) {
9561 // validate k if any
9562 if (k) {
9563 // convert BigNumber to a number
9564 if (type.isBigNumber(k))
9565 k = k.toNumber();
9566 // is must be an integer
9567 if (!isNumber(k) || !isInteger(k)) {
9568 throw new TypeError ('The parameter k must be an integer number');
9569 }
9570 }
9571 else {
9572 // default value
9573 k = 0;
9574 }
9575
9576 var kSuper = k > 0 ? k : 0;
9577 var kSub = k < 0 ? -k : 0;
9578
9579 // rows & columns
9580 var rows = this._size[0];
9581 var columns = this._size[1];
9582
9583 // number diagonal values
9584 var n = Math.min(rows - kSub, columns - kSuper);
9585
9586 // x is a matrix get diagonal from matrix
9587 var data = [];
9588
9589 // loop rows
9590 for (var i = 0; i < n; i++) {
9591 data[i] = this._data[i + kSub][i + kSuper];
9592 }
9593
9594 // create DenseMatrix
9595 return new DenseMatrix({
9596 data: data,
9597 size: [n],
9598 datatype: this._datatype
9599 });
9600 };
9601
9602 /**
9603 * Create a diagonal matrix.
9604 *
9605 * @memberof DenseMatrix
9606 * @param {Array} size The matrix size.
9607 * @param {number | Array} value The values for the diagonal.
9608 * @param {number | BigNumber} [k=0] The kth diagonal where the vector will be filled in.
9609 * @param {number} [defaultValue] The default value for non-diagonal
9610 *
9611 * @returns {DenseMatrix}
9612 */
9613 DenseMatrix.diagonal = function (size, value, k, defaultValue, datatype) {
9614 if (!isArray(size))
9615 throw new TypeError('Array expected, size parameter');
9616 if (size.length !== 2)
9617 throw new Error('Only two dimensions matrix are supported');
9618
9619 // map size & validate
9620 size = size.map(function (s) {
9621 // check it is a big number
9622 if (type.isBigNumber(s)) {
9623 // convert it
9624 s = s.toNumber();
9625 }
9626 // validate arguments
9627 if (!isNumber(s) || !isInteger(s) || s < 1) {
9628 throw new Error('Size values must be positive integers');
9629 }
9630 return s;
9631 });
9632
9633 // validate k if any
9634 if (k) {
9635 // convert BigNumber to a number
9636 if (type.isBigNumber(k))
9637 k = k.toNumber();
9638 // is must be an integer
9639 if (!isNumber(k) || !isInteger(k)) {
9640 throw new TypeError ('The parameter k must be an integer number');
9641 }
9642 }
9643 else {
9644 // default value
9645 k = 0;
9646 }
9647
9648 if (defaultValue && isString(datatype)) {
9649 // convert defaultValue to the same datatype
9650 defaultValue = typed.convert(defaultValue, datatype);
9651 }
9652
9653 var kSuper = k > 0 ? k : 0;
9654 var kSub = k < 0 ? -k : 0;
9655
9656 // rows and columns
9657 var rows = size[0];
9658 var columns = size[1];
9659
9660 // number of non-zero items
9661 var n = Math.min(rows - kSub, columns - kSuper);
9662
9663 // value extraction function
9664 var _value;
9665
9666 // check value
9667 if (isArray(value)) {
9668 // validate array
9669 if (value.length !== n) {
9670 // number of values in array must be n
9671 throw new Error('Invalid value array length');
9672 }
9673 // define function
9674 _value = function (i) {
9675 // return value @ i
9676 return value[i];
9677 };
9678 }
9679 else if (type.isMatrix(value)) {
9680 // matrix size
9681 var ms = value.size();
9682 // validate matrix
9683 if (ms.length !== 1 || ms[0] !== n) {
9684 // number of values in array must be n
9685 throw new Error('Invalid matrix length');
9686 }
9687 // define function
9688 _value = function (i) {
9689 // return value @ i
9690 return value.get([i]);
9691 };
9692 }
9693 else {
9694 // define function
9695 _value = function () {
9696 // return value
9697 return value;
9698 };
9699 }
9700
9701 // discover default value if needed
9702 if (!defaultValue) {
9703 // check first value in array
9704 defaultValue = type.isBigNumber(_value(0)) ? new type.BigNumber(0) : 0;
9705 }
9706
9707 // empty array
9708 var data = [];
9709
9710 // check we need to resize array
9711 if (size.length > 0) {
9712 // resize array
9713 data = array.resize(data, size, defaultValue);
9714 // fill diagonal
9715 for (var d = 0; d < n; d++) {
9716 data[d + kSub][d + kSuper] = _value(d);
9717 }
9718 }
9719
9720 // create DenseMatrix
9721 return new DenseMatrix({
9722 data: data,
9723 size: [rows, columns]
9724 });
9725 };
9726
9727 /**
9728 * Generate a matrix from a JSON object
9729 * @memberof DenseMatrix
9730 * @param {Object} json An object structured like
9731 * `{"mathjs": "DenseMatrix", data: [], size: []}`,
9732 * where mathjs is optional
9733 * @returns {DenseMatrix}
9734 */
9735 DenseMatrix.fromJSON = function (json) {
9736 return new DenseMatrix(json);
9737 };
9738
9739 /**
9740 * Swap rows i and j in Matrix.
9741 *
9742 * @memberof DenseMatrix
9743 * @param {number} i Matrix row index 1
9744 * @param {number} j Matrix row index 2
9745 *
9746 * @return {Matrix} The matrix reference
9747 */
9748 DenseMatrix.prototype.swapRows = function (i, j) {
9749 // check index
9750 if (!isNumber(i) || !isInteger(i) || !isNumber(j) || !isInteger(j)) {
9751 throw new Error('Row index must be positive integers');
9752 }
9753 // check dimensions
9754 if (this._size.length !== 2) {
9755 throw new Error('Only two dimensional matrix is supported');
9756 }
9757 // validate index
9758 validateIndex(i, this._size[0]);
9759 validateIndex(j, this._size[0]);
9760
9761 // swap rows
9762 DenseMatrix._swapRows(i, j, this._data);
9763 // return current instance
9764 return this;
9765 };
9766
9767 /**
9768 * Swap rows i and j in Dense Matrix data structure.
9769 *
9770 * @param {number} i Matrix row index 1
9771 * @param {number} j Matrix row index 2
9772 */
9773 DenseMatrix._swapRows = function (i, j, data) {
9774 // swap values i <-> j
9775 var vi = data[i];
9776 data[i] = data[j];
9777 data[j] = vi;
9778 };
9779
9780 /**
9781 * Preprocess data, which can be an Array or DenseMatrix with nested Arrays and
9782 * Matrices. Replaces all nested Matrices with Arrays
9783 * @memberof DenseMatrix
9784 * @param {Array} data
9785 * @return {Array} data
9786 */
9787 function preprocess(data) {
9788 for (var i = 0, ii = data.length; i < ii; i++) {
9789 var elem = data[i];
9790 if (isArray(elem)) {
9791 data[i] = preprocess(elem);
9792 }
9793 else if (elem && elem.isMatrix === true) {
9794 data[i] = preprocess(elem.valueOf());
9795 }
9796 }
9797
9798 return data;
9799 }
9800
9801 // register this type in the base class Matrix
9802 type.Matrix._storage.dense = DenseMatrix;
9803 type.Matrix._storage['default'] = DenseMatrix;
9804
9805 // exports
9806 return DenseMatrix;
9807}
9808
9809exports.name = 'DenseMatrix';
9810exports.path = 'type';
9811exports.factory = factory;
9812exports.lazy = false; // no lazy loading, as we alter type.Matrix._storage
9813
9814
9815/***/ }),
9816/* 46 */
9817/***/ (function(module, exports, __webpack_require__) {
9818
9819"use strict";
9820
9821
9822var isInteger = __webpack_require__(3).isInteger;
9823var size = __webpack_require__(2).size;
9824
9825function factory (type, config, load, typed) {
9826 var latex = __webpack_require__(4);
9827 var eye = load(__webpack_require__(62));
9828 var multiply = load(__webpack_require__(12));
9829 var matrix = load(__webpack_require__(0));
9830 var fraction = load(__webpack_require__(93));
9831 var number = load(__webpack_require__(74));
9832
9833 /**
9834 * Calculates the power of x to y, `x ^ y`.
9835 * Matrix exponentiation is supported for square matrices `x`, and positive
9836 * integer exponents `y`.
9837 *
9838 * For cubic roots of negative numbers, the function returns the principal
9839 * root by default. In order to let the function return the real root,
9840 * math.js can be configured with `math.config({predictable: true})`.
9841 * To retrieve all cubic roots of a value, use `math.cbrt(x, true)`.
9842 *
9843 * Syntax:
9844 *
9845 * math.pow(x, y)
9846 *
9847 * Examples:
9848 *
9849 * math.pow(2, 3); // returns number 8
9850 *
9851 * var a = math.complex(2, 3);
9852 * math.pow(a, 2) // returns Complex -5 + 12i
9853 *
9854 * var b = [[1, 2], [4, 3]];
9855 * math.pow(b, 2); // returns Array [[9, 8], [16, 17]]
9856 *
9857 * See also:
9858 *
9859 * multiply, sqrt, cbrt, nthRoot
9860 *
9861 * @param {number | BigNumber | Complex | Array | Matrix} x The base
9862 * @param {number | BigNumber | Complex} y The exponent
9863 * @return {number | BigNumber | Complex | Array | Matrix} The value of `x` to the power `y`
9864 */
9865 var pow = typed('pow', {
9866 'number, number': _pow,
9867
9868 'Complex, Complex': function (x, y) {
9869 return x.pow(y);
9870 },
9871
9872 'BigNumber, BigNumber': function (x, y) {
9873 if (y.isInteger() || x >= 0 || config.predictable) {
9874 return x.pow(y);
9875 }
9876 else {
9877 return new type.Complex(x.toNumber(), 0).pow(y.toNumber(), 0);
9878 }
9879 },
9880
9881 'Fraction, Fraction': function (x, y) {
9882 if (y.d !== 1) {
9883 if (config.predictable) {
9884 throw new Error('Function pow does not support non-integer exponents for fractions.');
9885 }
9886 else {
9887 return _pow(x.valueOf(), y.valueOf());
9888 }
9889 }
9890 else {
9891 return x.pow(y);
9892 }
9893 },
9894
9895 'Array, number': _powArray,
9896
9897 'Array, BigNumber': function (x, y) {
9898 return _powArray(x, y.toNumber());
9899 },
9900
9901 'Matrix, number': _powMatrix,
9902
9903 'Matrix, BigNumber': function (x, y) {
9904 return _powMatrix(x, y.toNumber());
9905 },
9906
9907 'Unit, number': function (x, y) {
9908 return x.pow(y);
9909 }
9910
9911 });
9912
9913 /**
9914 * Calculates the power of x to y, x^y, for two numbers.
9915 * @param {number} x
9916 * @param {number} y
9917 * @return {number | Complex} res
9918 * @private
9919 */
9920 function _pow(x, y) {
9921
9922 // Alternatively could define a 'realmode' config option or something, but
9923 // 'predictable' will work for now
9924 if (config.predictable && !isInteger(y) && x < 0) {
9925 // Check to see if y can be represented as a fraction
9926 try {
9927 var yFrac = fraction(y);
9928 var yNum = number(yFrac);
9929 if(y === yNum || Math.abs((y - yNum) / y) < 1e-14) {
9930 if(yFrac.d % 2 === 1) {
9931 return (yFrac.n % 2 === 0 ? 1 : -1) * Math.pow(-x, y);
9932 }
9933 }
9934 }
9935 catch (ex) {
9936 // fraction() throws an error if y is Infinity, etc.
9937 }
9938
9939 // Unable to express y as a fraction, so continue on
9940 }
9941
9942
9943 // x^Infinity === 0 if -1 < x < 1
9944 // A real number 0 is returned instead of complex(0)
9945 if ((x*x < 1 && y === Infinity) ||
9946 (x*x > 1 && y === -Infinity)) {
9947 return 0;
9948 }
9949
9950 // **for predictable mode** x^Infinity === NaN if x < -1
9951 // N.B. this behavour is different from `Math.pow` which gives
9952 // (-2)^Infinity === Infinity
9953 if (config.predictable &&
9954 ((x < -1 && y === Infinity) ||
9955 (x > -1 && x < 0 && y === -Infinity))) {
9956 return NaN;
9957 }
9958
9959 if (isInteger(y) || x >= 0 || config.predictable) {
9960 return Math.pow(x, y);
9961 }
9962 else {
9963 return new type.Complex(x, 0).pow(y, 0);
9964 }
9965 }
9966
9967 /**
9968 * Calculate the power of a 2d array
9969 * @param {Array} x must be a 2 dimensional, square matrix
9970 * @param {number} y a positive, integer value
9971 * @returns {Array}
9972 * @private
9973 */
9974 function _powArray(x, y) {
9975 if (!isInteger(y) || y < 0) {
9976 throw new TypeError('For A^b, b must be a positive integer (value is ' + y + ')');
9977 }
9978 // verify that A is a 2 dimensional square matrix
9979 var s = size(x);
9980 if (s.length != 2) {
9981 throw new Error('For A^b, A must be 2 dimensional (A has ' + s.length + ' dimensions)');
9982 }
9983 if (s[0] != s[1]) {
9984 throw new Error('For A^b, A must be square (size is ' + s[0] + 'x' + s[1] + ')');
9985 }
9986
9987 var res = eye(s[0]).valueOf();
9988 var px = x;
9989 while (y >= 1) {
9990 if ((y & 1) == 1) {
9991 res = multiply(px, res);
9992 }
9993 y >>= 1;
9994 px = multiply(px, px);
9995 }
9996 return res;
9997 }
9998
9999 /**
10000 * Calculate the power of a 2d matrix
10001 * @param {Matrix} x must be a 2 dimensional, square matrix
10002 * @param {number} y a positive, integer value
10003 * @returns {Matrix}
10004 * @private
10005 */
10006 function _powMatrix (x, y) {
10007 return matrix(_powArray(x.valueOf(), y));
10008 }
10009
10010
10011
10012 pow.toTex = {
10013 2: '\\left(${args[0]}\\right)' + latex.operators['pow'] + '{${args[1]}}'
10014 };
10015
10016 return pow;
10017}
10018
10019exports.name = 'pow';
10020exports.factory = factory;
10021
10022
10023/***/ }),
10024/* 47 */
10025/***/ (function(module, exports, __webpack_require__) {
10026
10027"use strict";
10028
10029
10030var getType = __webpack_require__(60).type;
10031var stringify = __webpack_require__(9).stringify;
10032var escape = __webpack_require__(9).escape;
10033var escapeLatex = __webpack_require__(4).escape;
10034
10035function factory (type, config, load, typed) {
10036 var register = load(__webpack_require__(7)).register;
10037 var compile = load(__webpack_require__(7)).compile;
10038 var Node = load(__webpack_require__(15));
10039
10040 /**
10041 * A ConstantNode holds a constant value like a number or string. A ConstantNode
10042 * stores a stringified version of the value and uses this to compile to
10043 * JavaScript.
10044 *
10045 * In case of a stringified number as input, this may be compiled to a BigNumber
10046 * when the math instance is configured for BigNumbers.
10047 *
10048 * Usage:
10049 *
10050 * // stringified values with type
10051 * new ConstantNode('2.3', 'number');
10052 * new ConstantNode('true', 'boolean');
10053 * new ConstantNode('hello', 'string');
10054 *
10055 * // non-stringified values, type will be automatically detected
10056 * new ConstantNode(2.3);
10057 * new ConstantNode('hello');
10058 *
10059 * @param {string | number | boolean | null | undefined} value
10060 * When valueType is provided, value must contain
10061 * an uninterpreted string representing the value.
10062 * When valueType is undefined, value can be a
10063 * number, string, boolean, null, or undefined, and
10064 * the type will be determined automatically.
10065 * @param {string} [valueType] The type of value. Choose from 'number', 'string',
10066 * 'boolean', 'undefined', 'null'
10067 * @constructor ConstantNode
10068 * @extends {Node}
10069 */
10070 function ConstantNode(value, valueType) {
10071 if (!(this instanceof ConstantNode)) {
10072 throw new SyntaxError('Constructor must be called with the new operator');
10073 }
10074
10075 if (valueType) {
10076 if (typeof valueType !== 'string') {
10077 throw new TypeError('String expected for parameter "valueType"');
10078 }
10079 if (typeof value !== 'string') {
10080 throw new TypeError('String expected for parameter "value"');
10081 }
10082
10083 this.value = value;
10084 this.valueType = valueType;
10085 }
10086 else {
10087 // stringify the value and determine the type
10088 this.value = value + '';
10089 this.valueType = getType(value);
10090 }
10091
10092 if (!SUPPORTED_TYPES[this.valueType]) {
10093 throw new TypeError('Unsupported type of value "' + this.valueType + '"');
10094 }
10095 }
10096
10097 var SUPPORTED_TYPES = {
10098 'number': true,
10099 'string': true,
10100 'boolean': true,
10101 'undefined': true,
10102 'null': true
10103 };
10104
10105 ConstantNode.prototype = new Node();
10106
10107 ConstantNode.prototype.type = 'ConstantNode';
10108
10109 ConstantNode.prototype.isConstantNode = true;
10110
10111 /**
10112 * Compile the node to javascript code
10113 * @param {ConstantNode} node The node to be compiled
10114 * @param {Object} defs Object which can be used to define functions
10115 * or constants globally available for the compiled
10116 * expression
10117 * @param {Object} args Object with local function arguments, the key is
10118 * the name of the argument, and the value is `true`.
10119 * The object may not be mutated, but must be
10120 * extended instead.
10121 * @return {string} js
10122 * @private
10123 */
10124 function compileConstantNode(node, defs, args) {
10125 if (!(node instanceof ConstantNode)) {
10126 throw new TypeError('No valid ConstantNode')
10127 }
10128
10129 switch (node.valueType) {
10130 case 'number':
10131 if (config.number === 'BigNumber') {
10132 return 'math.bignumber(' + stringify(node.value) + ')';
10133 }
10134 else if (config.number === 'Fraction') {
10135 return 'math.fraction(' + stringify(node.value) + ')';
10136 }
10137 else {
10138 // remove leading zeros like '003.2' which are not allowed by JavaScript
10139 validateNumericValue(node.value);
10140 return node.value.replace(/^(0*)[0-9]/, function (match, zeros) {
10141 return match.substring(zeros.length);
10142 });
10143 }
10144
10145 case 'string':
10146 // Important to escape unescaped double quotes in the string
10147 return stringify(node.value);
10148
10149 case 'boolean':
10150 // prevent invalid values
10151 return String(node.value) === 'true' ? 'true' : 'false';
10152
10153 case 'undefined':
10154 return 'undefined';
10155
10156 case 'null':
10157 return 'null';
10158
10159 default:
10160 // TODO: move this error to the constructor?
10161 throw new TypeError('Unsupported type of constant "' + node.valueType + '"');
10162 }
10163 }
10164
10165 /**
10166 * Test whether value is a string containing a numeric value
10167 * @param {String} value
10168 * @return {boolean} Returns true when ok
10169 */
10170 function validateNumericValue (value) {
10171 // The following regexp is relatively permissive
10172 if (typeof value !== 'string' ||
10173 !/^[\-+]?((\d+\.?\d*)|(\d*\.?\d+))([eE][+\-]?\d+)?$/.test(value)) {
10174 throw new Error('Invalid numeric value "' + value + '"');
10175 }
10176 }
10177
10178 // register the compile function
10179 register(ConstantNode.prototype.type, compileConstantNode);
10180
10181 /**
10182 * Execute a callback for each of the child nodes of this node
10183 * @param {function(child: Node, path: string, parent: Node)} callback
10184 */
10185 ConstantNode.prototype.forEach = function (callback) {
10186 // nothing to do, we don't have childs
10187 };
10188
10189
10190 /**
10191 * Create a new ConstantNode having it's childs be the results of calling
10192 * the provided callback function for each of the childs of the original node.
10193 * @param {function(child: Node, path: string, parent: Node) : Node} callback
10194 * @returns {ConstantNode} Returns a clone of the node
10195 */
10196 ConstantNode.prototype.map = function (callback) {
10197 return this.clone();
10198 };
10199
10200 /**
10201 * Create a clone of this node, a shallow copy
10202 * @return {ConstantNode}
10203 */
10204 ConstantNode.prototype.clone = function () {
10205 return new ConstantNode(this.value, this.valueType);
10206 };
10207
10208 /**
10209 * Get string representation
10210 * @param {Object} options
10211 * @return {string} str
10212 */
10213 ConstantNode.prototype._toString = function (options) {
10214 switch (this.valueType) {
10215 case 'string':
10216 return stringify(this.value);
10217
10218 default:
10219 return this.value;
10220 }
10221 };
10222
10223 /**
10224 * Get HTML representation
10225 * @param {Object} options
10226 * @return {string} str
10227 */
10228 ConstantNode.prototype.toHTML = function (options) {
10229 var value = escape(this.value);
10230 switch (this.valueType) {
10231 case 'number':
10232 return '<span class="math-number">' + value + '</span>';
10233 case 'string':
10234 return '<span class="math-string">' + value + '</span>';
10235 case 'boolean':
10236 return '<span class="math-boolean">' + value + '</span>';
10237 case 'null':
10238 return '<span class="math-null-symbol">' + value + '</span>';
10239 case 'undefined':
10240 return '<span class="math-undefined">' + value + '</span>';
10241
10242 default:
10243 return '<span class="math-symbol">' + value + '</span>';
10244 }
10245 };
10246
10247 /**
10248 * Get LaTeX representation
10249 * @param {Object} options
10250 * @return {string} str
10251 */
10252 ConstantNode.prototype._toTex = function (options) {
10253 var value = this.value,
10254 index;
10255 switch (this.valueType) {
10256 case 'string':
10257 return '\\mathtt{' + escapeLatex(stringify(value)) + '}';
10258
10259 case 'number':
10260 index = value.toLowerCase().indexOf('e');
10261 if (index !== -1) {
10262 return value.substring(0, index) + '\\cdot10^{' +
10263 value.substring(index + 1) + '}';
10264 }
10265 return value;
10266
10267 default:
10268 return value;
10269 }
10270 };
10271
10272 return ConstantNode;
10273}
10274
10275exports.name = 'ConstantNode';
10276exports.path = 'expression.node';
10277exports.factory = factory;
10278
10279
10280/***/ }),
10281/* 48 */
10282/***/ (function(module, exports, __webpack_require__) {
10283
10284"use strict";
10285
10286
10287var isMatrix = __webpack_require__(59);
10288
10289/**
10290 * Test whether a value is a collection: an Array or Matrix
10291 * @param {*} x
10292 * @returns {boolean} isCollection
10293 */
10294module.exports = function isCollection (x) {
10295 return Array.isArray(x) || isMatrix(x);
10296};
10297
10298
10299/***/ }),
10300/* 49 */
10301/***/ (function(module, exports, __webpack_require__) {
10302
10303"use strict";
10304
10305
10306var extend = __webpack_require__(5).extend;
10307
10308function factory (type, config, load, typed) {
10309
10310 var divideScalar = load(__webpack_require__(14));
10311 var multiply = load(__webpack_require__(12));
10312 var inv = load(__webpack_require__(116));
10313 var matrix = load(__webpack_require__(0));
10314
10315 var algorithm11 = load(__webpack_require__(19));
10316 var algorithm14 = load(__webpack_require__(6));
10317
10318 /**
10319 * Divide two values, `x / y`.
10320 * To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`.
10321 *
10322 * Syntax:
10323 *
10324 * math.divide(x, y)
10325 *
10326 * Examples:
10327 *
10328 * math.divide(2, 3); // returns number 0.6666666666666666
10329 *
10330 * var a = math.complex(5, 14);
10331 * var b = math.complex(4, 1);
10332 * math.divide(a, b); // returns Complex 2 + 3i
10333 *
10334 * var c = [[7, -6], [13, -4]];
10335 * var d = [[1, 2], [4, 3]];
10336 * math.divide(c, d); // returns Array [[-9, 4], [-11, 6]]
10337 *
10338 * var e = math.unit('18 km');
10339 * math.divide(e, 4.5); // returns Unit 4 km
10340 *
10341 * See also:
10342 *
10343 * multiply
10344 *
10345 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Numerator
10346 * @param {number | BigNumber | Fraction | Complex | Array | Matrix} y Denominator
10347 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Quotient, `x / y`
10348 */
10349 var divide = typed('divide', extend({
10350 // we extend the signatures of divideScalar with signatures dealing with matrices
10351
10352 'Array | Matrix, Array | Matrix': function (x, y) {
10353 // TODO: implement matrix right division using pseudo inverse
10354 // http://www.mathworks.nl/help/matlab/ref/mrdivide.html
10355 // http://www.gnu.org/software/octave/doc/interpreter/Arithmetic-Ops.html
10356 // http://stackoverflow.com/questions/12263932/how-does-gnu-octave-matrix-division-work-getting-unexpected-behaviour
10357 return multiply(x, inv(y));
10358 },
10359
10360 'Matrix, any': function (x, y) {
10361 // result
10362 var c;
10363
10364 // process storage format
10365 switch (x.storage()) {
10366 case 'sparse':
10367 c = algorithm11(x, y, divideScalar, false);
10368 break;
10369 case 'dense':
10370 c = algorithm14(x, y, divideScalar, false);
10371 break;
10372 }
10373 return c;
10374 },
10375
10376 'Array, any': function (x, y) {
10377 // use matrix implementation
10378 return algorithm14(matrix(x), y, divideScalar, false).valueOf();
10379 },
10380
10381 'any, Array | Matrix': function (x, y) {
10382 return multiply(x, inv(y));
10383 }
10384 }, divideScalar.signatures));
10385
10386 divide.toTex = {2: '\\frac{${args[0]}}{${args[1]}}'};
10387
10388 return divide;
10389}
10390
10391exports.name = 'divide';
10392exports.factory = factory;
10393
10394
10395/***/ }),
10396/* 50 */
10397/***/ (function(module, exports, __webpack_require__) {
10398
10399"use strict";
10400
10401
10402var deepMap = __webpack_require__(1);
10403
10404function factory (type, config, load, typed) {
10405 /**
10406 * Calculate the square root of a value.
10407 *
10408 * For matrices, the function is evaluated element wise.
10409 *
10410 * Syntax:
10411 *
10412 * math.sqrt(x)
10413 *
10414 * Examples:
10415 *
10416 * math.sqrt(25); // returns 5
10417 * math.square(5); // returns 25
10418 * math.sqrt(-4); // returns Complex 2i
10419 *
10420 * See also:
10421 *
10422 * square, multiply, cube, cbrt
10423 *
10424 * @param {number | BigNumber | Complex | Array | Matrix | Unit} x
10425 * Value for which to calculate the square root.
10426 * @return {number | BigNumber | Complex | Array | Matrix | Unit}
10427 * Returns the square root of `x`
10428 */
10429 var sqrt = typed('sqrt', {
10430 'number': _sqrtNumber,
10431
10432 'Complex': function (x) {
10433 return x.sqrt();
10434 },
10435
10436 'BigNumber': function (x) {
10437 if (!x.isNegative() || config.predictable) {
10438 return x.sqrt();
10439 }
10440 else {
10441 // negative value -> downgrade to number to do complex value computation
10442 return _sqrtNumber(x.toNumber());
10443 }
10444 },
10445
10446 'Array | Matrix': function (x) {
10447 // deep map collection, skip zeros since sqrt(0) = 0
10448 return deepMap(x, sqrt, true);
10449 },
10450
10451 'Unit': function (x) {
10452 // Someday will work for complex units when they are implemented
10453 return x.pow(0.5);
10454 }
10455
10456 });
10457
10458 /**
10459 * Calculate sqrt for a number
10460 * @param {number} x
10461 * @returns {number | Complex} Returns the square root of x
10462 * @private
10463 */
10464 function _sqrtNumber(x) {
10465 if (x >= 0 || config.predictable) {
10466 return Math.sqrt(x);
10467 }
10468 else {
10469 return new type.Complex(x, 0).sqrt();
10470 }
10471 }
10472
10473 sqrt.toTex = {1: '\\sqrt{${args[0]}}'};
10474
10475 return sqrt;
10476}
10477
10478exports.name = 'sqrt';
10479exports.factory = factory;
10480
10481
10482/***/ }),
10483/* 51 */
10484/***/ (function(module, exports, __webpack_require__) {
10485
10486"use strict";
10487
10488
10489var deepMap = __webpack_require__(1);
10490var number = __webpack_require__(3);
10491
10492function factory (type, config, load, typed) {
10493 /**
10494 * Test whether a value is an integer number.
10495 * The function supports `number`, `BigNumber`, and `Fraction`.
10496 *
10497 * The function is evaluated element-wise in case of Array or Matrix input.
10498 *
10499 * Syntax:
10500 *
10501 * math.isInteger(x)
10502 *
10503 * Examples:
10504 *
10505 * math.isInteger(2); // returns true
10506 * math.isInteger(0); // returns true
10507 * math.isInteger(0.5); // returns false
10508 * math.isInteger(math.bignumber(500)); // returns true
10509 * math.isInteger(math.fraction(4)); // returns true
10510 * math.isInteger('3'); // returns true
10511 * math.isInteger([3, 0.5, -2]); // returns [true, false, true]
10512 * math.isInteger(math.complex('2-4i'); // throws an error
10513 *
10514 * See also:
10515 *
10516 * isNumeric, isPositive, isNegative, isZero
10517 *
10518 * @param {number | BigNumber | Fraction | Array | Matrix} x Value to be tested
10519 * @return {boolean} Returns true when `x` contains a numeric, integer value.
10520 * Throws an error in case of an unknown data type.
10521 */
10522 var isInteger = typed('isInteger', {
10523 'number': number.isInteger, // TODO: what to do with isInteger(add(0.1, 0.2)) ?
10524
10525 'BigNumber': function (x) {
10526 return x.isInt();
10527 },
10528
10529 'Fraction': function (x) {
10530 return x.d === 1 && isFinite(x.n);
10531 },
10532
10533 'Array | Matrix': function (x) {
10534 return deepMap(x, isInteger);
10535 }
10536 });
10537
10538 return isInteger;
10539}
10540
10541exports.name = 'isInteger';
10542exports.factory = factory;
10543
10544
10545/***/ }),
10546/* 52 */
10547/***/ (function(module, exports, __webpack_require__) {
10548
10549"use strict";
10550
10551
10552var nearlyEqual = __webpack_require__(3).nearlyEqual;
10553var bigNearlyEqual = __webpack_require__(37);
10554
10555function factory (type, config, load, typed) {
10556
10557 var matrix = load(__webpack_require__(0));
10558
10559 var algorithm03 = load(__webpack_require__(17));
10560 var algorithm05 = load(__webpack_require__(61));
10561 var algorithm12 = load(__webpack_require__(18));
10562 var algorithm13 = load(__webpack_require__(8));
10563 var algorithm14 = load(__webpack_require__(6));
10564
10565 /**
10566 * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y.
10567 *
10568 * x and y are considered equal when the relative difference between x and y
10569 * is smaller than the configured epsilon. The function cannot be used to
10570 * compare values smaller than approximately 2.22e-16.
10571 *
10572 * For matrices, the function is evaluated element wise.
10573 *
10574 * Syntax:
10575 *
10576 * math.compare(x, y)
10577 *
10578 * Examples:
10579 *
10580 * math.compare(6, 1); // returns 1
10581 * math.compare(2, 3); // returns -1
10582 * math.compare(7, 7); // returns 0
10583 *
10584 * var a = math.unit('5 cm');
10585 * var b = math.unit('40 mm');
10586 * math.compare(a, b); // returns 1
10587 *
10588 * math.compare(2, [1, 2, 3]); // returns [1, 0, -1]
10589 *
10590 * See also:
10591 *
10592 * equal, unequal, smaller, smallerEq, larger, largerEq, compareNatural
10593 *
10594 * @param {number | BigNumber | Fraction | Unit | string | Array | Matrix} x First value to compare
10595 * @param {number | BigNumber | Fraction | Unit | string | Array | Matrix} y Second value to compare
10596 * @return {number | BigNumber | Fraction | Array | Matrix} Returns the result of the comparison: 1, 0 or -1.
10597 */
10598 var compare = typed('compare', {
10599
10600 'boolean, boolean': function (x, y) {
10601 return x === y ? 0 : (x > y ? 1 : -1);
10602 },
10603
10604 'number, number': function (x, y) {
10605 return (x === y || nearlyEqual(x, y, config.epsilon))
10606 ? 0
10607 : (x > y ? 1 : -1);
10608 },
10609
10610 'BigNumber, BigNumber': function (x, y) {
10611 return (x.eq(y) || bigNearlyEqual(x, y, config.epsilon))
10612 ? new type.BigNumber(0)
10613 : new type.BigNumber(x.cmp(y));
10614 },
10615
10616 'Fraction, Fraction': function (x, y) {
10617 return new type.Fraction(x.compare(y));
10618 },
10619
10620 'Complex, Complex': function () {
10621 throw new TypeError('No ordering relation is defined for complex numbers');
10622 },
10623
10624 'Unit, Unit': function (x, y) {
10625 if (!x.equalBase(y)) {
10626 throw new Error('Cannot compare units with different base');
10627 }
10628 return compare(x.value, y.value);
10629 },
10630
10631 'string, string': function (x, y) {
10632 return x === y ? 0 : (x > y ? 1 : -1);
10633 },
10634
10635 'Matrix, Matrix': function (x, y) {
10636 // result
10637 var c;
10638
10639 // process matrix storage
10640 switch (x.storage()) {
10641 case 'sparse':
10642 switch (y.storage()) {
10643 case 'sparse':
10644 // sparse + sparse
10645 c = algorithm05(x, y, compare);
10646 break;
10647 default:
10648 // sparse + dense
10649 c = algorithm03(y, x, compare, true);
10650 break;
10651 }
10652 break;
10653 default:
10654 switch (y.storage()) {
10655 case 'sparse':
10656 // dense + sparse
10657 c = algorithm03(x, y, compare, false);
10658 break;
10659 default:
10660 // dense + dense
10661 c = algorithm13(x, y, compare);
10662 break;
10663 }
10664 break;
10665 }
10666 return c;
10667 },
10668
10669 'Array, Array': function (x, y) {
10670 // use matrix implementation
10671 return compare(matrix(x), matrix(y)).valueOf();
10672 },
10673
10674 'Array, Matrix': function (x, y) {
10675 // use matrix implementation
10676 return compare(matrix(x), y);
10677 },
10678
10679 'Matrix, Array': function (x, y) {
10680 // use matrix implementation
10681 return compare(x, matrix(y));
10682 },
10683
10684 'Matrix, any': function (x, y) {
10685 // result
10686 var c;
10687 // check storage format
10688 switch (x.storage()) {
10689 case 'sparse':
10690 c = algorithm12(x, y, compare, false);
10691 break;
10692 default:
10693 c = algorithm14(x, y, compare, false);
10694 break;
10695 }
10696 return c;
10697 },
10698
10699 'any, Matrix': function (x, y) {
10700 // result
10701 var c;
10702 // check storage format
10703 switch (y.storage()) {
10704 case 'sparse':
10705 c = algorithm12(y, x, compare, true);
10706 break;
10707 default:
10708 c = algorithm14(y, x, compare, true);
10709 break;
10710 }
10711 return c;
10712 },
10713
10714 'Array, any': function (x, y) {
10715 // use matrix implementation
10716 return algorithm14(matrix(x), y, compare, false).valueOf();
10717 },
10718
10719 'any, Array': function (x, y) {
10720 // use matrix implementation
10721 return algorithm14(matrix(y), x, compare, true).valueOf();
10722 }
10723 });
10724
10725 compare.toTex = undefined; // use default template
10726
10727 return compare;
10728}
10729
10730exports.name = 'compare';
10731exports.factory = factory;
10732
10733
10734/***/ }),
10735/* 53 */
10736/***/ (function(module, exports, __webpack_require__) {
10737
10738"use strict";
10739
10740
10741/**
10742 * Create a range error with the message:
10743 * 'Index out of range (index < min)'
10744 * 'Index out of range (index < max)'
10745 *
10746 * @param {number} index The actual index
10747 * @param {number} [min=0] Minimum index (included)
10748 * @param {number} [max] Maximum index (excluded)
10749 * @extends RangeError
10750 */
10751function IndexError(index, min, max) {
10752 if (!(this instanceof IndexError)) {
10753 throw new SyntaxError('Constructor must be called with the new operator');
10754 }
10755
10756 this.index = index;
10757 if (arguments.length < 3) {
10758 this.min = 0;
10759 this.max = min;
10760 }
10761 else {
10762 this.min = min;
10763 this.max = max;
10764 }
10765
10766 if (this.min !== undefined && this.index < this.min) {
10767 this.message = 'Index out of range (' + this.index + ' < ' + this.min + ')';
10768 }
10769 else if (this.max !== undefined && this.index >= this.max) {
10770 this.message = 'Index out of range (' + this.index + ' > ' + (this.max - 1) + ')';
10771 }
10772 else {
10773 this.message = 'Index out of range (' + this.index + ')';
10774 }
10775
10776 this.stack = (new Error()).stack;
10777}
10778
10779IndexError.prototype = new RangeError();
10780IndexError.prototype.constructor = RangeError;
10781IndexError.prototype.name = 'IndexError';
10782IndexError.prototype.isIndexError = true;
10783
10784module.exports = IndexError;
10785
10786
10787/***/ }),
10788/* 54 */
10789/***/ (function(module, exports, __webpack_require__) {
10790
10791"use strict";
10792
10793
10794//list of identifiers of nodes in order of their precedence
10795//also contains information about left/right associativity
10796//and which other operator the operator is associative with
10797//Example:
10798// addition is associative with addition and subtraction, because:
10799// (a+b)+c=a+(b+c)
10800// (a+b)-c=a+(b-c)
10801//
10802// postfix operators are left associative, prefix operators
10803// are right associative
10804//
10805//It's also possible to set the following properties:
10806// latexParens: if set to false, this node doesn't need to be enclosed
10807// in parentheses when using LaTeX
10808// latexLeftParens: if set to false, this !OperatorNode's!
10809// left argument doesn't need to be enclosed
10810// in parentheses
10811// latexRightParens: the same for the right argument
10812var properties = [
10813 { //assignment
10814 'AssignmentNode': {},
10815 'FunctionAssignmentNode': {}
10816 },
10817 { //conditional expression
10818 'ConditionalNode': {
10819 latexLeftParens: false,
10820 latexRightParens: false,
10821 latexParens: false
10822 //conditionals don't need parentheses in LaTeX because
10823 //they are 2 dimensional
10824 }
10825 },
10826 { //logical or
10827 'OperatorNode:or': {
10828 associativity: 'left',
10829 associativeWith: []
10830 }
10831
10832 },
10833 { //logical xor
10834 'OperatorNode:xor': {
10835 associativity: 'left',
10836 associativeWith: []
10837 }
10838 },
10839 { //logical and
10840 'OperatorNode:and': {
10841 associativity: 'left',
10842 associativeWith: []
10843 }
10844 },
10845 { //bitwise or
10846 'OperatorNode:bitOr': {
10847 associativity: 'left',
10848 associativeWith: []
10849 }
10850 },
10851 { //bitwise xor
10852 'OperatorNode:bitXor': {
10853 associativity: 'left',
10854 associativeWith: []
10855 }
10856 },
10857 { //bitwise and
10858 'OperatorNode:bitAnd': {
10859 associativity: 'left',
10860 associativeWith: []
10861 }
10862 },
10863 { //relational operators
10864 'OperatorNode:equal': {
10865 associativity: 'left',
10866 associativeWith: []
10867 },
10868 'OperatorNode:unequal': {
10869 associativity: 'left',
10870 associativeWith: []
10871 },
10872 'OperatorNode:smaller': {
10873 associativity: 'left',
10874 associativeWith: []
10875 },
10876 'OperatorNode:larger': {
10877 associativity: 'left',
10878 associativeWith: []
10879 },
10880 'OperatorNode:smallerEq': {
10881 associativity: 'left',
10882 associativeWith: []
10883 },
10884 'OperatorNode:largerEq': {
10885 associativity: 'left',
10886 associativeWith: []
10887 }
10888 },
10889 { //bitshift operators
10890 'OperatorNode:leftShift': {
10891 associativity: 'left',
10892 associativeWith: []
10893 },
10894 'OperatorNode:rightArithShift': {
10895 associativity: 'left',
10896 associativeWith: []
10897 },
10898 'OperatorNode:rightLogShift': {
10899 associativity: 'left',
10900 associativeWith: []
10901 }
10902 },
10903 { //unit conversion
10904 'OperatorNode:to': {
10905 associativity: 'left',
10906 associativeWith: []
10907 }
10908 },
10909 { //range
10910 'RangeNode': {}
10911 },
10912 { //addition, subtraction
10913 'OperatorNode:add': {
10914 associativity: 'left',
10915 associativeWith: ['OperatorNode:add', 'OperatorNode:subtract']
10916 },
10917 'OperatorNode:subtract': {
10918 associativity: 'left',
10919 associativeWith: []
10920 }
10921 },
10922 { //multiply, divide, modulus
10923 'OperatorNode:multiply': {
10924 associativity: 'left',
10925 associativeWith: [
10926 'OperatorNode:multiply',
10927 'OperatorNode:divide',
10928 'Operator:dotMultiply',
10929 'Operator:dotDivide'
10930 ]
10931 },
10932 'OperatorNode:divide': {
10933 associativity: 'left',
10934 associativeWith: [],
10935 latexLeftParens: false,
10936 latexRightParens: false,
10937 latexParens: false
10938 //fractions don't require parentheses because
10939 //they're 2 dimensional, so parens aren't needed
10940 //in LaTeX
10941 },
10942 'OperatorNode:dotMultiply': {
10943 associativity: 'left',
10944 associativeWith: [
10945 'OperatorNode:multiply',
10946 'OperatorNode:divide',
10947 'OperatorNode:dotMultiply',
10948 'OperatorNode:doDivide'
10949 ]
10950 },
10951 'OperatorNode:dotDivide': {
10952 associativity: 'left',
10953 associativeWith: []
10954 },
10955 'OperatorNode:mod': {
10956 associativity: 'left',
10957 associativeWith: []
10958 }
10959 },
10960 { //unary prefix operators
10961 'OperatorNode:unaryPlus': {
10962 associativity: 'right'
10963 },
10964 'OperatorNode:unaryMinus': {
10965 associativity: 'right'
10966 },
10967 'OperatorNode:bitNot': {
10968 associativity: 'right'
10969 },
10970 'OperatorNode:not': {
10971 associativity: 'right'
10972 }
10973 },
10974 { //exponentiation
10975 'OperatorNode:pow': {
10976 associativity: 'right',
10977 associativeWith: [],
10978 latexRightParens: false
10979 //the exponent doesn't need parentheses in
10980 //LaTeX because it's 2 dimensional
10981 //(it's on top)
10982 },
10983 'OperatorNode:dotPow': {
10984 associativity: 'right',
10985 associativeWith: []
10986 }
10987 },
10988 { //factorial
10989 'OperatorNode:factorial': {
10990 associativity: 'left'
10991 }
10992 },
10993 { //matrix transpose
10994 'OperatorNode:transpose': {
10995 associativity: 'left'
10996 }
10997 }
10998];
10999
11000/**
11001 * Get the precedence of a Node.
11002 * Higher number for higher precedence, starting with 0.
11003 * Returns null if the precedence is undefined.
11004 *
11005 * @param {Node}
11006 * @param {string} parenthesis
11007 * @return {number|null}
11008 */
11009function getPrecedence (_node, parenthesis) {
11010 var node = _node;
11011 if (parenthesis !== 'keep') {
11012 //ParenthesisNodes are only ignored when not in 'keep' mode
11013 node = _node.getContent();
11014 }
11015 var identifier = node.getIdentifier();
11016 for (var i = 0; i < properties.length; i++) {
11017 if (identifier in properties[i]) {
11018 return i;
11019 }
11020 }
11021 return null;
11022}
11023
11024/**
11025 * Get the associativity of an operator (left or right).
11026 * Returns a string containing 'left' or 'right' or null if
11027 * the associativity is not defined.
11028 *
11029 * @param {Node}
11030 * @param {string} parenthesis
11031 * @return {string|null}
11032 * @throws {Error}
11033 */
11034function getAssociativity (_node, parenthesis) {
11035 var node = _node;
11036 if (parenthesis !== 'keep') {
11037 //ParenthesisNodes are only ignored when not in 'keep' mode
11038 node = _node.getContent();
11039 }
11040 var identifier = node.getIdentifier();
11041 var index = getPrecedence(node, parenthesis);
11042 if (index === null) {
11043 //node isn't in the list
11044 return null;
11045 }
11046 var property = properties[index][identifier];
11047
11048 if (property.hasOwnProperty('associativity')) {
11049 if (property.associativity === 'left') {
11050 return 'left';
11051 }
11052 if (property.associativity === 'right') {
11053 return 'right';
11054 }
11055 //associativity is invalid
11056 throw Error('\'' + identifier + '\' has the invalid associativity \''
11057 + property.associativity + '\'.');
11058 }
11059
11060 //associativity is undefined
11061 return null;
11062}
11063
11064/**
11065 * Check if an operator is associative with another operator.
11066 * Returns either true or false or null if not defined.
11067 *
11068 * @param {Node} nodeA
11069 * @param {Node} nodeB
11070 * @param {string} parenthesis
11071 * @return {bool|null}
11072 */
11073function isAssociativeWith (nodeA, nodeB, parenthesis) {
11074 var a = nodeA;
11075 var b = nodeB;
11076 if (parenthesis !== 'keep') {
11077 //ParenthesisNodes are only ignored when not in 'keep' mode
11078 var a = nodeA.getContent();
11079 var b = nodeB.getContent();
11080 }
11081 var identifierA = a.getIdentifier();
11082 var identifierB = b.getIdentifier();
11083 var index = getPrecedence(a, parenthesis);
11084 if (index === null) {
11085 //node isn't in the list
11086 return null;
11087 }
11088 var property = properties[index][identifierA];
11089
11090 if (property.hasOwnProperty('associativeWith')
11091 && (property.associativeWith instanceof Array)) {
11092 for (var i = 0; i < property.associativeWith.length; i++) {
11093 if (property.associativeWith[i] === identifierB) {
11094 return true;
11095 }
11096 }
11097 return false;
11098 }
11099
11100 //associativeWith is not defined
11101 return null;
11102}
11103
11104module.exports.properties = properties;
11105module.exports.getPrecedence = getPrecedence;
11106module.exports.getAssociativity = getAssociativity;
11107module.exports.isAssociativeWith = isAssociativeWith;
11108
11109
11110/***/ }),
11111/* 55 */
11112/***/ (function(module, exports, __webpack_require__) {
11113
11114"use strict";
11115
11116
11117var latex = __webpack_require__(4);
11118var map = __webpack_require__(2).map;
11119var join = __webpack_require__(2).join;
11120var stringify = __webpack_require__(9).stringify;
11121var escape = __webpack_require__(9).escape;
11122var isSafeMethod = __webpack_require__(13).isSafeMethod;
11123var operators = __webpack_require__(54);
11124
11125function factory (type, config, load, typed) {
11126 var register = load(__webpack_require__(7)).register;
11127 var compile = load(__webpack_require__(7)).compile;
11128 var Node = load(__webpack_require__(15));
11129 var ConstantNode = load(__webpack_require__(47));
11130 var SymbolNode = load(__webpack_require__(36));
11131 var FunctionNode = load(__webpack_require__(56));
11132
11133 /**
11134 * @constructor OperatorNode
11135 * @extends {Node}
11136 * An operator with two arguments, like 2+3
11137 *
11138 * @param {string} op Operator name, for example '+'
11139 * @param {string} fn Function name, for example 'add'
11140 * @param {Node[]} args Operator arguments
11141 * @param {boolean} [implicit] Is this an implicit multiplication?
11142 */
11143 function OperatorNode(op, fn, args, implicit) {
11144 if (!(this instanceof OperatorNode)) {
11145 throw new SyntaxError('Constructor must be called with the new operator');
11146 }
11147
11148 //validate input
11149 if (typeof op !== 'string') {
11150 throw new TypeError('string expected for parameter "op"');
11151 }
11152 if (typeof fn !== 'string') {
11153 throw new TypeError('string expected for parameter "fn"');
11154 }
11155 if (!Array.isArray(args) || !args.every(type.isNode)) {
11156 throw new TypeError('Array containing Nodes expected for parameter "args"');
11157 }
11158
11159 this.implicit = (implicit === true);
11160 this.op = op;
11161 this.fn = fn;
11162 this.args = args || [];
11163 }
11164
11165 OperatorNode.prototype = new Node();
11166
11167 OperatorNode.prototype.type = 'OperatorNode';
11168
11169 OperatorNode.prototype.isOperatorNode = true;
11170
11171 /**
11172 * Compile the node to javascript code
11173 * @param {OperatorNode} node The node to be compiled
11174 * @param {Object} defs Object which can be used to define functions
11175 * or constants globally available for the compiled
11176 * expression
11177 * @param {Object} args Object with local function arguments, the key is
11178 * the name of the argument, and the value is `true`.
11179 * The object may not be mutated, but must be
11180 * extended instead.
11181 * @return {string} js
11182 * @private
11183 */
11184 function compileOperatorNode(node, defs, args) {
11185 if (!(node instanceof OperatorNode)) {
11186 throw new TypeError('No valid OperatorNode')
11187 }
11188
11189 // validate fn
11190 if (typeof node.fn !== 'string' || !isSafeMethod(defs.math, node.fn)) {
11191 if (!defs.math[node.fn]) {
11192 throw new Error('Function ' + node.fn + ' missing in provided namespace "math"');
11193 }
11194 else {
11195 throw new Error('No access to function "' + node.fn + '"');
11196 }
11197 }
11198
11199 var jsArgs = map(node.args, function (arg) {
11200 return compile(arg, defs, args);
11201 });
11202
11203 return 'math[' + stringify(node.fn) + '](' + join(jsArgs, ', ') + ')';
11204 }
11205
11206 // register the compile function
11207 register(OperatorNode.prototype.type, compileOperatorNode);
11208
11209 /**
11210 * Execute a callback for each of the child nodes of this node
11211 * @param {function(child: Node, path: string, parent: Node)} callback
11212 */
11213 OperatorNode.prototype.forEach = function (callback) {
11214 for (var i = 0; i < this.args.length; i++) {
11215 callback(this.args[i], 'args[' + i + ']', this);
11216 }
11217 };
11218
11219 /**
11220 * Create a new OperatorNode having it's childs be the results of calling
11221 * the provided callback function for each of the childs of the original node.
11222 * @param {function(child: Node, path: string, parent: Node): Node} callback
11223 * @returns {OperatorNode} Returns a transformed copy of the node
11224 */
11225 OperatorNode.prototype.map = function (callback) {
11226 var args = [];
11227 for (var i = 0; i < this.args.length; i++) {
11228 args[i] = this._ifNode(callback(this.args[i], 'args[' + i + ']', this));
11229 }
11230 return new OperatorNode(this.op, this.fn, args, this.implicit);
11231 };
11232
11233 /**
11234 * Create a clone of this node, a shallow copy
11235 * @return {OperatorNode}
11236 */
11237 OperatorNode.prototype.clone = function () {
11238 return new OperatorNode(this.op, this.fn, this.args.slice(0), this.implicit);
11239 };
11240
11241 /**
11242 * Calculate which parentheses are necessary. Gets an OperatorNode
11243 * (which is the root of the tree) and an Array of Nodes
11244 * (this.args) and returns an array where 'true' means that an argument
11245 * has to be enclosed in parentheses whereas 'false' means the opposite.
11246 *
11247 * @param {OperatorNode} root
11248 * @param {string} parenthesis
11249 * @param {Node[]} args
11250 * @param {boolean} latex
11251 * @return {boolean[]}
11252 * @private
11253 */
11254 function calculateNecessaryParentheses(root, parenthesis, implicit, args, latex) {
11255 //precedence of the root OperatorNode
11256 var precedence = operators.getPrecedence(root, parenthesis);
11257 var associativity = operators.getAssociativity(root, parenthesis);
11258
11259 if ((parenthesis === 'all') || ((args.length > 2) && (root.getIdentifier() !== 'OperatorNode:add') && (root.getIdentifier() !== 'OperatorNode:multiply'))) {
11260 var parens = args.map(function (arg) {
11261 switch (arg.getContent().type) { //Nodes that don't need extra parentheses
11262 case 'ArrayNode':
11263 case 'ConstantNode':
11264 case 'SymbolNode':
11265 case 'ParenthesisNode':
11266 return false;
11267 break;
11268 default:
11269 return true;
11270 }
11271 });
11272 return parens;
11273 }
11274
11275 var result = undefined;
11276 switch (args.length) {
11277 case 0:
11278 result = [];
11279 break;
11280
11281 case 1: //unary operators
11282 //precedence of the operand
11283 var operandPrecedence = operators.getPrecedence(args[0], parenthesis);
11284
11285 //handle special cases for LaTeX, where some of the parentheses aren't needed
11286 if (latex && (operandPrecedence !== null)) {
11287 var operandIdentifier;
11288 var rootIdentifier;
11289 if (parenthesis === 'keep') {
11290 operandIdentifier = args[0].getIdentifier();
11291 rootIdentifier = root.getIdentifier();
11292 }
11293 else {
11294 //Ignore Parenthesis Nodes when not in 'keep' mode
11295 operandIdentifier = args[0].getContent().getIdentifier();
11296 rootIdentifier = root.getContent().getIdentifier();
11297 }
11298 if (operators.properties[precedence][rootIdentifier].latexLeftParens === false) {
11299 result = [false];
11300 break;
11301 }
11302
11303 if (operators.properties[operandPrecedence][operandIdentifier].latexParens === false) {
11304 result = [false];
11305 break;
11306 }
11307 }
11308
11309 if (operandPrecedence === null) {
11310 //if the operand has no defined precedence, no parens are needed
11311 result = [false];
11312 break;
11313 }
11314
11315 if (operandPrecedence <= precedence) {
11316 //if the operands precedence is lower, parens are needed
11317 result = [true];
11318 break;
11319 }
11320
11321 //otherwise, no parens needed
11322 result = [false];
11323 break;
11324
11325 case 2: //binary operators
11326 var lhsParens; //left hand side needs parenthesis?
11327 //precedence of the left hand side
11328 var lhsPrecedence = operators.getPrecedence(args[0], parenthesis);
11329 //is the root node associative with the left hand side
11330 var assocWithLhs = operators.isAssociativeWith(root, args[0], parenthesis);
11331
11332 if (lhsPrecedence === null) {
11333 //if the left hand side has no defined precedence, no parens are needed
11334 //FunctionNode for example
11335 lhsParens = false;
11336 }
11337 else if ((lhsPrecedence === precedence) && (associativity === 'right') && !assocWithLhs) {
11338 //In case of equal precedence, if the root node is left associative
11339 // parens are **never** necessary for the left hand side.
11340 //If it is right associative however, parens are necessary
11341 //if the root node isn't associative with the left hand side
11342 lhsParens = true;
11343 }
11344 else if (lhsPrecedence < precedence) {
11345 lhsParens = true;
11346 }
11347 else {
11348 lhsParens = false;
11349 }
11350
11351 var rhsParens; //right hand side needs parenthesis?
11352 //precedence of the right hand side
11353 var rhsPrecedence = operators.getPrecedence(args[1], parenthesis);
11354 //is the root node associative with the right hand side?
11355 var assocWithRhs = operators.isAssociativeWith(root, args[1], parenthesis);
11356
11357 if (rhsPrecedence === null) {
11358 //if the right hand side has no defined precedence, no parens are needed
11359 //FunctionNode for example
11360 rhsParens = false;
11361 }
11362 else if ((rhsPrecedence === precedence) && (associativity === 'left') && !assocWithRhs) {
11363 //In case of equal precedence, if the root node is right associative
11364 // parens are **never** necessary for the right hand side.
11365 //If it is left associative however, parens are necessary
11366 //if the root node isn't associative with the right hand side
11367 rhsParens = true;
11368 }
11369 else if (rhsPrecedence < precedence) {
11370 rhsParens = true;
11371 }
11372 else {
11373 rhsParens = false;
11374 }
11375
11376 //handle special cases for LaTeX, where some of the parentheses aren't needed
11377 if (latex) {
11378 var rootIdentifier;
11379 var lhsIdentifier;
11380 var rhsIdentifier;
11381 if (parenthesis === 'keep') {
11382 rootIdentifier = root.getIdentifier();
11383 lhsIdentifier = root.args[0].getIdentifier();
11384 rhsIdentifier = root.args[1].getIdentifier();
11385 }
11386 else {
11387 //Ignore ParenthesisNodes when not in 'keep' mode
11388 rootIdentifier = root.getContent().getIdentifier();
11389 lhsIdentifier = root.args[0].getContent().getIdentifier();
11390 rhsIdentifier = root.args[1].getContent().getIdentifier();
11391 }
11392
11393 if (lhsPrecedence !== null) {
11394 if (operators.properties[precedence][rootIdentifier].latexLeftParens === false) {
11395 lhsParens = false;
11396 }
11397
11398 if (operators.properties[lhsPrecedence][lhsIdentifier].latexParens === false) {
11399 lhsParens = false;
11400 }
11401 }
11402
11403 if (rhsPrecedence !== null) {
11404 if (operators.properties[precedence][rootIdentifier].latexRightParens === false) {
11405 rhsParens = false;
11406 }
11407
11408 if (operators.properties[rhsPrecedence][rhsIdentifier].latexParens === false) {
11409 rhsParens = false;
11410 }
11411 }
11412 }
11413
11414 result = [lhsParens, rhsParens];
11415 break;
11416
11417 default:
11418 if ((root.getIdentifier() === 'OperatorNode:add') || (root.getIdentifier() === 'OperatorNode:multiply')) {
11419 var result = args.map(function (arg) {
11420 var argPrecedence = operators.getPrecedence(arg, parenthesis);
11421 var assocWithArg = operators.isAssociativeWith(root, arg, parenthesis);
11422 var argAssociativity = operators.getAssociativity(arg, parenthesis);
11423 if (argPrecedence === null) {
11424 //if the argument has no defined precedence, no parens are needed
11425 return false;
11426 } else if ((precedence === argPrecedence) && (associativity === argAssociativity) && !assocWithArg) {
11427 return true;
11428 } else if (argPrecedence < precedence) {
11429 return true;
11430 }
11431
11432 return false;
11433 });
11434 }
11435 break;
11436 }
11437
11438 //handles an edge case of 'auto' parentheses with implicit multiplication of ConstantNode
11439 //In that case print parentheses for ParenthesisNodes even though they normally wouldn't be
11440 //printed.
11441 if ((args.length >= 2) && (root.getIdentifier() === 'OperatorNode:multiply') && root.implicit && (parenthesis === 'auto') && (implicit === 'hide')) {
11442 result = args.map(function (arg, index) {
11443 var isParenthesisNode = (arg.getIdentifier() === 'ParenthesisNode');
11444 if (result[index] || isParenthesisNode) { //put in parenthesis?
11445 return true;
11446 }
11447
11448 return false;
11449 });
11450 }
11451
11452 return result;
11453 }
11454
11455 /**
11456 * Get string representation.
11457 * @param {Object} options
11458 * @return {string} str
11459 */
11460 OperatorNode.prototype._toString = function (options) {
11461 var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep';
11462 var implicit = (options && options.implicit) ? options.implicit : 'hide';
11463 var args = this.args;
11464 var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, false);
11465
11466 if (args.length === 1) { //unary operators
11467 var assoc = operators.getAssociativity(this, parenthesis);
11468
11469 var operand = args[0].toString(options);
11470 if (parens[0]) {
11471 operand = '(' + operand + ')';
11472 }
11473
11474 if (assoc === 'right') { //prefix operator
11475 return this.op + operand;
11476 }
11477 else if (assoc === 'left') { //postfix
11478 return operand + this.op;
11479 }
11480
11481 //fall back to postfix
11482 return operand + this.op;
11483 } else if (args.length == 2) {
11484 var lhs = args[0].toString(options); //left hand side
11485 var rhs = args[1].toString(options); //right hand side
11486 if (parens[0]) { //left hand side in parenthesis?
11487 lhs = '(' + lhs + ')';
11488 }
11489 if (parens[1]) { //right hand side in parenthesis?
11490 rhs = '(' + rhs + ')';
11491 }
11492
11493 if (this.implicit && (this.getIdentifier() === 'OperatorNode:multiply') && (implicit == 'hide')) {
11494 return lhs + ' ' + rhs;
11495 }
11496
11497 return lhs + ' ' + this.op + ' ' + rhs;
11498 } else if ((args.length > 2) && ((this.getIdentifier() === 'OperatorNode:add') || (this.getIdentifier() === 'OperatorNode:multiply'))) {
11499 var stringifiedArgs = args.map(function (arg, index) {
11500 arg = arg.toString(options);
11501 if (parens[index]) { //put in parenthesis?
11502 arg = '(' + arg + ')';
11503 }
11504
11505 return arg;
11506 });
11507
11508 if (this.implicit && (this.getIdentifier() === 'OperatorNode:multiply') && (implicit === 'hide')) {
11509 return stringifiedArgs.join(' ');
11510 }
11511
11512 return stringifiedArgs.join(' ' + this.op + ' ');
11513 } else {
11514 //fallback to formatting as a function call
11515 return this.fn + '(' + this.args.join(', ') + ')';
11516 }
11517 };
11518
11519 /**
11520 * Get HTML representation.
11521 * @param {Object} options
11522 * @return {string} str
11523 */
11524 OperatorNode.prototype.toHTML = function (options) {
11525 var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep';
11526 var implicit = (options && options.implicit) ? options.implicit : 'hide';
11527 var args = this.args;
11528 var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, false);
11529
11530 if (args.length === 1) { //unary operators
11531 var assoc = operators.getAssociativity(this, parenthesis);
11532
11533 var operand = args[0].toHTML(options);
11534 if (parens[0]) {
11535 operand = '<span class="math-parenthesis math-round-parenthesis">(</span>' + operand + '<span class="math-parenthesis math-round-parenthesis">)</span>';
11536 }
11537
11538 if (assoc === 'right') { //prefix operator
11539 return '<span class="math-operator math-unary-operator math-lefthand-unary-operator">' + escape(this.op) + '</span>' + operand;
11540 }
11541 else if (assoc === 'left') { //postfix
11542 return '<span class="math-operator math-unary-operator math-righthand-unary-operator">' + escape(this.op) + '</span>' + operand;
11543 }
11544
11545 //fall back to postfix
11546 return '<span class="math-operator math-unary-operator math-righthand-unary-operator">' + escape(this.op) + '</span>' + operand;
11547 }
11548 else if (args.length == 2) { // binary operatoes
11549 var lhs = args[0].toHTML(options); //left hand side
11550 var rhs = args[1].toHTML(options); //right hand side
11551 if (parens[0]) { //left hand side in parenthesis?
11552 lhs = '<span class="math-parenthesis math-round-parenthesis">(</span>' + lhs + '<span class="math-parenthesis math-round-parenthesis">)</span>';
11553 }
11554 if (parens[1]) { //right hand side in parenthesis?
11555 rhs = '<span class="math-parenthesis math-round-parenthesis">(</span>' + rhs + '<span class="math-parenthesis math-round-parenthesis">)</span>';
11556 }
11557
11558 if (this.implicit && (this.getIdentifier() === 'OperatorNode:multiply') && (implicit == 'hide')) {
11559 return lhs + '<span class="math-operator math-binary-operator math-implicit-binary-operator"></span>' + rhs;
11560 }
11561
11562 return lhs + '<span class="math-operator math-binary-operator math-explicit-binary-operator">' + escape(this.op) + '</span>' + rhs;
11563 }
11564 else if ((args.length > 2) && ((this.getIdentifier() === 'OperatorNode:add') || (this.getIdentifier() === 'OperatorNode:multiply'))) {
11565 var stringifiedArgs = args.map(function (arg, index) {
11566 arg = arg.toHTML(options);
11567 if (parens[index]) { //put in parenthesis?
11568 arg = '<span class="math-parenthesis math-round-parenthesis">(</span>' + arg + '<span class="math-parenthesis math-round-parenthesis">)</span>';
11569 }
11570
11571 return arg;
11572 });
11573
11574 if (this.implicit && (this.getIdentifier() === 'OperatorNode:multiply') && (implicit === 'hide')) {
11575 return stringifiedArgs.join('<span class="math-operator math-binary-operator math-implicit-binary-operator"></span>');
11576 }
11577
11578 return stringifiedArgs.join('<span class="math-operator math-binary-operator math-explicit-binary-operator">' + escape(this.op) + '</span>');
11579 } else {
11580 //fallback to formatting as a function call
11581 return '<span class="math-function">' + 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>';
11582 }
11583 };
11584
11585 /**
11586 * Get LaTeX representation
11587 * @param {Object} options
11588 * @return {string} str
11589 */
11590 OperatorNode.prototype._toTex = function (options) {
11591 var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep';
11592 var implicit = (options && options.implicit) ? options.implicit : 'hide';
11593 var args = this.args;
11594 var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, true);
11595 var op = latex.operators[this.fn];
11596 op = typeof op === 'undefined' ? this.op : op; //fall back to using this.op
11597
11598 if (args.length === 1) { //unary operators
11599 var assoc = operators.getAssociativity(this, parenthesis);
11600
11601 var operand = args[0].toTex(options);
11602 if (parens[0]) {
11603 operand = '\\left(' + operand + '\\right)';
11604 }
11605
11606 if (assoc === 'right') { //prefix operator
11607 return op + operand;
11608 }
11609 else if (assoc === 'left') { //postfix operator
11610 return operand + op;
11611 }
11612
11613 //fall back to postfix
11614 return operand + op;
11615 } else if (args.length === 2) { //binary operators
11616 var lhs = args[0]; //left hand side
11617 var lhsTex = lhs.toTex(options);
11618 if (parens[0]) {
11619 lhsTex = '\\left(' + lhsTex + '\\right)';
11620 }
11621
11622 var rhs = args[1]; //right hand side
11623 var rhsTex = rhs.toTex(options);
11624 if (parens[1]) {
11625 rhsTex = '\\left(' + rhsTex + '\\right)';
11626 }
11627
11628 //handle some exceptions (due to the way LaTeX works)
11629 var lhsIdentifier;
11630 if (parenthesis === 'keep') {
11631 lhsIdentifier = lhs.getIdentifier();
11632 }
11633 else {
11634 //Ignore ParenthesisNodes if in 'keep' mode
11635 lhsIdentifier = lhs.getContent().getIdentifier();
11636 }
11637 switch (this.getIdentifier()) {
11638 case 'OperatorNode:divide':
11639 //op contains '\\frac' at this point
11640 return op + '{' + lhsTex + '}' + '{' + rhsTex + '}';
11641 case 'OperatorNode:pow':
11642 lhsTex = '{' + lhsTex + '}';
11643 rhsTex = '{' + rhsTex + '}';
11644 switch (lhsIdentifier) {
11645 case 'ConditionalNode': //
11646 case 'OperatorNode:divide':
11647 lhsTex = '\\left(' + lhsTex + '\\right)';
11648 }
11649 case 'OperatorNode:multiply':
11650 if (this.implicit && (implicit === 'hide')) {
11651 return lhsTex + '~' + rhsTex;
11652 }
11653 }
11654 return lhsTex + op + rhsTex;
11655 } else if ((args.length > 2) && ((this.getIdentifier() === 'OperatorNode:add') || (this.getIdentifier() === 'OperatorNode:multiply'))) {
11656 var texifiedArgs = args.map(function (arg, index) {
11657 arg = arg.toTex(options);
11658 if (parens[index]) {
11659 arg = '\\left(' + arg + '\\right)';
11660 }
11661 return arg;
11662 });
11663
11664 if ((this.getIdentifier() === 'OperatorNode:multiply') && this.implicit) {
11665 return texifiedArgs.join('~');
11666 }
11667
11668 return texifiedArgs.join(op)
11669 } else {
11670 //fall back to formatting as a function call
11671 //as this is a fallback, it doesn't use
11672 //fancy function names
11673 return '\\mathrm{' + this.fn + '}\\left('
11674 + args.map(function (arg) {
11675 return arg.toTex(options);
11676 }).join(',') + '\\right)';
11677 }
11678 };
11679
11680 /**
11681 * Get identifier.
11682 * @return {string}
11683 */
11684 OperatorNode.prototype.getIdentifier = function () {
11685 return this.type + ':' + this.fn;
11686 };
11687
11688 return OperatorNode;
11689}
11690
11691exports.name = 'OperatorNode';
11692exports.path = 'expression.node';
11693exports.factory = factory;
11694
11695
11696/***/ }),
11697/* 56 */
11698/***/ (function(module, exports, __webpack_require__) {
11699
11700"use strict";
11701
11702
11703var latex = __webpack_require__(4);
11704var stringify = __webpack_require__(9).stringify;
11705var escape = __webpack_require__(9).escape;
11706var extend = __webpack_require__(5).extend;
11707var hasOwnProperty = __webpack_require__(5).hasOwnProperty;
11708var map = __webpack_require__(2).map;
11709var join = __webpack_require__(2).join;
11710var validateSafeMethod = __webpack_require__(13).validateSafeMethod;
11711var getUniqueArgumentName = __webpack_require__(109);
11712
11713function factory (type, config, load, typed, math) {
11714 var register = load(__webpack_require__(7)).register;
11715 var compile = load(__webpack_require__(7)).compile;
11716 var Node = load(__webpack_require__(15));
11717 var SymbolNode = load(__webpack_require__(36));
11718
11719 /**
11720 * @constructor FunctionNode
11721 * @extends {./Node}
11722 * invoke a list with arguments on a node
11723 * @param {./Node | string} fn Node resolving with a function on which to invoke
11724 * the arguments, typically a SymboNode or AccessorNode
11725 * @param {./Node[]} args
11726 */
11727 function FunctionNode(fn, args) {
11728 if (!(this instanceof FunctionNode)) {
11729 throw new SyntaxError('Constructor must be called with the new operator');
11730 }
11731
11732 if (typeof fn === 'string') {
11733 fn = new SymbolNode(fn);
11734 }
11735
11736 // validate input
11737 if (!type.isNode(fn)) throw new TypeError('Node expected as parameter "fn"');
11738 if (!Array.isArray(args) || !args.every(type.isNode)) {
11739 throw new TypeError('Array containing Nodes expected for parameter "args"');
11740 }
11741
11742 this.fn = fn;
11743 this.args = args || [];
11744
11745 // readonly property name
11746 Object.defineProperty(this, 'name', {
11747 get: function () {
11748 return this.fn.name || '';
11749 }.bind(this),
11750 set: function () {
11751 throw new Error('Cannot assign a new name, name is read-only');
11752 }
11753 });
11754
11755 // TODO: deprecated since v3, remove some day
11756 var deprecated = function () {
11757 throw new Error('Property `FunctionNode.object` is deprecated, use `FunctionNode.fn` instead');
11758 };
11759 Object.defineProperty(this, 'object', { get: deprecated, set: deprecated });
11760 }
11761
11762 FunctionNode.prototype = new Node();
11763
11764 FunctionNode.prototype.type = 'FunctionNode';
11765
11766 FunctionNode.prototype.isFunctionNode = true;
11767
11768 /**
11769 * Compile the node to javascript code
11770 * @param {FunctionNode} node The node to be compiled
11771 * @param {Object} defs Object which can be used to define functions
11772 * or constants globally available for the compiled
11773 * expression
11774 * @param {Object} args Object with local function arguments, the key is
11775 * the name of the argument, and the value is `true`.
11776 * The object may not be mutated, but must be
11777 * extended instead.
11778 * @return {string} js
11779 * @private
11780 */
11781 function compileFunctionNode(node, defs, args) {
11782 if (!(node instanceof FunctionNode)) {
11783 throw new TypeError('No valid FunctionNode')
11784 }
11785
11786 // compile fn and arguments
11787 var jsFn = compile(node.fn, defs, args);
11788 var jsArgs = map(node.args, function (arg) {
11789 return compile(arg, defs, args);
11790 });
11791 var jsScope = compileScope(defs, args);
11792 var argsName;
11793
11794 if (type.isSymbolNode(node.fn)) {
11795 // we can statically determine whether the function has an rawArgs property
11796 var name = node.fn.name;
11797 var fn = hasOwnProperty(defs.math, name) ? defs.math[name] : undefined;
11798 var isRaw = (typeof fn === 'function') && (fn.rawArgs == true);
11799
11800 if (isRaw) {
11801 // pass unevaluated parameters (nodes) to the function
11802 argsName = getUniqueArgumentName(defs);
11803 defs[argsName] = node.args;
11804
11805 return jsFn + '(' + argsName + ', math, ' + jsScope + ')'; // "raw" evaluation
11806 }
11807 else {
11808 return jsFn + '(' + join(jsArgs, ', ') + ')'; // "regular" evaluation
11809 }
11810 }
11811 else if (type.isAccessorNode(node.fn) &&
11812 type.isIndexNode(node.fn.index) && node.fn.index.isObjectProperty()) {
11813 // execute the function with the right context: the object of the AccessorNode
11814 argsName = getUniqueArgumentName(defs);
11815 defs[argsName] = node.args;
11816 defs.validateSafeMethod = validateSafeMethod
11817
11818 var jsObject = compile(node.fn.object, defs, args);
11819 var jsProp = stringify(node.fn.index.getObjectProperty());
11820
11821 return '(function () {' +
11822 'var object = ' + jsObject + ';' +
11823 'validateSafeMethod(object, ' + jsProp + ');' +
11824 'return (object[' + jsProp + '] && object[' + jsProp + '].rawArgs) ' +
11825 ' ? object[' + jsProp + '](' + argsName + ', math, ' + jsScope + ')' + // "raw" evaluation
11826 ' : object[' + jsProp + '](' + join(jsArgs, ', ') + ')' + // "regular" evaluation
11827 '})()';
11828 }
11829 else { // node.fn.isAccessorNode && !node.fn.index.isObjectProperty()
11830 // we have to dynamically determine whether the function has a rawArgs property
11831 argsName = getUniqueArgumentName(defs);
11832 defs[argsName] = node.args;
11833
11834 return '(function () {' +
11835 'var fn = ' + jsFn + ';' +
11836 'return (fn && fn.rawArgs) ' +
11837 ' ? fn(' + argsName + ', math, ' + jsScope + ')' + // "raw" evaluation
11838 ' : fn(' + join(jsArgs, ', ') + ')' + // "regular" evaluation
11839 '})()';
11840 }
11841 }
11842
11843 // register the compile function
11844 register(FunctionNode.prototype.type, compileFunctionNode);
11845
11846 /**
11847 * Merge function arguments into scope before passing to the actual function.
11848 * This is needed when the function has `rawArgs=true`. In that case we have
11849 * to pass the `scope` as third argument, including any variables of
11850 * enclosing functions.
11851 * @param {Object} defs Object which can be used to define functions
11852 * or constants globally available for the compiled
11853 * expression
11854 * @param {Object} args Object with local function arguments, the key is
11855 * the name of the argument, and the value is `true`.
11856 * The object may not be mutated, but must be
11857 * extended instead.
11858 * @return {string} js
11859 * @private
11860 */
11861 function compileScope (defs, args) {
11862 var names = Object.keys(args)
11863 // .map(function (arg) {
11864 // return args[arg];
11865 // });
11866 if (names.length === 0) {
11867 return 'scope';
11868 }
11869 else {
11870 // merge arguments into scope
11871 defs.extend = extend;
11872
11873 var jsArgs = map(names, function (name) {
11874 return stringify(name) + ': ' + args[name];
11875 });
11876
11877 return 'extend(extend({}, scope), {' + join(jsArgs, ', ') + '})';
11878 }
11879 }
11880
11881 /**
11882 * Execute a callback for each of the child nodes of this node
11883 * @param {function(child: Node, path: string, parent: Node)} callback
11884 */
11885 FunctionNode.prototype.forEach = function (callback) {
11886 for (var i = 0; i < this.args.length; i++) {
11887 callback(this.args[i], 'args[' + i + ']', this);
11888 }
11889 };
11890
11891 /**
11892 * Create a new FunctionNode having it's childs be the results of calling
11893 * the provided callback function for each of the childs of the original node.
11894 * @param {function(child: Node, path: string, parent: Node): Node} callback
11895 * @returns {FunctionNode} Returns a transformed copy of the node
11896 */
11897 FunctionNode.prototype.map = function (callback) {
11898 var fn = this.fn.map(callback);
11899 var args = [];
11900 for (var i = 0; i < this.args.length; i++) {
11901 args[i] = this._ifNode(callback(this.args[i], 'args[' + i + ']', this));
11902 }
11903 return new FunctionNode(fn, args);
11904 };
11905
11906 /**
11907 * Create a clone of this node, a shallow copy
11908 * @return {FunctionNode}
11909 */
11910 FunctionNode.prototype.clone = function () {
11911 return new FunctionNode(this.fn, this.args.slice(0));
11912 };
11913
11914 //backup Node's toString function
11915 //@private
11916 var nodeToString = FunctionNode.prototype.toString;
11917
11918 /**
11919 * Get string representation. (wrapper function)
11920 * This overrides parts of Node's toString function.
11921 * If callback is an object containing callbacks, it
11922 * calls the correct callback for the current node,
11923 * otherwise it falls back to calling Node's toString
11924 * function.
11925 *
11926 * @param {Object} options
11927 * @return {string} str
11928 * @override
11929 */
11930 FunctionNode.prototype.toString = function (options) {
11931 var customString;
11932 var name = this.fn.toString(options);
11933 if (options && (typeof options.handler === 'object') && hasOwnProperty(options.handler, name)) {
11934 //callback is a map of callback functions
11935 customString = options.handler[name](this, options);
11936 }
11937
11938 if (typeof customString !== 'undefined') {
11939 return customString;
11940 }
11941
11942 //fall back to Node's toString
11943 return nodeToString.call(this, options);
11944 };
11945
11946 /**
11947 * Get string representation
11948 * @param {Object} options
11949 * @return {string} str
11950 */
11951 FunctionNode.prototype._toString = function (options) {
11952 var args = this.args.map(function (arg) {
11953 return arg.toString(options);
11954 });
11955
11956 var fn = type.isFunctionAssignmentNode(this.fn)
11957 ? ('(' + this.fn.toString(options) + ')')
11958 : this.fn.toString(options)
11959
11960 // format the arguments like "add(2, 4.2)"
11961 return fn + '(' + args.join(', ') + ')';
11962 };
11963
11964 /**
11965 * Get HTML representation
11966 * @param {Object} options
11967 * @return {string} str
11968 */
11969 FunctionNode.prototype.toHTML = function (options) {
11970 var args = this.args.map(function (arg) {
11971 return arg.toHTML(options);
11972 });
11973
11974 // format the arguments like "add(2, 4.2)"
11975 return '<span class="math-function">' + 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>';
11976 };
11977
11978 /*
11979 * Expand a LaTeX template
11980 *
11981 * @param {string} template
11982 * @param {Node} node
11983 * @param {Object} options
11984 * @private
11985 **/
11986 function expandTemplate(template, node, options) {
11987 var latex = '';
11988
11989 // Match everything of the form ${identifier} or ${identifier[2]} or $$
11990 // while submatching identifier and 2 (in the second case)
11991 var regex = new RegExp('\\$(?:\\{([a-z_][a-z_0-9]*)(?:\\[([0-9]+)\\])?\\}|\\$)', 'ig');
11992
11993 var inputPos = 0; //position in the input string
11994 var match;
11995 while ((match = regex.exec(template)) !== null) { //go through all matches
11996 // add everything in front of the match to the LaTeX string
11997 latex += template.substring(inputPos, match.index);
11998 inputPos = match.index;
11999
12000 if (match[0] === '$$') { // escaped dollar sign
12001 latex += '$';
12002 inputPos++;
12003 }
12004 else { // template parameter
12005 inputPos += match[0].length;
12006 var property = node[match[1]];
12007 if (!property) {
12008 throw new ReferenceError('Template: Property ' + match[1] + ' does not exist.');
12009 }
12010 if (match[2] === undefined) { //no square brackets
12011 switch (typeof property) {
12012 case 'string':
12013 latex += property;
12014 break;
12015 case 'object':
12016 if (type.isNode(property)) {
12017 latex += property.toTex(options);
12018 }
12019 else if (Array.isArray(property)) {
12020 //make array of Nodes into comma separated list
12021 latex += property.map(function (arg, index) {
12022 if (type.isNode(arg)) {
12023 return arg.toTex(options);
12024 }
12025 throw new TypeError('Template: ' + match[1] + '[' + index + '] is not a Node.');
12026 }).join(',');
12027 }
12028 else {
12029 throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes');
12030 }
12031 break;
12032 default:
12033 throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes');
12034 }
12035 }
12036 else { //with square brackets
12037 if (type.isNode(property[match[2]] && property[match[2]])) {
12038 latex += property[match[2]].toTex(options);
12039 }
12040 else {
12041 throw new TypeError('Template: ' + match[1] + '[' + match[2] + '] is not a Node.');
12042 }
12043 }
12044 }
12045 }
12046 latex += template.slice(inputPos); //append rest of the template
12047
12048 return latex;
12049 }
12050
12051 //backup Node's toTex function
12052 //@private
12053 var nodeToTex = FunctionNode.prototype.toTex;
12054
12055 /**
12056 * Get LaTeX representation. (wrapper function)
12057 * This overrides parts of Node's toTex function.
12058 * If callback is an object containing callbacks, it
12059 * calls the correct callback for the current node,
12060 * otherwise it falls back to calling Node's toTex
12061 * function.
12062 *
12063 * @param {Object} options
12064 * @return {string}
12065 */
12066 FunctionNode.prototype.toTex = function (options) {
12067 var customTex;
12068 if (options && (typeof options.handler === 'object') && hasOwnProperty(options.handler, this.name)) {
12069 //callback is a map of callback functions
12070 customTex = options.handler[this.name](this, options);
12071 }
12072
12073 if (typeof customTex !== 'undefined') {
12074 return customTex;
12075 }
12076
12077 //fall back to Node's toTex
12078 return nodeToTex.call(this, options);
12079 };
12080
12081 /**
12082 * Get LaTeX representation
12083 * @param {Object} options
12084 * @return {string} str
12085 */
12086 FunctionNode.prototype._toTex = function (options) {
12087 var args = this.args.map(function (arg) { //get LaTeX of the arguments
12088 return arg.toTex(options);
12089 });
12090
12091 var latexConverter;
12092
12093 if (math[this.name] && ((typeof math[this.name].toTex === 'function') || (typeof math[this.name].toTex === 'object') || (typeof math[this.name].toTex === 'string'))) {
12094 //.toTex is a callback function
12095 latexConverter = math[this.name].toTex;
12096 }
12097
12098 var customToTex;
12099 switch (typeof latexConverter) {
12100 case 'function': //a callback function
12101 customToTex = latexConverter(this, options);
12102 break;
12103 case 'string': //a template string
12104 customToTex = expandTemplate(latexConverter, this, options);
12105 break;
12106 case 'object': //an object with different "converters" for different numbers of arguments
12107 switch (typeof latexConverter[args.length]) {
12108 case 'function':
12109 customToTex = latexConverter[args.length](this, options);
12110 break;
12111 case 'string':
12112 customToTex = expandTemplate(latexConverter[args.length], this, options);
12113 break;
12114 }
12115 }
12116
12117 if (typeof customToTex !== 'undefined') {
12118 return customToTex;
12119 }
12120
12121 return expandTemplate(latex.defaultTemplate, this, options);
12122 };
12123
12124 /**
12125 * Get identifier.
12126 * @return {string}
12127 */
12128 FunctionNode.prototype.getIdentifier = function () {
12129 return this.type + ':' + this.name;
12130 };
12131
12132 return FunctionNode;
12133}
12134
12135exports.name = 'FunctionNode';
12136exports.path = 'expression.node';
12137exports.math = true; // request access to the math namespace as 5th argument of the factory function
12138exports.factory = factory;
12139
12140
12141/***/ }),
12142/* 57 */
12143/***/ (function(module, exports, __webpack_require__) {
12144
12145"use strict";
12146
12147
12148var deepMap = __webpack_require__(1);
12149var number = __webpack_require__(3);
12150
12151function factory (type, config, load, typed) {
12152 /**
12153 * Test whether a value is positive: larger than zero.
12154 * The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`.
12155 *
12156 * The function is evaluated element-wise in case of Array or Matrix input.
12157 *
12158 * Syntax:
12159 *
12160 * math.isPositive(x)
12161 *
12162 * Examples:
12163 *
12164 * math.isPositive(3); // returns true
12165 * math.isPositive(-2); // returns false
12166 * math.isPositive(0); // returns false
12167 * math.isPositive(-0); // returns false
12168 * math.isPositive(0.5); // returns true
12169 * math.isPositive(math.bignumber(2)); // returns true
12170 * math.isPositive(math.fraction(-2, 5)); // returns false
12171 * math.isPositive(math.fraction(1,3)); // returns false
12172 * math.isPositive('2'); // returns true
12173 * math.isPositive([2, 0, -3]'); // returns [true, false, false]
12174 *
12175 * See also:
12176 *
12177 * isNumeric, isZero, isNegative, isInteger
12178 *
12179 * @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested
12180 * @return {boolean} Returns true when `x` is larger than zero.
12181 * Throws an error in case of an unknown data type.
12182 */
12183 var isPositive = typed('isPositive', {
12184 'number': function (x) {
12185 return x > 0;
12186 },
12187
12188 'BigNumber': function (x) {
12189 return !x.isNeg() && !x.isZero() && !x.isNaN();
12190 },
12191
12192 'Fraction': function (x) {
12193 return x.s > 0 && x.n > 0;
12194 },
12195
12196 'Unit': function (x) {
12197 return isPositive(x.value);
12198 },
12199
12200 'Array | Matrix': function (x) {
12201 return deepMap(x, isPositive);
12202 }
12203 });
12204
12205 return isPositive;
12206}
12207
12208exports.name = 'isPositive';
12209exports.factory = factory;
12210
12211
12212/***/ }),
12213/* 58 */
12214/***/ (function(module, exports, __webpack_require__) {
12215
12216"use strict";
12217
12218
12219var deepMap = __webpack_require__(1);
12220var number = __webpack_require__(3);
12221
12222function factory (type, config, load, typed) {
12223 /**
12224 * Test whether a value is negative: smaller than zero.
12225 * The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`.
12226 *
12227 * The function is evaluated element-wise in case of Array or Matrix input.
12228 *
12229 * Syntax:
12230 *
12231 * math.isNegative(x)
12232 *
12233 * Examples:
12234 *
12235 * math.isNegative(3); // returns false
12236 * math.isNegative(-2); // returns true
12237 * math.isNegative(0); // returns false
12238 * math.isNegative(-0); // returns false
12239 * math.isNegative(math.bignumber(2)); // returns false
12240 * math.isNegative(math.fraction(-2, 5)); // returns true
12241 * math.isNegative('-2'); // returns true
12242 * math.isNegative([2, 0, -3]'); // returns [false, false, true]
12243 *
12244 * See also:
12245 *
12246 * isNumeric, isPositive, isZero, isInteger
12247 *
12248 * @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested
12249 * @return {boolean} Returns true when `x` is larger than zero.
12250 * Throws an error in case of an unknown data type.
12251 */
12252 var isNegative = typed('isNegative', {
12253 'number': function (x) {
12254 return x < 0;
12255 },
12256
12257 'BigNumber': function (x) {
12258 return x.isNeg() && !x.isZero() && !x.isNaN();
12259 },
12260
12261 'Fraction': function (x) {
12262 return x.s < 0; // It's enough to decide on the sign
12263 },
12264
12265 'Unit': function (x) {
12266 return isNegative(x.value);
12267 },
12268
12269 'Array | Matrix': function (x) {
12270 return deepMap(x, isNegative);
12271 }
12272 });
12273
12274 return isNegative;
12275}
12276
12277exports.name = 'isNegative';
12278exports.factory = factory;
12279
12280
12281/***/ }),
12282/* 59 */
12283/***/ (function(module, exports, __webpack_require__) {
12284
12285"use strict";
12286
12287
12288/**
12289 * Test whether a value is a Matrix
12290 * @param {*} x
12291 * @returns {boolean} returns true with input is a Matrix
12292 * (like a DenseMatrix or SparseMatrix)
12293 */
12294module.exports = function isMatrix (x) {
12295 return x && x.constructor.prototype.isMatrix || false;
12296};
12297
12298
12299/***/ }),
12300/* 60 */
12301/***/ (function(module, exports, __webpack_require__) {
12302
12303"use strict";
12304
12305
12306/**
12307 * Determine the type of a variable
12308 *
12309 * type(x)
12310 *
12311 * The following types are recognized:
12312 *
12313 * 'undefined'
12314 * 'null'
12315 * 'boolean'
12316 * 'number'
12317 * 'string'
12318 * 'Array'
12319 * 'Function'
12320 * 'Date'
12321 * 'RegExp'
12322 * 'Object'
12323 *
12324 * @param {*} x
12325 * @return {string} Returns the name of the type. Primitive types are lower case,
12326 * non-primitive types are upper-camel-case.
12327 * For example 'number', 'string', 'Array', 'Date'.
12328 */
12329exports.type = function(x) {
12330 var type = typeof x;
12331
12332 if (type === 'object') {
12333 if (x === null) return 'null';
12334 if (Array.isArray(x)) return 'Array';
12335 if (x instanceof Date) return 'Date';
12336 if (x instanceof RegExp) return 'RegExp';
12337 if (x instanceof Boolean) return 'boolean';
12338 if (x instanceof Number) return 'number';
12339 if (x instanceof String) return 'string';
12340
12341 return 'Object';
12342 }
12343
12344 if (type === 'function') return 'Function';
12345
12346 return type;
12347};
12348
12349
12350/***/ }),
12351/* 61 */
12352/***/ (function(module, exports, __webpack_require__) {
12353
12354"use strict";
12355
12356
12357var DimensionError = __webpack_require__(11);
12358
12359function factory (type, config, load, typed) {
12360
12361 var equalScalar = load(__webpack_require__(10));
12362
12363 var SparseMatrix = type.SparseMatrix;
12364
12365 /**
12366 * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij).
12367 * Callback function invoked MAX(NNZA, NNZB) times
12368 *
12369 *
12370 * ┌ f(Aij, Bij) ; A(i,j) !== 0 || B(i,j) !== 0
12371 * C(i,j) = ┤
12372 * └ 0 ; otherwise
12373 *
12374 *
12375 * @param {Matrix} a The SparseMatrix instance (A)
12376 * @param {Matrix} b The SparseMatrix instance (B)
12377 * @param {Function} callback The f(Aij,Bij) operation to invoke
12378 *
12379 * @return {Matrix} SparseMatrix (C)
12380 *
12381 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
12382 */
12383 var algorithm05 = function (a, b, callback) {
12384 // sparse matrix arrays
12385 var avalues = a._values;
12386 var aindex = a._index;
12387 var aptr = a._ptr;
12388 var asize = a._size;
12389 var adt = a._datatype;
12390 // sparse matrix arrays
12391 var bvalues = b._values;
12392 var bindex = b._index;
12393 var bptr = b._ptr;
12394 var bsize = b._size;
12395 var bdt = b._datatype;
12396
12397 // validate dimensions
12398 if (asize.length !== bsize.length)
12399 throw new DimensionError(asize.length, bsize.length);
12400
12401 // check rows & columns
12402 if (asize[0] !== bsize[0] || asize[1] !== bsize[1])
12403 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
12404
12405 // rows & columns
12406 var rows = asize[0];
12407 var columns = asize[1];
12408
12409 // datatype
12410 var dt;
12411 // equal signature to use
12412 var eq = equalScalar;
12413 // zero value
12414 var zero = 0;
12415 // callback signature to use
12416 var cf = callback;
12417
12418 // process data types
12419 if (typeof adt === 'string' && adt === bdt) {
12420 // datatype
12421 dt = adt;
12422 // find signature that matches (dt, dt)
12423 eq = typed.find(equalScalar, [dt, dt]);
12424 // convert 0 to the same datatype
12425 zero = typed.convert(0, dt);
12426 // callback
12427 cf = typed.find(callback, [dt, dt]);
12428 }
12429
12430 // result arrays
12431 var cvalues = avalues && bvalues ? [] : undefined;
12432 var cindex = [];
12433 var cptr = [];
12434 // matrix
12435 var c = new SparseMatrix({
12436 values: cvalues,
12437 index: cindex,
12438 ptr: cptr,
12439 size: [rows, columns],
12440 datatype: dt
12441 });
12442
12443 // workspaces
12444 var xa = cvalues ? [] : undefined;
12445 var xb = cvalues ? [] : undefined;
12446 // marks indicating we have a value in x for a given column
12447 var wa = [];
12448 var wb = [];
12449
12450 // vars
12451 var i, j, k, k1;
12452
12453 // loop columns
12454 for (j = 0; j < columns; j++) {
12455 // update cptr
12456 cptr[j] = cindex.length;
12457 // columns mark
12458 var mark = j + 1;
12459 // loop values A(:,j)
12460 for (k = aptr[j], k1 = aptr[j + 1]; k < k1; k++) {
12461 // row
12462 i = aindex[k];
12463 // push index
12464 cindex.push(i);
12465 // update workspace
12466 wa[i] = mark;
12467 // check we need to process values
12468 if (xa)
12469 xa[i] = avalues[k];
12470 }
12471 // loop values B(:,j)
12472 for (k = bptr[j], k1 = bptr[j + 1]; k < k1; k++) {
12473 // row
12474 i = bindex[k];
12475 // check row existed in A
12476 if (wa[i] !== mark) {
12477 // push index
12478 cindex.push(i);
12479 }
12480 // update workspace
12481 wb[i] = mark;
12482 // check we need to process values
12483 if (xb)
12484 xb[i] = bvalues[k];
12485 }
12486 // check we need to process values (non pattern matrix)
12487 if (cvalues) {
12488 // initialize first index in j
12489 k = cptr[j];
12490 // loop index in j
12491 while (k < cindex.length) {
12492 // row
12493 i = cindex[k];
12494 // marks
12495 var wai = wa[i];
12496 var wbi = wb[i];
12497 // check Aij or Bij are nonzero
12498 if (wai === mark || wbi === mark) {
12499 // matrix values @ i,j
12500 var va = wai === mark ? xa[i] : zero;
12501 var vb = wbi === mark ? xb[i] : zero;
12502 // Cij
12503 var vc = cf(va, vb);
12504 // check for zero
12505 if (!eq(vc, zero)) {
12506 // push value
12507 cvalues.push(vc);
12508 // increment pointer
12509 k++;
12510 }
12511 else {
12512 // remove value @ i, do not increment pointer
12513 cindex.splice(k, 1);
12514 }
12515 }
12516 }
12517 }
12518 }
12519 // update cptr
12520 cptr[columns] = cindex.length;
12521
12522 // return sparse matrix
12523 return c;
12524 };
12525
12526 return algorithm05;
12527}
12528
12529exports.name = 'algorithm05';
12530exports.factory = factory;
12531
12532
12533/***/ }),
12534/* 62 */
12535/***/ (function(module, exports, __webpack_require__) {
12536
12537"use strict";
12538
12539
12540var array = __webpack_require__(2);
12541var isInteger = __webpack_require__(3).isInteger;
12542
12543function factory (type, config, load, typed) {
12544
12545 var matrix = load(__webpack_require__(0));
12546
12547 /**
12548 * Create a 2-dimensional identity matrix with size m x n or n x n.
12549 * The matrix has ones on the diagonal and zeros elsewhere.
12550 *
12551 * Syntax:
12552 *
12553 * math.eye(n)
12554 * math.eye(n, format)
12555 * math.eye(m, n)
12556 * math.eye(m, n, format)
12557 * math.eye([m, n])
12558 * math.eye([m, n], format)
12559 *
12560 * Examples:
12561 *
12562 * math.eye(3); // returns [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
12563 * math.eye(3, 2); // returns [[1, 0], [0, 1], [0, 0]]
12564 *
12565 * var A = [[1, 2, 3], [4, 5, 6]];
12566 * math.eye(math.size(A)); // returns [[1, 0, 0], [0, 1, 0]]
12567 *
12568 * See also:
12569 *
12570 * diag, ones, zeros, size, range
12571 *
12572 * @param {...number | Matrix | Array} size The size for the matrix
12573 * @param {string} [format] The Matrix storage format
12574 *
12575 * @return {Matrix | Array | number} A matrix with ones on the diagonal.
12576 */
12577 var eye = typed('eye', {
12578 '': function () {
12579 return (config.matrix === 'Matrix') ? matrix([]) : [];
12580 },
12581
12582 'string': function (format) {
12583 return matrix(format);
12584 },
12585
12586 'number | BigNumber': function (rows) {
12587 return _eye(rows, rows, config.matrix === 'Matrix' ? 'default' : undefined);
12588 },
12589
12590 'number | BigNumber, string': function (rows, format) {
12591 return _eye(rows, rows, format);
12592 },
12593
12594 'number | BigNumber, number | BigNumber': function (rows, cols) {
12595 return _eye(rows, cols, config.matrix === 'Matrix' ? 'default' : undefined);
12596 },
12597
12598 'number | BigNumber, number | BigNumber, string': function (rows, cols, format) {
12599 return _eye(rows, cols, format);
12600 },
12601
12602 'Array': function (size) {
12603 return _eyeVector(size);
12604 },
12605
12606 'Array, string': function (size, format) {
12607 return _eyeVector(size, format);
12608 },
12609
12610 'Matrix': function (size) {
12611 return _eyeVector(size.valueOf(), size.storage());
12612 },
12613
12614 'Matrix, string': function (size, format) {
12615 return _eyeVector(size.valueOf(), format);
12616 }
12617 });
12618
12619 eye.toTex = undefined; // use default template
12620
12621 return eye;
12622
12623 function _eyeVector (size, format) {
12624 switch (size.length) {
12625 case 0: return format ? matrix(format) : [];
12626 case 1: return _eye(size[0], size[0], format);
12627 case 2: return _eye(size[0], size[1], format);
12628 default: throw new Error('Vector containing two values expected');
12629 }
12630 }
12631
12632 /**
12633 * Create an identity matrix
12634 * @param {number | BigNumber} rows
12635 * @param {number | BigNumber} cols
12636 * @param {string} [format]
12637 * @returns {Matrix}
12638 * @private
12639 */
12640 function _eye (rows, cols, format) {
12641 // BigNumber constructor with the right precision
12642 var Big = (type.isBigNumber(rows) || type.isBigNumber(cols))
12643 ? type.BigNumber
12644 : null;
12645
12646 if (type.isBigNumber(rows)) rows = rows.toNumber();
12647 if (type.isBigNumber(cols)) cols = cols.toNumber();
12648
12649 if (!isInteger(rows) || rows < 1) {
12650 throw new Error('Parameters in function eye must be positive integers');
12651 }
12652 if (!isInteger(cols) || cols < 1) {
12653 throw new Error('Parameters in function eye must be positive integers');
12654 }
12655
12656 var one = Big ? new type.BigNumber(1) : 1;
12657 var defaultValue = Big ? new Big(0) : 0;
12658 var size = [rows, cols];
12659
12660 // check we need to return a matrix
12661 if (format) {
12662 // get matrix storage constructor
12663 var F = type.Matrix.storage(format);
12664 // create diagonal matrix (use optimized implementation for storage format)
12665 return F.diagonal(size, one, 0, defaultValue);
12666 }
12667
12668 // create and resize array
12669 var res = array.resize([], size, defaultValue);
12670 // fill in ones on the diagonal
12671 var minimum = rows < cols ? rows : cols;
12672 // fill diagonal
12673 for (var d = 0; d < minimum; d++) {
12674 res[d][d] = one;
12675 }
12676 return res;
12677 }
12678}
12679
12680exports.name = 'eye';
12681exports.factory = factory;
12682
12683
12684/***/ }),
12685/* 63 */
12686/***/ (function(module, exports, __webpack_require__) {
12687
12688"use strict";
12689
12690
12691function factory (type, config, load, typed) {
12692 var register = load(__webpack_require__(7)).register;
12693 var compile = load(__webpack_require__(7)).compile;
12694 var Node = load(__webpack_require__(15));
12695
12696 /**
12697 * @constructor ParenthesisNode
12698 * @extends {Node}
12699 * A parenthesis node describes manual parenthesis from the user input
12700 * @param {Node} content
12701 * @extends {Node}
12702 */
12703 function ParenthesisNode(content) {
12704 if (!(this instanceof ParenthesisNode)) {
12705 throw new SyntaxError('Constructor must be called with the new operator');
12706 }
12707
12708 // validate input
12709 if (!type.isNode(content)) {
12710 throw new TypeError('Node expected for parameter "content"');
12711 }
12712
12713 this.content = content;
12714 }
12715
12716 ParenthesisNode.prototype = new Node();
12717
12718 ParenthesisNode.prototype.type = 'ParenthesisNode';
12719
12720 ParenthesisNode.prototype.isParenthesisNode = true;
12721
12722 /**
12723 * Compile the node to javascript code
12724 * @param {ParenthesisNode} node The node to be compiled
12725 * @param {Object} defs Object which can be used to define functions
12726 * or constants globally available for the compiled
12727 * expression
12728 * @param {Object} args Object with local function arguments, the key is
12729 * the name of the argument, and the value is `true`.
12730 * The object may not be mutated, but must be
12731 * extended instead.
12732 * @return {string} js
12733 * @private
12734 */
12735 function compileParenthesisNode(node, defs, args) {
12736 if (!(node instanceof ParenthesisNode)) {
12737 throw new TypeError('No valid ParenthesisNode')
12738 }
12739
12740 return compile(node.content, defs, args);
12741 }
12742
12743 // register the compile function
12744 register(ParenthesisNode.prototype.type, compileParenthesisNode);
12745
12746 /**
12747 * Get the content of the current Node.
12748 * @return {Node} content
12749 * @override
12750 **/
12751 ParenthesisNode.prototype.getContent = function () {
12752 return this.content.getContent();
12753 };
12754
12755 /**
12756 * Execute a callback for each of the child nodes of this node
12757 * @param {function(child: Node, path: string, parent: Node)} callback
12758 */
12759 ParenthesisNode.prototype.forEach = function (callback) {
12760 callback(this.content, 'content', this);
12761 };
12762
12763 /**
12764 * Create a new ParenthesisNode having it's childs be the results of calling
12765 * the provided callback function for each of the childs of the original node.
12766 * @param {function(child: Node, path: string, parent: Node) : Node} callback
12767 * @returns {ParenthesisNode} Returns a clone of the node
12768 */
12769 ParenthesisNode.prototype.map = function (callback) {
12770 var content = callback(this.content, 'content', this);
12771 return new ParenthesisNode(content);
12772 };
12773
12774 /**
12775 * Create a clone of this node, a shallow copy
12776 * @return {ParenthesisNode}
12777 */
12778 ParenthesisNode.prototype.clone = function() {
12779 return new ParenthesisNode(this.content);
12780 };
12781
12782 /**
12783 * Get string representation
12784 * @param {Object} options
12785 * @return {string} str
12786 * @override
12787 */
12788 ParenthesisNode.prototype._toString = function(options) {
12789 if ((!options) || (options && !options.parenthesis) || (options && options.parenthesis === 'keep')) {
12790 return '(' + this.content.toString(options) + ')';
12791 }
12792 return this.content.toString(options);
12793 };
12794
12795 /**
12796 * Get HTML representation
12797 * @param {Object} options
12798 * @return {string} str
12799 * @override
12800 */
12801 ParenthesisNode.prototype.toHTML = function(options) {
12802 if ((!options) || (options && !options.parenthesis) || (options && options.parenthesis === 'keep')) {
12803 return '<span class="math-parenthesis math-round-parenthesis">(</span>' + this.content.toHTML(options) + '<span class="math-parenthesis math-round-parenthesis">)</span>';
12804 }
12805 return this.content.toHTML(options);
12806 };
12807
12808 /**
12809 * Get LaTeX representation
12810 * @param {Object} options
12811 * @return {string} str
12812 * @override
12813 */
12814 ParenthesisNode.prototype._toTex = function(options) {
12815 if ((!options) || (options && !options.parenthesis) || (options && options.parenthesis === 'keep')) {
12816 return '\\left(' + this.content.toTex(options) + '\\right)';
12817 }
12818 return this.content.toTex(options);
12819 };
12820
12821 return ParenthesisNode;
12822}
12823
12824exports.name = 'ParenthesisNode';
12825exports.path = 'expression.node';
12826exports.factory = factory;
12827
12828
12829/***/ }),
12830/* 64 */
12831/***/ (function(module, exports, __webpack_require__) {
12832
12833"use strict";
12834
12835
12836var clone = __webpack_require__(5).clone;
12837var isInteger = __webpack_require__(3).isInteger;
12838var array = __webpack_require__(2);
12839var IndexError = __webpack_require__(53);
12840var DimensionError = __webpack_require__(11);
12841
12842function factory (type, config, load, typed) {
12843 var matrix = load(__webpack_require__(0));
12844
12845 /**
12846 * Concatenate two or more matrices.
12847 *
12848 * Syntax:
12849 *
12850 * math.concat(A, B, C, ...)
12851 * math.concat(A, B, C, ..., dim)
12852 *
12853 * Where:
12854 *
12855 * - `dim: number` is a zero-based dimension over which to concatenate the matrices.
12856 * By default the last dimension of the matrices.
12857 *
12858 * Examples:
12859 *
12860 * var A = [[1, 2], [5, 6]];
12861 * var B = [[3, 4], [7, 8]];
12862 *
12863 * math.concat(A, B); // returns [[1, 2, 3, 4], [5, 6, 7, 8]]
12864 * math.concat(A, B, 0); // returns [[1, 2], [5, 6], [3, 4], [7, 8]]
12865 * math.concat('hello', ' ', 'world'); // returns 'hello world'
12866 *
12867 * See also:
12868 *
12869 * size, squeeze, subset, transpose
12870 *
12871 * @param {... Array | Matrix} args Two or more matrices
12872 * @return {Array | Matrix} Concatenated matrix
12873 */
12874 var concat = typed('concat', {
12875 // TODO: change signature to '...Array | Matrix, dim?' when supported
12876 '...Array | Matrix | number | BigNumber': function (args) {
12877 var i;
12878 var len = args.length;
12879 var dim = -1; // zero-based dimension
12880 var prevDim;
12881 var asMatrix = false;
12882 var matrices = []; // contains multi dimensional arrays
12883
12884 for (i = 0; i < len; i++) {
12885 var arg = args[i];
12886
12887 // test whether we need to return a Matrix (if not we return an Array)
12888 if (type.isMatrix(arg)) {
12889 asMatrix = true;
12890 }
12891
12892 if (type.isNumber(arg) || type.isBigNumber(arg)) {
12893 if (i !== len - 1) {
12894 throw new Error('Dimension must be specified as last argument');
12895 }
12896
12897 // last argument contains the dimension on which to concatenate
12898 prevDim = dim;
12899 dim = arg.valueOf(); // change BigNumber to number
12900
12901 if (!isInteger(dim)) {
12902 throw new TypeError('Integer number expected for dimension');
12903 }
12904
12905 if (dim < 0 || (i > 0 && dim > prevDim)) {
12906 // TODO: would be more clear when throwing a DimensionError here
12907 throw new IndexError(dim, prevDim + 1);
12908 }
12909 }
12910 else {
12911 // this is a matrix or array
12912 var m = clone(arg).valueOf();
12913 var size = array.size(m);
12914 matrices[i] = m;
12915 prevDim = dim;
12916 dim = size.length - 1;
12917
12918 // verify whether each of the matrices has the same number of dimensions
12919 if (i > 0 && dim != prevDim) {
12920 throw new DimensionError(prevDim + 1, dim + 1);
12921 }
12922 }
12923 }
12924
12925 if (matrices.length == 0) {
12926 throw new SyntaxError('At least one matrix expected');
12927 }
12928
12929 var res = matrices.shift();
12930 while (matrices.length) {
12931 res = _concat(res, matrices.shift(), dim, 0);
12932 }
12933
12934 return asMatrix ? matrix(res) : res;
12935 },
12936
12937 '...string': function (args) {
12938 return args.join('');
12939 }
12940 });
12941
12942 concat.toTex = undefined; // use default template
12943
12944 return concat;
12945}
12946
12947/**
12948 * Recursively concatenate two matrices.
12949 * The contents of the matrices is not cloned.
12950 * @param {Array} a Multi dimensional array
12951 * @param {Array} b Multi dimensional array
12952 * @param {number} concatDim The dimension on which to concatenate (zero-based)
12953 * @param {number} dim The current dim (zero-based)
12954 * @return {Array} c The concatenated matrix
12955 * @private
12956 */
12957function _concat(a, b, concatDim, dim) {
12958 if (dim < concatDim) {
12959 // recurse into next dimension
12960 if (a.length != b.length) {
12961 throw new DimensionError(a.length, b.length);
12962 }
12963
12964 var c = [];
12965 for (var i = 0; i < a.length; i++) {
12966 c[i] = _concat(a[i], b[i], concatDim, dim + 1);
12967 }
12968 return c;
12969 }
12970 else {
12971 // concatenate this dimension
12972 return a.concat(b);
12973 }
12974}
12975
12976exports.name = 'concat';
12977exports.factory = factory;
12978
12979
12980/***/ }),
12981/* 65 */
12982/***/ (function(module, exports, __webpack_require__) {
12983
12984"use strict";
12985
12986
12987var arraySize = __webpack_require__(2).size;
12988var isMatrix = __webpack_require__(59);
12989var IndexError = __webpack_require__(53);
12990
12991/**
12992 * Reduce a given matrix or array to a new matrix or
12993 * array with one less dimension, applying the given
12994 * callback in the selected dimension.
12995 * @param {Array | Matrix} mat
12996 * @param {number} dim
12997 * @param {Function} callback
12998 * @return {Array | Matrix} res
12999 */
13000module.exports = function(mat, dim, callback) {
13001 var size = Array.isArray(mat) ? arraySize(mat) : mat.size();
13002 if (dim < 0 || (dim >= size.length)) {
13003 // TODO: would be more clear when throwing a DimensionError here
13004 throw new IndexError(dim, size.length);
13005 }
13006
13007 if (isMatrix(mat)) {
13008 return mat.create(_reduce(mat.valueOf(), dim, callback));
13009 }else {
13010 return _reduce(mat, dim, callback);
13011 }
13012};
13013
13014/**
13015 * Recursively reduce a matrix
13016 * @param {Array} mat
13017 * @param {number} dim
13018 * @param {Function} callback
13019 * @returns {Array} ret
13020 * @private
13021 */
13022function _reduce(mat, dim, callback){
13023 var i, ret, val, tran;
13024
13025 if(dim<=0){
13026 if( !Array.isArray(mat[0]) ){
13027 val = mat[0];
13028 for(i=1; i<mat.length; i++){
13029 val = callback(val, mat[i]);
13030 }
13031 return val;
13032 }else{
13033 tran = _switch(mat);
13034 ret = [];
13035 for(i=0; i<tran.length; i++){
13036 ret[i] = _reduce(tran[i], dim-1, callback);
13037 }
13038 return ret;
13039 }
13040 }else{
13041 ret = [];
13042 for(i=0; i<mat.length; i++){
13043 ret[i] = _reduce(mat[i], dim-1, callback);
13044 }
13045 return ret;
13046 }
13047}
13048
13049/**
13050 * Transpose a matrix
13051 * @param {Array} mat
13052 * @returns {Array} ret
13053 * @private
13054 */
13055function _switch(mat){
13056 var I = mat.length;
13057 var J = mat[0].length;
13058 var i, j;
13059 var ret = [];
13060 for( j=0; j<J; j++) {
13061 var tmp = [];
13062 for( i=0; i<I; i++) {
13063 tmp.push(mat[i][j]);
13064 }
13065 ret.push(tmp);
13066 }
13067 return ret;
13068}
13069
13070
13071/***/ }),
13072/* 66 */
13073/***/ (function(module, exports, __webpack_require__) {
13074
13075"use strict";
13076
13077
13078var isCollection = __webpack_require__(48);
13079
13080/**
13081 * Test whether an array contains collections
13082 * @param {Array} array
13083 * @returns {boolean} Returns true when the array contains one or multiple
13084 * collections (Arrays or Matrices). Returns false otherwise.
13085 */
13086module.exports = function containsCollections (array) {
13087 for (var i = 0; i < array.length; i++) {
13088 if (isCollection(array[i])) {
13089 return true;
13090 }
13091 }
13092 return false;
13093};
13094
13095
13096/***/ }),
13097/* 67 */
13098/***/ (function(module, exports, __webpack_require__) {
13099
13100"use strict";
13101
13102
13103var clone = __webpack_require__(5).clone;
13104var format = __webpack_require__(9).format;
13105
13106function factory (type, config, load, typed) {
13107 var latex = __webpack_require__(4);
13108
13109 var matrix = load(__webpack_require__(0));
13110
13111 var DenseMatrix = type.DenseMatrix,
13112 SparseMatrix = type.SparseMatrix;
13113
13114 /**
13115 * Transpose a matrix. All values of the matrix are reflected over its
13116 * main diagonal. Only applicable to two dimensional matrices containing
13117 * a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional
13118 * vectors and scalars return the input unchanged.
13119 *
13120 * Syntax:
13121 *
13122 * math.transpose(x)
13123 *
13124 * Examples:
13125 *
13126 * var A = [[1, 2, 3], [4, 5, 6]];
13127 * math.transpose(A); // returns [[1, 4], [2, 5], [3, 6]]
13128 *
13129 * See also:
13130 *
13131 * diag, inv, subset, squeeze
13132 *
13133 * @param {Array | Matrix} x Matrix to be transposed
13134 * @return {Array | Matrix} The transposed matrix
13135 */
13136 var transpose = typed('transpose', {
13137
13138 'Array': function (x) {
13139 // use dense matrix implementation
13140 return transpose(matrix(x)).valueOf();
13141 },
13142
13143 'Matrix': function (x) {
13144 // matrix size
13145 var size = x.size();
13146
13147 // result
13148 var c;
13149
13150 // process dimensions
13151 switch (size.length) {
13152 case 1:
13153 // vector
13154 c = x.clone();
13155 break;
13156
13157 case 2:
13158 // rows and columns
13159 var rows = size[0];
13160 var columns = size[1];
13161
13162 // check columns
13163 if (columns === 0) {
13164 // throw exception
13165 throw new RangeError('Cannot transpose a 2D matrix with no columns (size: ' + format(size) + ')');
13166 }
13167
13168 // process storage format
13169 switch (x.storage()) {
13170 case 'dense':
13171 c = _denseTranspose(x, rows, columns);
13172 break;
13173 case 'sparse':
13174 c = _sparseTranspose(x, rows, columns);
13175 break;
13176 }
13177 break;
13178
13179 default:
13180 // multi dimensional
13181 throw new RangeError('Matrix must be a vector or two dimensional (size: ' + format(this._size) + ')');
13182 }
13183 return c;
13184 },
13185
13186 // scalars
13187 'any': function (x) {
13188 return clone(x);
13189 }
13190 });
13191
13192 var _denseTranspose = function (m, rows, columns) {
13193 // matrix array
13194 var data = m._data;
13195 // transposed matrix data
13196 var transposed = [];
13197 var transposedRow;
13198 // loop columns
13199 for (var j = 0; j < columns; j++) {
13200 // initialize row
13201 transposedRow = transposed[j] = [];
13202 // loop rows
13203 for (var i = 0; i < rows; i++) {
13204 // set data
13205 transposedRow[i] = clone(data[i][j]);
13206 }
13207 }
13208 // return matrix
13209 return new DenseMatrix({
13210 data: transposed,
13211 size: [columns, rows],
13212 datatype: m._datatype
13213 });
13214 };
13215
13216 var _sparseTranspose = function (m, rows, columns) {
13217 // matrix arrays
13218 var values = m._values;
13219 var index = m._index;
13220 var ptr = m._ptr;
13221 // result matrices
13222 var cvalues = values ? [] : undefined;
13223 var cindex = [];
13224 var cptr = [];
13225 // row counts
13226 var w = [];
13227 for (var x = 0; x < rows; x++)
13228 w[x] = 0;
13229 // vars
13230 var p, l, j;
13231 // loop values in matrix
13232 for (p = 0, l = index.length; p < l; p++) {
13233 // number of values in row
13234 w[index[p]]++;
13235 }
13236 // cumulative sum
13237 var sum = 0;
13238 // initialize cptr with the cummulative sum of row counts
13239 for (var i = 0; i < rows; i++) {
13240 // update cptr
13241 cptr.push(sum);
13242 // update sum
13243 sum += w[i];
13244 // update w
13245 w[i] = cptr[i];
13246 }
13247 // update cptr
13248 cptr.push(sum);
13249 // loop columns
13250 for (j = 0; j < columns; j++) {
13251 // values & index in column
13252 for (var k0 = ptr[j], k1 = ptr[j + 1], k = k0; k < k1; k++) {
13253 // C values & index
13254 var q = w[index[k]]++;
13255 // C[j, i] = A[i, j]
13256 cindex[q] = j;
13257 // check we need to process values (pattern matrix)
13258 if (values)
13259 cvalues[q] = clone(values[k]);
13260 }
13261 }
13262 // return matrix
13263 return new SparseMatrix({
13264 values: cvalues,
13265 index: cindex,
13266 ptr: cptr,
13267 size: [columns, rows],
13268 datatype: m._datatype
13269 });
13270 };
13271
13272 transpose.toTex = {1: '\\left(${args[0]}\\right)' + latex.operators['transpose']};
13273
13274 return transpose;
13275}
13276
13277exports.name = 'transpose';
13278exports.factory = factory;
13279
13280
13281/***/ }),
13282/* 68 */
13283/***/ (function(module, exports, __webpack_require__) {
13284
13285"use strict";
13286
13287
13288var scatter = __webpack_require__(439);
13289var DimensionError = __webpack_require__(11);
13290
13291function factory (type, config, load, typed) {
13292
13293 var equalScalar = load(__webpack_require__(10));
13294
13295 var SparseMatrix = type.SparseMatrix;
13296
13297 /**
13298 * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij).
13299 * Callback function invoked (Anz U Bnz) times, where Anz and Bnz are the nonzero elements in both matrices.
13300 *
13301 *
13302 * ┌ f(Aij, Bij) ; A(i,j) !== 0 && B(i,j) !== 0
13303 * C(i,j) = ┤
13304 * └ 0 ; otherwise
13305 *
13306 *
13307 * @param {Matrix} a The SparseMatrix instance (A)
13308 * @param {Matrix} b The SparseMatrix instance (B)
13309 * @param {Function} callback The f(Aij,Bij) operation to invoke
13310 *
13311 * @return {Matrix} SparseMatrix (C)
13312 *
13313 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
13314 */
13315 var algorithm06 = function (a, b, callback) {
13316 // sparse matrix arrays
13317 var avalues = a._values;
13318 var asize = a._size;
13319 var adt = a._datatype;
13320 // sparse matrix arrays
13321 var bvalues = b._values;
13322 var bsize = b._size;
13323 var bdt = b._datatype;
13324
13325 // validate dimensions
13326 if (asize.length !== bsize.length)
13327 throw new DimensionError(asize.length, bsize.length);
13328
13329 // check rows & columns
13330 if (asize[0] !== bsize[0] || asize[1] !== bsize[1])
13331 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
13332
13333 // rows & columns
13334 var rows = asize[0];
13335 var columns = asize[1];
13336
13337 // datatype
13338 var dt;
13339 // equal signature to use
13340 var eq = equalScalar;
13341 // zero value
13342 var zero = 0;
13343 // callback signature to use
13344 var cf = callback;
13345
13346 // process data types
13347 if (typeof adt === 'string' && adt === bdt) {
13348 // datatype
13349 dt = adt;
13350 // find signature that matches (dt, dt)
13351 eq = typed.find(equalScalar, [dt, dt]);
13352 // convert 0 to the same datatype
13353 zero = typed.convert(0, dt);
13354 // callback
13355 cf = typed.find(callback, [dt, dt]);
13356 }
13357
13358 // result arrays
13359 var cvalues = avalues && bvalues ? [] : undefined;
13360 var cindex = [];
13361 var cptr = [];
13362 // matrix
13363 var c = new SparseMatrix({
13364 values: cvalues,
13365 index: cindex,
13366 ptr: cptr,
13367 size: [rows, columns],
13368 datatype: dt
13369 });
13370
13371 // workspaces
13372 var x = cvalues ? [] : undefined;
13373 // marks indicating we have a value in x for a given column
13374 var w = [];
13375 // marks indicating value in a given row has been updated
13376 var u = [];
13377
13378 // loop columns
13379 for (var j = 0; j < columns; j++) {
13380 // update cptr
13381 cptr[j] = cindex.length;
13382 // columns mark
13383 var mark = j + 1;
13384 // scatter the values of A(:,j) into workspace
13385 scatter(a, j, w, x, u, mark, c, cf);
13386 // scatter the values of B(:,j) into workspace
13387 scatter(b, j, w, x, u, mark, c, cf);
13388 // check we need to process values (non pattern matrix)
13389 if (x) {
13390 // initialize first index in j
13391 var k = cptr[j];
13392 // loop index in j
13393 while (k < cindex.length) {
13394 // row
13395 var i = cindex[k];
13396 // check function was invoked on current row (Aij !=0 && Bij != 0)
13397 if (u[i] === mark) {
13398 // value @ i
13399 var v = x[i];
13400 // check for zero value
13401 if (!eq(v, zero)) {
13402 // push value
13403 cvalues.push(v);
13404 // increment pointer
13405 k++;
13406 }
13407 else {
13408 // remove value @ i, do not increment pointer
13409 cindex.splice(k, 1);
13410 }
13411 }
13412 else {
13413 // remove value @ i, do not increment pointer
13414 cindex.splice(k, 1);
13415 }
13416 }
13417 }
13418 else {
13419 // initialize first index in j
13420 var p = cptr[j];
13421 // loop index in j
13422 while (p < cindex.length) {
13423 // row
13424 var r = cindex[p];
13425 // check function was invoked on current row (Aij !=0 && Bij != 0)
13426 if (u[r] !== mark) {
13427 // remove value @ i, do not increment pointer
13428 cindex.splice(p, 1);
13429 }
13430 else {
13431 // increment pointer
13432 p++;
13433 }
13434 }
13435 }
13436 }
13437 // update cptr
13438 cptr[columns] = cindex.length;
13439
13440 // return sparse matrix
13441 return c;
13442 };
13443
13444 return algorithm06;
13445}
13446
13447exports.name = 'algorithm06';
13448exports.factory = factory;
13449
13450
13451/***/ }),
13452/* 69 */
13453/***/ (function(module, exports, __webpack_require__) {
13454
13455"use strict";
13456
13457
13458var deepMap = __webpack_require__(1);
13459
13460function factory (type, config, load, typed) {
13461 var gamma = load(__webpack_require__(140));
13462 var latex = __webpack_require__(4);
13463
13464 /**
13465 * Compute the factorial of a value
13466 *
13467 * Factorial only supports an integer value as argument.
13468 * For matrices, the function is evaluated element wise.
13469 *
13470 * Syntax:
13471 *
13472 * math.factorial(n)
13473 *
13474 * Examples:
13475 *
13476 * math.factorial(5); // returns 120
13477 * math.factorial(3); // returns 6
13478 *
13479 * See also:
13480 *
13481 * combinations, gamma, permutations
13482 *
13483 * @param {number | BigNumber | Array | Matrix} n An integer number
13484 * @return {number | BigNumber | Array | Matrix} The factorial of `n`
13485 */
13486 var factorial = typed('factorial', {
13487 'number': function (n) {
13488 if (n < 0) {
13489 throw new Error('Value must be non-negative');
13490 }
13491
13492 return gamma(n + 1);
13493 },
13494
13495 'BigNumber': function (n) {
13496 if (n.isNegative()) {
13497 throw new Error('Value must be non-negative');
13498 }
13499
13500 return gamma(n.plus(1));
13501 },
13502
13503 'Array | Matrix': function (n) {
13504 return deepMap(n, factorial);
13505 }
13506 });
13507
13508 factorial.toTex = {
13509 1: '\\left(${args[0]}\\right)' + latex.operators['factorial']
13510 };
13511
13512 return factorial;
13513}
13514
13515exports.name = 'factorial';
13516exports.factory = factory;
13517
13518
13519/***/ }),
13520/* 70 */
13521/***/ (function(module, exports, __webpack_require__) {
13522
13523"use strict";
13524
13525
13526var isInteger = __webpack_require__(3).isInteger;
13527
13528function factory (type, config, load, typed) {
13529 /**
13530 * Compute the number of ways of picking `k` unordered outcomes from `n`
13531 * possibilities.
13532 *
13533 * Combinations only takes integer arguments.
13534 * The following condition must be enforced: k <= n.
13535 *
13536 * Syntax:
13537 *
13538 * math.combinations(n, k)
13539 *
13540 * Examples:
13541 *
13542 * math.combinations(7, 5); // returns 21
13543 *
13544 * See also:
13545 *
13546 * permutations, factorial
13547 *
13548 * @param {number | BigNumber} n Total number of objects in the set
13549 * @param {number | BigNumber} k Number of objects in the subset
13550 * @return {number | BigNumber} Number of possible combinations.
13551 */
13552 var combinations = typed('combinations', {
13553 'number, number': function (n, k) {
13554 var max, result, i;
13555
13556 if (!isInteger(n) || n < 0) {
13557 throw new TypeError('Positive integer value expected in function combinations');
13558 }
13559 if (!isInteger(k) || k < 0) {
13560 throw new TypeError('Positive integer value expected in function combinations');
13561 }
13562 if (k > n) {
13563 throw new TypeError('k must be less than or equal to n');
13564 }
13565
13566 max = Math.max(k, n - k);
13567 result = 1;
13568 for (i = 1; i <= n - max; i++) {
13569 result = result * (max + i) / i;
13570 }
13571
13572 return result;
13573 },
13574
13575 'BigNumber, BigNumber': function (n, k) {
13576 var max, result, i, ii;
13577 var one = new type.BigNumber(1);
13578
13579 if (!isPositiveInteger(n) || !isPositiveInteger(k)) {
13580 throw new TypeError('Positive integer value expected in function combinations');
13581 }
13582 if (k.gt(n)) {
13583 throw new TypeError('k must be less than n in function combinations');
13584 }
13585
13586 max = n.minus(k);
13587 if (k.lt(max)) max = k;
13588 result = one;
13589 for (i = one, ii = n.minus(max); i.lte(ii); i = i.plus(1)) {
13590 result = result.times(max.plus(i)).dividedBy(i);
13591 }
13592
13593 return result;
13594 }
13595
13596 // TODO: implement support for collection in combinations
13597 });
13598
13599 combinations.toTex = {2: '\\binom{${args[0]}}{${args[1]}}'};
13600
13601 return combinations;
13602}
13603
13604/**
13605 * Test whether BigNumber n is a positive integer
13606 * @param {BigNumber} n
13607 * @returns {boolean} isPositiveInteger
13608 */
13609function isPositiveInteger(n) {
13610 return n.isInteger() && n.gte(0);
13611}
13612
13613exports.name = 'combinations';
13614exports.factory = factory;
13615
13616
13617/***/ }),
13618/* 71 */
13619/***/ (function(module, exports) {
13620
13621/**
13622 * Test whether a value is a BigNumber
13623 * @param {*} x
13624 * @return {boolean}
13625 */
13626module.exports = function isBigNumber(x) {
13627 return x && x.constructor.prototype.isBigNumber || false
13628}
13629
13630
13631/***/ }),
13632/* 72 */
13633/***/ (function(module, exports, __webpack_require__) {
13634
13635"use strict";
13636
13637
13638var util = __webpack_require__(25);
13639
13640var string = util.string;
13641
13642var isString = string.isString;
13643
13644function factory (type, config, load, typed) {
13645 /**
13646 * @constructor Matrix
13647 *
13648 * A Matrix is a wrapper around an Array. A matrix can hold a multi dimensional
13649 * array. A matrix can be constructed as:
13650 * var matrix = math.matrix(data)
13651 *
13652 * Matrix contains the functions to resize, get and set values, get the size,
13653 * clone the matrix and to convert the matrix to a vector, array, or scalar.
13654 * Furthermore, one can iterate over the matrix using map and forEach.
13655 * The internal Array of the Matrix can be accessed using the function valueOf.
13656 *
13657 * Example usage:
13658 * var matrix = math.matrix([[1, 2], [3, 4]]);
13659 * matix.size(); // [2, 2]
13660 * matrix.resize([3, 2], 5);
13661 * matrix.valueOf(); // [[1, 2], [3, 4], [5, 5]]
13662 * matrix.subset([1,2]) // 3 (indexes are zero-based)
13663 *
13664 */
13665 function Matrix() {
13666 if (!(this instanceof Matrix)) {
13667 throw new SyntaxError('Constructor must be called with the new operator');
13668 }
13669 }
13670
13671 /**
13672 * Attach type information
13673 */
13674 Matrix.prototype.type = 'Matrix';
13675 Matrix.prototype.isMatrix = true;
13676
13677 /**
13678 * Get the Matrix storage constructor for the given format.
13679 *
13680 * @param {string} format The Matrix storage format.
13681 *
13682 * @return {Function} The Matrix storage constructor.
13683 */
13684 Matrix.storage = function (format) {
13685 // check storage format is a string
13686 if (!isString(format)) {
13687 throw new TypeError('format must be a string value');
13688 }
13689
13690 // get storage format constructor
13691 var constructor = Matrix._storage[format];
13692 if (!constructor) {
13693 throw new SyntaxError('Unsupported matrix storage format: ' + format);
13694 }
13695
13696 // return storage constructor
13697 return constructor;
13698 };
13699
13700 // a map with all constructors for all storage types
13701 Matrix._storage = {};
13702
13703 /**
13704 * Get the storage format used by the matrix.
13705 *
13706 * Usage:
13707 * var format = matrix.storage() // retrieve storage format
13708 *
13709 * @return {string} The storage format.
13710 */
13711 Matrix.prototype.storage = function () {
13712 // must be implemented by each of the Matrix implementations
13713 throw new Error('Cannot invoke storage on a Matrix interface');
13714 };
13715
13716 /**
13717 * Get the datatype of the data stored in the matrix.
13718 *
13719 * Usage:
13720 * var format = matrix.datatype() // retrieve matrix datatype
13721 *
13722 * @return {string} The datatype.
13723 */
13724 Matrix.prototype.datatype = function () {
13725 // must be implemented by each of the Matrix implementations
13726 throw new Error('Cannot invoke datatype on a Matrix interface');
13727 };
13728
13729 /**
13730 * Create a new Matrix With the type of the current matrix instance
13731 * @param {Array | Object} data
13732 * @param {string} [datatype]
13733 */
13734 Matrix.prototype.create = function (data, datatype) {
13735 throw new Error('Cannot invoke create on a Matrix interface');
13736 };
13737
13738 /**
13739 * Get a subset of the matrix, or replace a subset of the matrix.
13740 *
13741 * Usage:
13742 * var subset = matrix.subset(index) // retrieve subset
13743 * var value = matrix.subset(index, replacement) // replace subset
13744 *
13745 * @param {Index} index
13746 * @param {Array | Matrix | *} [replacement]
13747 * @param {*} [defaultValue=0] Default value, filled in on new entries when
13748 * the matrix is resized. If not provided,
13749 * new matrix elements will be filled with zeros.
13750 */
13751 Matrix.prototype.subset = function (index, replacement, defaultValue) {
13752 // must be implemented by each of the Matrix implementations
13753 throw new Error('Cannot invoke subset on a Matrix interface');
13754 };
13755
13756 /**
13757 * Get a single element from the matrix.
13758 * @param {number[]} index Zero-based index
13759 * @return {*} value
13760 */
13761 Matrix.prototype.get = function (index) {
13762 // must be implemented by each of the Matrix implementations
13763 throw new Error('Cannot invoke get on a Matrix interface');
13764 };
13765
13766 /**
13767 * Replace a single element in the matrix.
13768 * @param {number[]} index Zero-based index
13769 * @param {*} value
13770 * @param {*} [defaultValue] Default value, filled in on new entries when
13771 * the matrix is resized. If not provided,
13772 * new matrix elements will be left undefined.
13773 * @return {Matrix} self
13774 */
13775 Matrix.prototype.set = function (index, value, defaultValue) {
13776 // must be implemented by each of the Matrix implementations
13777 throw new Error('Cannot invoke set on a Matrix interface');
13778 };
13779
13780 /**
13781 * Resize the matrix to the given size. Returns a copy of the matrix when
13782 * `copy=true`, otherwise return the matrix itself (resize in place).
13783 *
13784 * @param {number[]} size The new size the matrix should have.
13785 * @param {*} [defaultValue=0] Default value, filled in on new entries.
13786 * If not provided, the matrix elements will
13787 * be filled with zeros.
13788 * @param {boolean} [copy] Return a resized copy of the matrix
13789 *
13790 * @return {Matrix} The resized matrix
13791 */
13792 Matrix.prototype.resize = function (size, defaultValue) {
13793 // must be implemented by each of the Matrix implementations
13794 throw new Error('Cannot invoke resize on a Matrix interface');
13795 };
13796
13797 /**
13798 * Reshape the matrix to the given size. Returns a copy of the matrix when
13799 * `copy=true`, otherwise return the matrix itself (reshape in place).
13800 *
13801 * @param {number[]} size The new size the matrix should have.
13802 * @param {boolean} [copy] Return a reshaped copy of the matrix
13803 *
13804 * @return {Matrix} The reshaped matrix
13805 */
13806 Matrix.prototype.reshape = function (size, defaultValue) {
13807 // must be implemented by each of the Matrix implementations
13808 throw new Error('Cannot invoke reshape on a Matrix interface');
13809 };
13810
13811 /**
13812 * Create a clone of the matrix
13813 * @return {Matrix} clone
13814 */
13815 Matrix.prototype.clone = function () {
13816 // must be implemented by each of the Matrix implementations
13817 throw new Error('Cannot invoke clone on a Matrix interface');
13818 };
13819
13820 /**
13821 * Retrieve the size of the matrix.
13822 * @returns {number[]} size
13823 */
13824 Matrix.prototype.size = function() {
13825 // must be implemented by each of the Matrix implementations
13826 throw new Error('Cannot invoke size on a Matrix interface');
13827 };
13828
13829 /**
13830 * Create a new matrix with the results of the callback function executed on
13831 * each entry of the matrix.
13832 * @param {Function} callback The callback function is invoked with three
13833 * parameters: the value of the element, the index
13834 * of the element, and the Matrix being traversed.
13835 * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.
13836 *
13837 * @return {Matrix} matrix
13838 */
13839 Matrix.prototype.map = function (callback, skipZeros) {
13840 // must be implemented by each of the Matrix implementations
13841 throw new Error('Cannot invoke map on a Matrix interface');
13842 };
13843
13844 /**
13845 * Execute a callback function on each entry of the matrix.
13846 * @param {Function} callback The callback function is invoked with three
13847 * parameters: the value of the element, the index
13848 * of the element, and the Matrix being traversed.
13849 */
13850 Matrix.prototype.forEach = function (callback) {
13851 // must be implemented by each of the Matrix implementations
13852 throw new Error('Cannot invoke forEach on a Matrix interface');
13853 };
13854
13855 /**
13856 * Create an Array with a copy of the data of the Matrix
13857 * @returns {Array} array
13858 */
13859 Matrix.prototype.toArray = function () {
13860 // must be implemented by each of the Matrix implementations
13861 throw new Error('Cannot invoke toArray on a Matrix interface');
13862 };
13863
13864 /**
13865 * Get the primitive value of the Matrix: a multidimensional array
13866 * @returns {Array} array
13867 */
13868 Matrix.prototype.valueOf = function () {
13869 // must be implemented by each of the Matrix implementations
13870 throw new Error('Cannot invoke valueOf on a Matrix interface');
13871 };
13872
13873 /**
13874 * Get a string representation of the matrix, with optional formatting options.
13875 * @param {Object | number | Function} [options] Formatting options. See
13876 * lib/utils/number:format for a
13877 * description of the available
13878 * options.
13879 * @returns {string} str
13880 */
13881 Matrix.prototype.format = function (options) {
13882 // must be implemented by each of the Matrix implementations
13883 throw new Error('Cannot invoke format on a Matrix interface');
13884 };
13885
13886 /**
13887 * Get a string representation of the matrix
13888 * @returns {string} str
13889 */
13890 Matrix.prototype.toString = function () {
13891 // must be implemented by each of the Matrix implementations
13892 throw new Error('Cannot invoke toString on a Matrix interface');
13893 };
13894
13895 // exports
13896 return Matrix;
13897}
13898
13899exports.name = 'Matrix';
13900exports.path = 'type';
13901exports.factory = factory;
13902
13903
13904/***/ }),
13905/* 73 */
13906/***/ (function(module, exports, __webpack_require__) {
13907
13908"use strict";
13909
13910
13911var DimensionError = __webpack_require__(11);
13912
13913function factory (type, config, load, typed) {
13914
13915 var equalScalar = load(__webpack_require__(10));
13916
13917 var SparseMatrix = type.SparseMatrix;
13918
13919 /**
13920 * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij).
13921 * Callback function invoked MAX(NNZA, NNZB) times
13922 *
13923 *
13924 * ┌ f(Aij, Bij) ; A(i,j) !== 0 && B(i,j) !== 0
13925 * C(i,j) = ┤ A(i,j) ; A(i,j) !== 0
13926 * └ B(i,j) ; B(i,j) !== 0
13927 *
13928 *
13929 * @param {Matrix} a The SparseMatrix instance (A)
13930 * @param {Matrix} b The SparseMatrix instance (B)
13931 * @param {Function} callback The f(Aij,Bij) operation to invoke
13932 *
13933 * @return {Matrix} SparseMatrix (C)
13934 *
13935 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
13936 */
13937 var algorithm04 = function (a, b, callback) {
13938 // sparse matrix arrays
13939 var avalues = a._values;
13940 var aindex = a._index;
13941 var aptr = a._ptr;
13942 var asize = a._size;
13943 var adt = a._datatype;
13944 // sparse matrix arrays
13945 var bvalues = b._values;
13946 var bindex = b._index;
13947 var bptr = b._ptr;
13948 var bsize = b._size;
13949 var bdt = b._datatype;
13950
13951 // validate dimensions
13952 if (asize.length !== bsize.length)
13953 throw new DimensionError(asize.length, bsize.length);
13954
13955 // check rows & columns
13956 if (asize[0] !== bsize[0] || asize[1] !== bsize[1])
13957 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
13958
13959 // rows & columns
13960 var rows = asize[0];
13961 var columns = asize[1];
13962
13963 // datatype
13964 var dt;
13965 // equal signature to use
13966 var eq = equalScalar;
13967 // zero value
13968 var zero = 0;
13969 // callback signature to use
13970 var cf = callback;
13971
13972 // process data types
13973 if (typeof adt === 'string' && adt === bdt) {
13974 // datatype
13975 dt = adt;
13976 // find signature that matches (dt, dt)
13977 eq = typed.find(equalScalar, [dt, dt]);
13978 // convert 0 to the same datatype
13979 zero = typed.convert(0, dt);
13980 // callback
13981 cf = typed.find(callback, [dt, dt]);
13982 }
13983
13984 // result arrays
13985 var cvalues = avalues && bvalues ? [] : undefined;
13986 var cindex = [];
13987 var cptr = [];
13988 // matrix
13989 var c = new SparseMatrix({
13990 values: cvalues,
13991 index: cindex,
13992 ptr: cptr,
13993 size: [rows, columns],
13994 datatype: dt
13995 });
13996
13997 // workspace
13998 var xa = avalues && bvalues ? [] : undefined;
13999 var xb = avalues && bvalues ? [] : undefined;
14000 // marks indicating we have a value in x for a given column
14001 var wa = [];
14002 var wb = [];
14003
14004 // vars
14005 var i, j, k, k0, k1;
14006
14007 // loop columns
14008 for (j = 0; j < columns; j++) {
14009 // update cptr
14010 cptr[j] = cindex.length;
14011 // columns mark
14012 var mark = j + 1;
14013 // loop A(:,j)
14014 for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
14015 // row
14016 i = aindex[k];
14017 // update c
14018 cindex.push(i);
14019 // update workspace
14020 wa[i] = mark;
14021 // check we need to process values
14022 if (xa)
14023 xa[i] = avalues[k];
14024 }
14025 // loop B(:,j)
14026 for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
14027 // row
14028 i = bindex[k];
14029 // check row exists in A
14030 if (wa[i] === mark) {
14031 // update record in xa @ i
14032 if (xa) {
14033 // invoke callback
14034 var v = cf(xa[i], bvalues[k]);
14035 // check for zero
14036 if (!eq(v, zero)) {
14037 // update workspace
14038 xa[i] = v;
14039 }
14040 else {
14041 // remove mark (index will be removed later)
14042 wa[i] = null;
14043 }
14044 }
14045 }
14046 else {
14047 // update c
14048 cindex.push(i);
14049 // update workspace
14050 wb[i] = mark;
14051 // check we need to process values
14052 if (xb)
14053 xb[i] = bvalues[k];
14054 }
14055 }
14056 // check we need to process values (non pattern matrix)
14057 if (xa && xb) {
14058 // initialize first index in j
14059 k = cptr[j];
14060 // loop index in j
14061 while (k < cindex.length) {
14062 // row
14063 i = cindex[k];
14064 // check workspace has value @ i
14065 if (wa[i] === mark) {
14066 // push value (Aij != 0 || (Aij != 0 && Bij != 0))
14067 cvalues[k] = xa[i];
14068 // increment pointer
14069 k++;
14070 }
14071 else if (wb[i] === mark) {
14072 // push value (bij != 0)
14073 cvalues[k] = xb[i];
14074 // increment pointer
14075 k++;
14076 }
14077 else {
14078 // remove index @ k
14079 cindex.splice(k, 1);
14080 }
14081 }
14082 }
14083 }
14084 // update cptr
14085 cptr[columns] = cindex.length;
14086
14087 // return sparse matrix
14088 return c;
14089 };
14090
14091 return algorithm04;
14092}
14093
14094exports.name = 'algorithm04';
14095exports.factory = factory;
14096
14097
14098/***/ }),
14099/* 74 */
14100/***/ (function(module, exports, __webpack_require__) {
14101
14102"use strict";
14103
14104
14105var deepMap = __webpack_require__(1);
14106
14107function factory (type, config, load, typed) {
14108 /**
14109 * Create a number or convert a string, boolean, or unit to a number.
14110 * When value is a matrix, all elements will be converted to number.
14111 *
14112 * Syntax:
14113 *
14114 * math.number(value)
14115 * math.number(unit, valuelessUnit)
14116 *
14117 * Examples:
14118 *
14119 * math.number(2); // returns number 2
14120 * math.number('7.2'); // returns number 7.2
14121 * math.number(true); // returns number 1
14122 * math.number([true, false, true, true]); // returns [1, 0, 1, 1]
14123 * math.number(math.unit('52cm'), 'm'); // returns 0.52
14124 *
14125 * See also:
14126 *
14127 * bignumber, boolean, complex, index, matrix, string, unit
14128 *
14129 * @param {string | number | BigNumber | Fraction | boolean | Array | Matrix | Unit | null} [value] Value to be converted
14130 * @param {Unit | string} [valuelessUnit] A valueless unit, used to convert a unit to a number
14131 * @return {number | Array | Matrix} The created number
14132 */
14133 var number = typed('number', {
14134 '': function () {
14135 return 0;
14136 },
14137
14138 'number': function (x) {
14139 return x;
14140 },
14141
14142 'string': function (x) {
14143 var num = Number(x);
14144 if (isNaN(num)) {
14145 throw new SyntaxError('String "' + x + '" is no valid number');
14146 }
14147 return num;
14148 },
14149
14150 'BigNumber': function (x) {
14151 return x.toNumber();
14152 },
14153
14154 'Fraction': function (x) {
14155 return x.valueOf();
14156 },
14157
14158 'Unit': function (x) {
14159 throw new Error('Second argument with valueless unit expected');
14160 },
14161
14162 'Unit, string | Unit': function (unit, valuelessUnit) {
14163 return unit.toNumber(valuelessUnit);
14164 },
14165
14166 'Array | Matrix': function (x) {
14167 return deepMap(x, number);
14168 }
14169 });
14170
14171 number.toTex = {
14172 0: '0',
14173 1: '\\left(${args[0]}\\right)',
14174 2: '\\left(\\left(${args[0]}\\right)${args[1]}\\right)'
14175 };
14176
14177 return number;
14178}
14179
14180exports.name = 'number';
14181exports.factory = factory;
14182
14183
14184/***/ }),
14185/* 75 */
14186/***/ (function(module, exports, __webpack_require__) {
14187
14188"use strict";
14189
14190
14191var deepMap = __webpack_require__(1);
14192var number = __webpack_require__(3);
14193
14194function factory (type, config, load, typed) {
14195 /**
14196 * Test whether a value is an numeric value.
14197 *
14198 * The function is evaluated element-wise in case of Array or Matrix input.
14199 *
14200 * Syntax:
14201 *
14202 * math.isNumeric(x)
14203 *
14204 * Examples:
14205 *
14206 * math.isNumeric(2); // returns true
14207 * math.isNumeric(0); // returns true
14208 * math.isNumeric(math.bignumber(500)); // returns true
14209 * math.isNumeric(math.fraction(4)); // returns true
14210 * math.isNumeric(math.complex('2-4i'); // returns false
14211 * math.isNumeric('3'); // returns false
14212 * math.isNumeric([2.3, 'foo', false]); // returns [true, false, true]
14213 *
14214 * See also:
14215 *
14216 * isZero, isPositive, isNegative, isInteger
14217 *
14218 * @param {*} x Value to be tested
14219 * @return {boolean} Returns true when `x` is a `number`, `BigNumber`,
14220 * `Fraction`, or `boolean`. Returns false for other types.
14221 * Throws an error in case of unknown types.
14222 */
14223 var isNumeric = typed('isNumeric', {
14224 'number | BigNumber | Fraction | boolean': function () {
14225 return true;
14226 },
14227
14228 'Complex | Unit | string': function () {
14229 return false;
14230 },
14231
14232 'Array | Matrix': function (x) {
14233 return deepMap(x, isNumeric);
14234 }
14235 });
14236
14237 return isNumeric;
14238}
14239
14240exports.name = 'isNumeric';
14241exports.factory = factory;
14242
14243
14244/***/ }),
14245/* 76 */
14246/***/ (function(module, exports, __webpack_require__) {
14247
14248"use strict";
14249
14250
14251var types = __webpack_require__(60);
14252
14253function factory (type, config, load, typed) {
14254 /**
14255 * Determine the type of a variable.
14256 *
14257 * Function `typeof` recognizes the following types of objects:
14258 *
14259 * Object | Returns | Example
14260 * ---------------------- | ------------- | ------------------------------------------
14261 * null | `'null'` | `math.typeof(null)`
14262 * number | `'number'` | `math.typeof(3.5)`
14263 * boolean | `'boolean'` | `math.typeof (true)`
14264 * string | `'string'` | `math.typeof ('hello world')`
14265 * Array | `'Array'` | `math.typeof ([1, 2, 3])`
14266 * Date | `'Date'` | `math.typeof (new Date())`
14267 * Function | `'Function'` | `math.typeof (function () {})`
14268 * Object | `'Object'` | `math.typeof ({a: 2, b: 3})`
14269 * RegExp | `'RegExp'` | `math.typeof (/a regexp/)`
14270 * undefined | `'undefined'` | `math.typeof(undefined)`
14271 * math.type.BigNumber | `'BigNumber'` | `math.typeof (math.bignumber('2.3e500'))`
14272 * math.type.Chain | `'Chain'` | `math.typeof (math.chain(2))`
14273 * math.type.Complex | `'Complex'` | `math.typeof (math.complex(2, 3))`
14274 * math.type.Fraction | `'Fraction'` | `math.typeof (math.fraction(1, 3))`
14275 * math.type.Help | `'Help'` | `math.typeof (math.help('sqrt'))`
14276 * math.type.Index | `'Index'` | `math.typeof (math.index(1, 3))`
14277 * math.type.Matrix | `'Matrix'` | `math.typeof (math.matrix([[1,2], [3, 4]]))`
14278 * math.type.Range | `'Range'` | `math.typeof (math.range(0, 10))`
14279 * math.type.Unit | `'Unit'` | `math.typeof (math.unit('45 deg'))`
14280 *
14281 * Syntax:
14282 *
14283 * math.typeof(x)
14284 *
14285 * Examples:
14286 *
14287 * math.typeof(3.5); // returns 'number'
14288 * math.typeof(math.complex('2-4i')); // returns 'Complex'
14289 * math.typeof(math.unit('45 deg')); // returns 'Unit'
14290 * math.typeof('hello world'); // returns 'string'
14291 *
14292 * @param {*} x The variable for which to test the type.
14293 * @return {string} Returns the name of the type. Primitive types are lower case,
14294 * non-primitive types are upper-camel-case.
14295 * For example 'number', 'string', 'Array', 'Date'.
14296 */
14297 var _typeof = typed('_typeof', {
14298 'any': function (x) {
14299 // JavaScript types
14300 var t = types.type(x);
14301
14302 // math.js types
14303 if (t === 'Object') {
14304 if (type.isBigNumber(x)) return 'BigNumber';
14305 if (type.isComplex(x)) return 'Complex';
14306 if (type.isFraction(x)) return 'Fraction';
14307 if (type.isMatrix(x)) return 'Matrix';
14308 if (type.isUnit(x)) return 'Unit';
14309 if (type.isIndex(x)) return 'Index';
14310 if (type.isRange(x)) return 'Range';
14311 if (type.isChain(x)) return 'Chain';
14312 if (type.isHelp(x)) return 'Help';
14313 }
14314
14315 return t;
14316 }
14317 });
14318
14319 _typeof.toTex = undefined; // use default template
14320
14321 return _typeof;
14322}
14323
14324exports.name = 'typeof';
14325exports.factory = factory;
14326
14327
14328/***/ }),
14329/* 77 */
14330/***/ (function(module, exports, __webpack_require__) {
14331
14332"use strict";
14333
14334
14335// Reserved keywords not allowed to use in the parser
14336module.exports = {
14337 end: true
14338};
14339
14340
14341/***/ }),
14342/* 78 */
14343/***/ (function(module, exports, __webpack_require__) {
14344
14345"use strict";
14346
14347
14348var map = __webpack_require__(2).map;
14349var join = __webpack_require__(2).join;
14350var escape = __webpack_require__(9).escape;
14351
14352function factory (type, config, load, typed) {
14353 var register = load(__webpack_require__(7)).register;
14354 var compile = load(__webpack_require__(7)).compile;
14355 var Node = load(__webpack_require__(15));
14356 var RangeNode = load(__webpack_require__(79));
14357 var SymbolNode = load(__webpack_require__(36));
14358
14359 var Range = load(__webpack_require__(94));
14360
14361 var isArray = Array.isArray;
14362
14363 /**
14364 * @constructor IndexNode
14365 * @extends Node
14366 *
14367 * Describes a subset of a matrix or an object property.
14368 * Cannot be used on its own, needs to be used within an AccessorNode or
14369 * AssignmentNode.
14370 *
14371 * @param {Node[]} dimensions
14372 * @param {boolean} [dotNotation=false] Optional property describing whether
14373 * this index was written using dot
14374 * notation like `a.b`, or using bracket
14375 * notation like `a["b"]` (default).
14376 * Used to stringify an IndexNode.
14377 */
14378 function IndexNode(dimensions, dotNotation) {
14379 if (!(this instanceof IndexNode)) {
14380 throw new SyntaxError('Constructor must be called with the new operator');
14381 }
14382
14383 this.dimensions = dimensions;
14384 this.dotNotation = dotNotation || false;
14385
14386 // validate input
14387 if (!isArray(dimensions) || !dimensions.every(type.isNode)) {
14388 throw new TypeError('Array containing Nodes expected for parameter "dimensions"');
14389 }
14390 if (this.dotNotation && !this.isObjectProperty()) {
14391 throw new Error('dotNotation only applicable for object properties');
14392 }
14393
14394 // TODO: deprecated since v3, remove some day
14395 var deprecated = function () {
14396 throw new Error('Property `IndexNode.object` is deprecated, use `IndexNode.fn` instead');
14397 };
14398 Object.defineProperty(this, 'object', { get: deprecated, set: deprecated });
14399 }
14400
14401 IndexNode.prototype = new Node();
14402
14403 IndexNode.prototype.type = 'IndexNode';
14404
14405 IndexNode.prototype.isIndexNode = true;
14406
14407 /**
14408 * Compile all range nodes
14409 *
14410 * When some of the dimensions has `end` defined, the IndexNode requires
14411 * a variable `size` to be defined in the current closure, and must contain
14412 * the size of the matrix that's being handled. To check whether the `size`
14413 * variable is needed, call IndexNode.needsSize().
14414 *
14415 * @param {IndexNode} node The node to be compiled
14416 * @param {Object} defs Object which can be used to define functions
14417 * or constants globally available for the
14418 * compiled expression
14419 * @param {Object} args Object with local function arguments, the key is
14420 * the name of the argument, and the value is `true`.
14421 * The object may not be mutated, but must be
14422 * extended instead.
14423 * @return {string} code
14424 */
14425 function compileIndexNode(node, defs, args) {
14426 if (!(node instanceof IndexNode)) {
14427 throw new TypeError('No valid IndexNode')
14428 }
14429
14430 // args can be mutated by IndexNode, when dimensions use `end`
14431 var childArgs = Object.create(args);
14432
14433 // helper function to create a Range from start, step and end
14434 defs.range = function (start, end, step) {
14435 return new Range(
14436 type.isBigNumber(start) ? start.toNumber() : start,
14437 type.isBigNumber(end) ? end.toNumber() : end,
14438 type.isBigNumber(step) ? step.toNumber() : step
14439 );
14440 };
14441
14442 // TODO: implement support for bignumber (currently bignumbers are silently
14443 // reduced to numbers when changing the value to zero-based)
14444
14445 // TODO: Optimization: when the range values are ConstantNodes,
14446 // we can beforehand resolve the zero-based value
14447
14448 // optimization for a simple object property
14449 var dimensions = map(node.dimensions, function (range, i) {
14450 if (type.isRangeNode(range)) {
14451 if (range.needsEnd()) {
14452 childArgs.end = 'end';
14453
14454 // resolve end and create range
14455 return '(function () {' +
14456 'var end = size[' + i + ']; ' +
14457 'return range(' +
14458 compile(range.start, defs, childArgs) + ', ' +
14459 compile(range.end, defs, childArgs) + ', ' +
14460 (range.step ? compile(range.step, defs, childArgs) : '1') +
14461 '); ' +
14462 '})()';
14463 }
14464 else {
14465 // create range
14466 return 'range(' +
14467 compile(range.start, defs, childArgs) + ', ' +
14468 compile(range.end, defs, childArgs) + ', ' +
14469 (range.step ? compile(range.step, defs, childArgs) : '1') +
14470 ')';
14471 }
14472 }
14473 if (type.isSymbolNode(range) && range.name === 'end') {
14474 childArgs.end = 'end';
14475
14476 // resolve the parameter 'end'
14477 return '(function () {' +
14478 'var end = size[' + i + ']; ' +
14479 'return ' + compile(range, defs, childArgs) + '; ' +
14480 '})()'
14481 }
14482 else { // ConstantNode
14483 return compile(range, defs, childArgs);
14484 }
14485 });
14486
14487 return 'math.index(' + join(dimensions, ', ') + ')';
14488 }
14489
14490 // register the compile function
14491 register(IndexNode.prototype.type, compileIndexNode);
14492
14493 /**
14494 * Execute a callback for each of the child nodes of this node
14495 * @param {function(child: Node, path: string, parent: Node)} callback
14496 */
14497 IndexNode.prototype.forEach = function (callback) {
14498 for (var i = 0; i < this.dimensions.length; i++) {
14499 callback(this.dimensions[i], 'dimensions[' + i + ']', this);
14500 }
14501 };
14502
14503 /**
14504 * Create a new IndexNode having it's childs be the results of calling
14505 * the provided callback function for each of the childs of the original node.
14506 * @param {function(child: Node, path: string, parent: Node): Node} callback
14507 * @returns {IndexNode} Returns a transformed copy of the node
14508 */
14509 IndexNode.prototype.map = function (callback) {
14510 var dimensions = [];
14511 for (var i = 0; i < this.dimensions.length; i++) {
14512 dimensions[i] = this._ifNode(callback(this.dimensions[i], 'dimensions[' + i + ']', this));
14513 }
14514
14515 return new IndexNode(dimensions);
14516 };
14517
14518 /**
14519 * Create a clone of this node, a shallow copy
14520 * @return {IndexNode}
14521 */
14522 IndexNode.prototype.clone = function () {
14523 return new IndexNode(this.dimensions.slice(0));
14524 };
14525
14526 /**
14527 * Test whether this IndexNode contains a single property name
14528 * @return {boolean}
14529 */
14530 IndexNode.prototype.isObjectProperty = function () {
14531 return this.dimensions.length === 1 &&
14532 type.isConstantNode(this.dimensions[0]) &&
14533 this.dimensions[0].valueType === 'string';
14534 };
14535
14536 /**
14537 * Returns the property name if IndexNode contains a property.
14538 * If not, returns null.
14539 * @return {string | null}
14540 */
14541 IndexNode.prototype.getObjectProperty = function () {
14542 return this.isObjectProperty() ? this.dimensions[0].value : null;
14543 };
14544
14545 /**
14546 * Get string representation
14547 * @param {Object} options
14548 * @return {string} str
14549 */
14550 IndexNode.prototype._toString = function (options) {
14551 // format the parameters like "[1, 0:5]"
14552 return this.dotNotation
14553 ? ('.' + this.getObjectProperty())
14554 : ('[' + this.dimensions.join(', ') + ']');
14555 };
14556
14557 /**
14558 * Get HTML representation
14559 * @param {Object} options
14560 * @return {string} str
14561 */
14562 IndexNode.prototype.toHTML = function (options) {
14563 // format the parameters like "[1, 0:5]"
14564 var dimensions = []
14565 for (var i=0; i<this.dimensions.length; i++) {
14566 dimensions[i] = this.dimensions[i].toHTML();
14567 }
14568 if (this.dotNotation) {
14569 return '<span class="math-operator math-accessor-operator">.</span>' + '<span class="math-symbol math-property">' + escape(this.getObjectProperty()) + '</span>';}
14570 else {
14571 return '<span class="math-parenthesis math-square-parenthesis">[</span>' + dimensions.join('<span class="math-separator">,</span>') + '<span class="math-parenthesis math-square-parenthesis">]</span>'}
14572 };
14573
14574 /**
14575 * Get LaTeX representation
14576 * @param {Object} options
14577 * @return {string} str
14578 */
14579 IndexNode.prototype._toTex = function (options) {
14580 var dimensions = this.dimensions.map(function (range) {
14581 return range.toTex(options);
14582 });
14583
14584 return this.dotNotation
14585 ? ('.' + this.getObjectProperty() + '')
14586 : ('_{' + dimensions.join(',') + '}');
14587 };
14588
14589 /**
14590 * Test whether this IndexNode needs the object size, size of the Matrix
14591 * @return {boolean}
14592 */
14593 IndexNode.prototype.needsSize = function () {
14594 return this.dimensions.some(function (range) {
14595 return (type.isRangeNode(range) && range.needsEnd()) ||
14596 (type.isSymbolNode(range) && range.name === 'end');
14597 });
14598 };
14599
14600 return IndexNode;
14601}
14602
14603exports.name = 'IndexNode';
14604exports.path = 'expression.node';
14605exports.factory = factory;
14606
14607
14608/***/ }),
14609/* 79 */
14610/***/ (function(module, exports, __webpack_require__) {
14611
14612"use strict";
14613
14614
14615var operators = __webpack_require__(54);
14616
14617function factory (type, config, load, typed) {
14618 var register = load(__webpack_require__(7)).register;
14619 var compile = load(__webpack_require__(7)).compile;
14620 var Node = load(__webpack_require__(15));
14621
14622 /**
14623 * @constructor RangeNode
14624 * @extends {Node}
14625 * create a range
14626 * @param {Node} start included lower-bound
14627 * @param {Node} end included upper-bound
14628 * @param {Node} [step] optional step
14629 */
14630 function RangeNode(start, end, step) {
14631 if (!(this instanceof RangeNode)) {
14632 throw new SyntaxError('Constructor must be called with the new operator');
14633 }
14634
14635 // validate inputs
14636 if (!type.isNode(start)) throw new TypeError('Node expected');
14637 if (!type.isNode(end)) throw new TypeError('Node expected');
14638 if (step && !type.isNode(step)) throw new TypeError('Node expected');
14639 if (arguments.length > 3) throw new Error('Too many arguments');
14640
14641 this.start = start; // included lower-bound
14642 this.end = end; // included upper-bound
14643 this.step = step || null; // optional step
14644 }
14645
14646 RangeNode.prototype = new Node();
14647
14648 RangeNode.prototype.type = 'RangeNode';
14649
14650 RangeNode.prototype.isRangeNode = true;
14651
14652 /**
14653 * Check whether the RangeNode needs the `end` symbol to be defined.
14654 * This end is the size of the Matrix in current dimension.
14655 * @return {boolean}
14656 */
14657 RangeNode.prototype.needsEnd = function () {
14658 // find all `end` symbols in this RangeNode
14659 var endSymbols = this.filter(function (node) {
14660 return type.isSymbolNode(node) && (node.name === 'end');
14661 });
14662
14663 return endSymbols.length > 0;
14664 };
14665
14666 /**
14667 * Compile the node to javascript code
14668 *
14669 * When the range has a symbol `end` defined, the RangeNode requires
14670 * a variable `end` to be defined in the current closure, which must contain
14671 * the length of the of the matrix that's being handled in the range's
14672 * dimension. To check whether the `end` variable is needed, call
14673 * RangeNode.needsEnd().
14674 *
14675 * @param {RangeNode} node The node to be compiled
14676 * @param {Object} defs Object which can be used to define functions
14677 * or constants globally available for the compiled
14678 * expression
14679 * @param {Object} args Object with local function arguments, the key is
14680 * the name of the argument, and the value is `true`.
14681 * The object may not be mutated, but must be
14682 * extended instead.
14683 * @return {string} js
14684 * @private
14685 */
14686 function compileRangeNode(node, defs, args) {
14687 if (!(node instanceof RangeNode)) {
14688 throw new TypeError('No valid RangeNode')
14689 }
14690
14691 return 'math.range(' +
14692 compile(node.start, defs, args) + ', ' +
14693 compile(node.end, defs, args) +
14694 (node.step ? (', ' + compile(node.step, defs, args)) : '') +
14695 ')';
14696 }
14697
14698 // register the compile function
14699 register(RangeNode.prototype.type, compileRangeNode);
14700
14701 /**
14702 * Execute a callback for each of the child nodes of this node
14703 * @param {function(child: Node, path: string, parent: Node)} callback
14704 */
14705 RangeNode.prototype.forEach = function (callback) {
14706 callback(this.start, 'start', this);
14707 callback(this.end, 'end', this);
14708 if (this.step) {
14709 callback(this.step, 'step', this);
14710 }
14711 };
14712
14713 /**
14714 * Create a new RangeNode having it's childs be the results of calling
14715 * the provided callback function for each of the childs of the original node.
14716 * @param {function(child: Node, path: string, parent: Node): Node} callback
14717 * @returns {RangeNode} Returns a transformed copy of the node
14718 */
14719 RangeNode.prototype.map = function (callback) {
14720 return new RangeNode(
14721 this._ifNode(callback(this.start, 'start', this)),
14722 this._ifNode(callback(this.end, 'end', this)),
14723 this.step && this._ifNode(callback(this.step, 'step', this))
14724 );
14725 };
14726
14727 /**
14728 * Create a clone of this node, a shallow copy
14729 * @return {RangeNode}
14730 */
14731 RangeNode.prototype.clone = function () {
14732 return new RangeNode(this.start, this.end, this.step && this.step);
14733 };
14734
14735 /**
14736 * Calculate the necessary parentheses
14737 * @param {Node} node
14738 * @param {string} parenthesis
14739 * @return {Object} parentheses
14740 * @private
14741 */
14742 function calculateNecessaryParentheses(node, parenthesis) {
14743 var precedence = operators.getPrecedence(node, parenthesis);
14744 var parens = {};
14745
14746 var startPrecedence = operators.getPrecedence(node.start, parenthesis);
14747 parens.start = ((startPrecedence !== null) && (startPrecedence <= precedence))
14748 || (parenthesis === 'all');
14749
14750 if (node.step) {
14751 var stepPrecedence = operators.getPrecedence(node.step, parenthesis);
14752 parens.step = ((stepPrecedence !== null) && (stepPrecedence <= precedence))
14753 || (parenthesis === 'all');
14754 }
14755
14756 var endPrecedence = operators.getPrecedence(node.end, parenthesis);
14757 parens.end = ((endPrecedence !== null) && (endPrecedence <= precedence))
14758 || (parenthesis === 'all');
14759
14760 return parens;
14761 }
14762
14763 /**
14764 * Get string representation
14765 * @param {Object} options
14766 * @return {string} str
14767 */
14768 RangeNode.prototype._toString = function (options) {
14769 var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep';
14770 var parens = calculateNecessaryParentheses(this, parenthesis);
14771
14772 //format string as start:step:stop
14773 var str;
14774
14775 var start = this.start.toString(options);
14776 if (parens.start) {
14777 start = '(' + start + ')';
14778 }
14779 str = start;
14780
14781 if (this.step) {
14782 var step = this.step.toString(options);
14783 if (parens.step) {
14784 step = '(' + step + ')';
14785 }
14786 str += ':' + step;
14787 }
14788
14789 var end = this.end.toString(options);
14790 if (parens.end) {
14791 end = '(' + end + ')';
14792 }
14793 str += ':' + end;
14794
14795 return str;
14796 };
14797
14798 /**
14799 * Get HTML representation
14800 * @param {Object} options
14801 * @return {string} str
14802 */
14803 RangeNode.prototype.toHTML = function (options) {
14804 var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep';
14805 var parens = calculateNecessaryParentheses(this, parenthesis);
14806
14807 //format string as start:step:stop
14808 var str;
14809
14810 var start = this.start.toHTML(options);
14811 if (parens.start) {
14812 start = '<span class="math-parenthesis math-round-parenthesis">(</span>' + start + '<span class="math-parenthesis math-round-parenthesis">)</span>';
14813 }
14814 str = start;
14815
14816 if (this.step) {
14817 var step = this.step.toHTML(options);
14818 if (parens.step) {
14819 step = '<span class="math-parenthesis math-round-parenthesis">(</span>' + step + '<span class="math-parenthesis math-round-parenthesis">)</span>';
14820 }
14821 str += '<span class="math-operator math-range-operator">:</span>' + step;
14822 }
14823
14824 var end = this.end.toHTML(options);
14825 if (parens.end) {
14826 end = '<span class="math-parenthesis math-round-parenthesis">(</span>' + end + '<span class="math-parenthesis math-round-parenthesis">)</span>';
14827 }
14828 str += '<span class="math-operator math-range-operator">:</span>' + end;
14829
14830 return str;
14831 };
14832
14833 /**
14834 * Get LaTeX representation
14835 * @params {Object} options
14836 * @return {string} str
14837 */
14838 RangeNode.prototype._toTex = function (options) {
14839 var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep';
14840 var parens = calculateNecessaryParentheses(this, parenthesis);
14841
14842 var str = this.start.toTex(options);
14843 if (parens.start) {
14844 str = '\\left(' + str + '\\right)';
14845 }
14846
14847 if (this.step) {
14848 var step = this.step.toTex(options);
14849 if (parens.step) {
14850 step = '\\left(' + step + '\\right)';
14851 }
14852 str += ':' + step;
14853 }
14854
14855 var end = this.end.toTex(options);
14856 if (parens.end) {
14857 end = '\\left(' + end + '\\right)';
14858 }
14859 str += ':' + end;
14860
14861 return str;
14862 };
14863
14864 return RangeNode;
14865}
14866
14867exports.name = 'RangeNode';
14868exports.path = 'expression.node';
14869exports.factory = factory;
14870
14871
14872/***/ }),
14873/* 80 */
14874/***/ (function(module, exports, __webpack_require__) {
14875
14876"use strict";
14877
14878
14879var map = __webpack_require__(2).map;
14880var join = __webpack_require__(2).join;
14881
14882function factory (type, config, load, typed) {
14883 var register = load(__webpack_require__(7)).register;
14884 var compile = load(__webpack_require__(7)).compile;
14885 var Node = load(__webpack_require__(15));
14886
14887 /**
14888 * @constructor ArrayNode
14889 * @extends {Node}
14890 * Holds an 1-dimensional array with items
14891 * @param {Node[]} [items] 1 dimensional array with items
14892 */
14893 function ArrayNode(items) {
14894 if (!(this instanceof ArrayNode)) {
14895 throw new SyntaxError('Constructor must be called with the new operator');
14896 }
14897
14898 this.items = items || [];
14899
14900 // validate input
14901 if (!Array.isArray(this.items) || !this.items.every(type.isNode)) {
14902 throw new TypeError('Array containing Nodes expected');
14903 }
14904
14905 // TODO: deprecated since v3, remove some day
14906 var deprecated = function () {
14907 throw new Error('Property `ArrayNode.nodes` is deprecated, use `ArrayNode.items` instead');
14908 };
14909 Object.defineProperty(this, 'nodes', { get: deprecated, set: deprecated });
14910 }
14911
14912 ArrayNode.prototype = new Node();
14913
14914 ArrayNode.prototype.type = 'ArrayNode';
14915
14916 ArrayNode.prototype.isArrayNode = true;
14917
14918 /**
14919 * Compile the node to javascript code
14920 * @param {ArrayNode} node Node to be compiled
14921 * @param {Object} defs Object which can be used to define functions
14922 * or constants globally available for the compiled
14923 * expression
14924 * @param {Object} args Object with local function arguments, the key is
14925 * the name of the argument, and the value is `true`.
14926 * The object may not be mutated, but must be
14927 * extended instead.
14928 * @private
14929 */
14930 function compileArrayNode(node, defs, args) {
14931 if (!(node instanceof ArrayNode)) {
14932 throw new TypeError('No valid ArrayNode')
14933 }
14934
14935 var asMatrix = (defs.math.config().matrix !== 'Array');
14936
14937 var items = map(node.items, function (item) {
14938 return compile(item, defs, args);
14939 });
14940
14941 return (asMatrix ? 'math.matrix([' : '[') +
14942 join(items, ',') +
14943 (asMatrix ? '])' : ']');
14944 }
14945
14946 // register the compile function
14947 register(ArrayNode.prototype.type, compileArrayNode);
14948
14949 /**
14950 * Execute a callback for each of the child nodes of this node
14951 * @param {function(child: Node, path: string, parent: Node)} callback
14952 */
14953 ArrayNode.prototype.forEach = function (callback) {
14954 for (var i = 0; i < this.items.length; i++) {
14955 var node = this.items[i];
14956 callback(node, 'items[' + i + ']', this);
14957 }
14958 };
14959
14960 /**
14961 * Create a new ArrayNode having it's childs be the results of calling
14962 * the provided callback function for each of the childs of the original node.
14963 * @param {function(child: Node, path: string, parent: Node): Node} callback
14964 * @returns {ArrayNode} Returns a transformed copy of the node
14965 */
14966 ArrayNode.prototype.map = function (callback) {
14967 var items = [];
14968 for (var i = 0; i < this.items.length; i++) {
14969 items[i] = this._ifNode(callback(this.items[i], 'items[' + i + ']', this));
14970 }
14971 return new ArrayNode(items);
14972 };
14973
14974 /**
14975 * Create a clone of this node, a shallow copy
14976 * @return {ArrayNode}
14977 */
14978 ArrayNode.prototype.clone = function() {
14979 return new ArrayNode(this.items.slice(0));
14980 };
14981
14982 /**
14983 * Get string representation
14984 * @param {Object} options
14985 * @return {string} str
14986 * @override
14987 */
14988 ArrayNode.prototype._toString = function(options) {
14989 var items = this.items.map(function (node) {
14990 return node.toString(options);
14991 });
14992 return '[' + items.join(', ') + ']';
14993 };
14994
14995 /**
14996 * Get HTML representation
14997 * @param {Object} options
14998 * @return {string} str
14999 * @override
15000 */
15001 ArrayNode.prototype.toHTML = function(options) {
15002 var items = this.items.map(function (node) {
15003 return node.toHTML(options);
15004 });
15005 return '<span class="math-parenthesis math-square-parenthesis">[</span>' + items.join('<span class="math-separator">,</span>') + '<span class="math-parenthesis math-square-parenthesis">]</span>';
15006 };
15007
15008 /**
15009 * Get LaTeX representation
15010 * @param {Object} options
15011 * @return {string} str
15012 */
15013 ArrayNode.prototype._toTex = function(options) {
15014 var s = '\\begin{bmatrix}';
15015
15016 this.items.forEach(function(node) {
15017 if (node.items) {
15018 s += node.items.map(function(childNode) {
15019 return childNode.toTex(options);
15020 }).join('&');
15021 }
15022 else {
15023 s += node.toTex(options);
15024 }
15025
15026 // new line
15027 s += '\\\\';
15028 });
15029 s += '\\end{bmatrix}';
15030 return s;
15031 };
15032
15033 return ArrayNode;
15034}
15035
15036exports.name = 'ArrayNode';
15037exports.path = 'expression.node';
15038exports.factory = factory;
15039
15040
15041/***/ }),
15042/* 81 */
15043/***/ (function(module, exports) {
15044
15045function factory (type, config, load, typed) {
15046 /**
15047 * Compile an inline expression like "x > 0"
15048 * @param {Node} expression
15049 * @param {Object} math
15050 * @param {Object} scope
15051 * @return {function} Returns a function with one argument which fills in the
15052 * undefined variable (like "x") and evaluates the expression
15053 */
15054 return function compileInlineExpression(expression, math, scope) {
15055 // find an undefined symbol
15056 var symbol = expression.filter(function (node) {
15057 return type.isSymbolNode(node) &&
15058 !(node.name in math) &&
15059 !(node.name in scope);
15060 })[0];
15061
15062 if (!symbol) {
15063 throw new Error('No undefined variable found in inline expression "' + expression + '"');
15064 }
15065
15066 // create a test function for this equation
15067 var name = symbol.name; // variable name
15068 var subScope = Object.create(scope);
15069 var eq = expression.compile();
15070 return function inlineExpression(x) {
15071 subScope[name] = x;
15072 return eq.eval(subScope);
15073 }
15074 };
15075}
15076
15077exports.factory = factory;
15078
15079
15080/***/ }),
15081/* 82 */
15082/***/ (function(module, exports, __webpack_require__) {
15083
15084"use strict";
15085
15086
15087
15088function factory (type, config, load, typed, math) {
15089 var parse = load(__webpack_require__(41));
15090 var ConstantNode = load(__webpack_require__(47));
15091 var FunctionNode = load(__webpack_require__(56));
15092 var OperatorNode = load(__webpack_require__(55));
15093 var ParenthesisNode = load(__webpack_require__(63));
15094 var SymbolNode = load(__webpack_require__(36));
15095 var Node = load(__webpack_require__(15));
15096 var simplifyConstant = load(__webpack_require__(120));
15097 var simplifyCore = load(__webpack_require__(122));
15098 var resolve = load(__webpack_require__(410));
15099
15100 var util = load(__webpack_require__(121));
15101 var isCommutative = util.isCommutative;
15102 var isAssociative = util.isAssociative;
15103 var flatten = util.flatten;
15104 var unflattenr = util.unflattenr;
15105 var unflattenl = util.unflattenl;
15106 var createMakeNodeFunction = util.createMakeNodeFunction;
15107
15108 /**
15109 * Simplify an expression tree.
15110 *
15111 * A list of rules are applied to an expression, repeating over the list until
15112 * no further changes are made.
15113 * It's possible to pass a custom set of rules to the function as second
15114 * argument. A rule can be specified as an object, string, or function:
15115 *
15116 * var rules = [
15117 * { l: 'n1*n3 + n2*n3', r: '(n1+n2)*n3' },
15118 * 'n1*n3 + n2*n3 -> (n1+n2)*n3',
15119 * function (node) {
15120 * // ... return a new node or return the node unchanged
15121 * return node
15122 * }
15123 * ]
15124 *
15125 * String and object rules consist of a left and right pattern. The left is
15126 * used to match against the expression and the right determines what matches
15127 * are replaced with. The main difference between a pattern and a normal
15128 * expression is that variables starting with the following characters are
15129 * interpreted as wildcards:
15130 *
15131 * - 'n' - matches any Node
15132 * - 'c' - matches any ConstantNode
15133 * - 'v' - matches any Node that is not a ConstantNode
15134 *
15135 * The default list of rules is exposed on the function as `simplify.rules`
15136 * and can be used as a basis to built a set of custom rules.
15137 *
15138 * For more details on the theory, see:
15139 *
15140 * - [Strategies for simplifying math expressions (Stackoverflow)](http://stackoverflow.com/questions/7540227/strategies-for-simplifying-math-expressions)
15141 * - [Symbolic computation - Simplification (Wikipedia)](https://en.wikipedia.org/wiki/Symbolic_computation#Simplification)
15142 *
15143 * Syntax:
15144 *
15145 * simplify(expr)
15146 * simplify(expr, rules)
15147 * simplify(expr, rules, scope)
15148 * simplify(expr, scope)
15149 *
15150 * Examples:
15151 *
15152 * math.simplify('2 * 1 * x ^ (2 - 1)'); // Node {2 * x}
15153 * math.simplify('2 * 3 * x', {x: 4}); // Node {24}
15154 * var f = math.parse('2 * 1 * x ^ (2 - 1)');
15155 * math.simplify(f); // Node {2 * x}
15156 *
15157 * See also:
15158 *
15159 * derivative, parse, eval
15160 *
15161 * @param {Node | string} expr
15162 * The expression to be simplified
15163 * @param {Array<{l:string, r: string} | string | function>} [rules]
15164 * Optional list with custom rules
15165 * @return {Node} Returns the simplified form of `expr`
15166 */
15167 var simplify = typed('simplify', {
15168 'string': function (expr) {
15169 return simplify(parse(expr), simplify.rules, {});
15170 },
15171
15172 'string, Object': function (expr, scope) {
15173 return simplify(parse(expr), simplify.rules, scope);
15174 },
15175
15176 'string, Array': function (expr, rules) {
15177 return simplify(parse(expr), rules, {});
15178 },
15179
15180 'string, Array, Object': function (expr, rules, scope) {
15181 return simplify(parse(expr), rules, scope);
15182 },
15183
15184 'Node, Object': function (expr, scope) {
15185 return simplify(expr, simplify.rules, scope);
15186 },
15187
15188 'Node': function (expr) {
15189 return simplify(expr, simplify.rules, {});
15190 },
15191
15192 'Node, Array': function (expr, rules) {
15193 return simplify(expr, rules, {});
15194 },
15195
15196 'Node, Array, Object': function (expr, rules, scope) {
15197 rules = _buildRules(rules);
15198
15199 var res = resolve(expr, scope);
15200 var res = removeParens(res);
15201 var visited = {};
15202
15203 var str = res.toString({parenthesis: 'all'});
15204 while(!visited[str]) {
15205 visited[str] = true;
15206 _lastsym = 0; // counter for placeholder symbols
15207 for (var i=0; i<rules.length; i++) {
15208 if (typeof rules[i] === 'function') {
15209 res = rules[i](res);
15210 }
15211 else {
15212 flatten(res);
15213 res = applyRule(res, rules[i]);
15214 }
15215 unflattenl(res); // using left-heavy binary tree here since custom rule functions may expect it
15216 }
15217 str = res.toString({parenthesis: 'all'});
15218 }
15219
15220 return res;
15221 }
15222 });
15223 simplify.simplifyCore = simplifyCore;
15224 simplify.resolve = resolve;
15225
15226 function removeParens(node) {
15227 return node.transform(function(node, path, parent) {
15228 return type.isParenthesisNode(node)
15229 ? node.content
15230 : node;
15231 });
15232 }
15233
15234 // All constants that are allowed in rules
15235 var SUPPORTED_CONSTANTS = {
15236 true: true,
15237 false: true,
15238 e: true,
15239 i: true,
15240 Infinity: true,
15241 LN2: true,
15242 LN10: true,
15243 LOG2E: true,
15244 LOG10E: true,
15245 NaN: true,
15246 phi: true,
15247 pi: true,
15248 SQRT1_2: true,
15249 SQRT2: true,
15250 tau: true,
15251 // null: false,
15252 // uninitialized: false,
15253 // version: false,
15254 };
15255
15256 // Array of strings, used to build the ruleSet.
15257 // Each l (left side) and r (right side) are parsed by
15258 // the expression parser into a node tree.
15259 // Left hand sides are matched to subtrees within the
15260 // expression to be parsed and replaced with the right
15261 // hand side.
15262 // TODO: Add support for constraints on constants (either in the form of a '=' expression or a callback [callback allows things like comparing symbols alphabetically])
15263 // 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.
15264 // It is possible to get into an infinite loop with conflicting rules
15265 simplify.rules = [
15266 simplifyCore,
15267 //{ l: 'n+0', r: 'n' }, // simplifyCore
15268 //{ l: 'n^0', r: '1' }, // simplifyCore
15269 //{ l: '0*n', r: '0' }, // simplifyCore
15270 //{ l: 'n/n', r: '1'}, // simplifyCore
15271 //{ l: 'n^1', r: 'n' }, // simplifyCore
15272 //{ l: '+n1', r:'n1' }, // simplifyCore
15273 //{ l: 'n--n1', r:'n+n1' }, // simplifyCore
15274 { l: 'log(e)', r:'1' },
15275
15276 // temporary rules
15277 { l: 'n-n1', r:'n+-n1' }, // temporarily replace 'subtract' so we can further flatten the 'add' operator
15278 { l: '-(c*v)', r: '(-c) * v' }, // make non-constant terms positive
15279 { l: '-v', r: '(-1) * v' },
15280 { l: 'n/n1^n2', r:'n*n1^-n2' }, // temporarily replace 'divide' so we can further flatten the 'multiply' operator
15281 { l: 'n/n1', r:'n*n1^-1' },
15282
15283 // expand nested exponentiation
15284 { l: '(n ^ n1) ^ n2', r: 'n ^ (n1 * n2)'},
15285
15286 // collect like factors
15287 { l: 'n*n', r: 'n^2' },
15288 { l: 'n * n^n1', r: 'n^(n1+1)' },
15289 { l: 'n^n1 * n^n2', r: 'n^(n1+n2)' },
15290
15291 // collect like terms
15292 { l: 'n+n', r: '2*n' },
15293 { l: 'n+-n', r: '0' },
15294 { l: 'n1*n2 + n2', r: '(n1+1)*n2' },
15295 { l: 'n1*n3 + n2*n3', r: '(n1+n2)*n3' },
15296
15297 // remove parenthesis in the case of negating a quantitiy
15298 { l: 'n1 + -1 * (n2 + n3)', r:'n1 + -1 * n2 + -1 * n3' },
15299
15300 simplifyConstant,
15301
15302 { l: '(-n)*n1', r: '-(n*n1)' }, // make factors positive (and undo 'make non-constant terms positive')
15303
15304 // ordering of constants
15305 { l: 'c+v', r: 'v+c', context: { 'add': { commutative:false } } },
15306 { l: 'v*c', r: 'c*v', context: { 'multiply': { commutative:false } } },
15307
15308 // undo temporary rules
15309 //{ l: '(-1) * n', r: '-n' }, // #811 added test which proved this is redundant
15310 { l: 'n+-n1', r:'n-n1' }, // undo replace 'subtract'
15311 { l: 'n*(n1^-1)', r:'n/n1' }, // undo replace 'divide'
15312 { l: 'n*n1^-n2', r:'n/n1^n2' },
15313 { l: 'n1^-1', r:'1/n1' },
15314
15315 { l: 'n*(n1/n2)', r:'(n*n1)/n2' }, // '*' before '/'
15316 { l: 'n-(n1+n2)', r:'n-n1-n2' }, // '-' before '+'
15317 // { l: '(n1/n2)/n3', r: 'n1/(n2*n3)' },
15318 // { l: '(n*n1)/(n*n2)', r: 'n1/n2' },
15319
15320 { l: '1*n', r: 'n' } // this pattern can be produced by simplifyConstant
15321
15322 ];
15323
15324 /**
15325 * Parse the string array of rules into nodes
15326 *
15327 * Example syntax for rules:
15328 *
15329 * Position constants to the left in a product:
15330 * { l: 'n1 * c1', r: 'c1 * n1' }
15331 * n1 is any Node, and c1 is a ConstantNode.
15332 *
15333 * Apply difference of squares formula:
15334 * { l: '(n1 - n2) * (n1 + n2)', r: 'n1^2 - n2^2' }
15335 * n1, n2 mean any Node.
15336 *
15337 * Short hand notation:
15338 * 'n1 * c1 -> c1 * n1'
15339 */
15340 function _buildRules(rules) {
15341 // Array of rules to be used to simplify expressions
15342 var ruleSet = [];
15343 for(var i=0; i<rules.length; i++) {
15344 var rule = rules[i];
15345 var newRule;
15346 var ruleType = typeof rule;
15347 switch (ruleType) {
15348 case 'string':
15349 var lr = rule.split('->');
15350 if (lr.length !== 2) {
15351 throw SyntaxError('Could not parse rule: ' + rule);
15352 }
15353 rule = {l: lr[0], r: lr[1]};
15354 /* falls through */
15355 case 'object':
15356 newRule = {
15357 l: removeParens(parse(rule.l)),
15358 r: removeParens(parse(rule.r)),
15359 }
15360 if(rule.context) {
15361 newRule.evaluate = rule.context;
15362 }
15363 if(rule.evaluate) {
15364 newRule.evaluate = parse(rule.evaluate);
15365 }
15366
15367 if (isAssociative(newRule.l)) {
15368 var makeNode = createMakeNodeFunction(newRule.l);
15369 var expandsym = _getExpandPlaceholderSymbol();
15370 newRule.expanded = {};
15371 newRule.expanded.l = makeNode([newRule.l.clone(), expandsym]);
15372 // Push the expandsym into the deepest possible branch.
15373 // This helps to match the newRule against nodes returned from getSplits() later on.
15374 flatten(newRule.expanded.l);
15375 unflattenr(newRule.expanded.l);
15376 newRule.expanded.r = makeNode([newRule.r, expandsym]);
15377 }
15378 break;
15379 case 'function':
15380 newRule = rule;
15381 break;
15382 default:
15383 throw TypeError('Unsupported type of rule: ' + ruleType);
15384 }
15385 // console.log('Adding rule: ' + rules[i]);
15386 // console.log(newRule);
15387 ruleSet.push(newRule);
15388 }
15389 return ruleSet;
15390 }
15391
15392 var _lastsym = 0;
15393 function _getExpandPlaceholderSymbol() {
15394 return new SymbolNode('_p' + _lastsym++);
15395 }
15396
15397 /**
15398 * Returns a simplfied form of node, or the original node if no simplification was possible.
15399 *
15400 * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
15401 * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The simplified form of `expr`, or the original node if no simplification was possible.
15402 */
15403 var applyRule = typed('applyRule', {
15404 'Node, Object': function (node, rule) {
15405
15406 //console.log('Entering applyRule(' + node.toString() + ')');
15407
15408 // Do not clone node unless we find a match
15409 var res = node;
15410
15411 // First replace our child nodes with their simplified versions
15412 // If a child could not be simplified, the assignments will have
15413 // no effect since the node is returned unchanged
15414 if (res instanceof OperatorNode || res instanceof FunctionNode) {
15415 if (res.args) {
15416 for(var i=0; i<res.args.length; i++) {
15417 res.args[i] = applyRule(res.args[i], rule);
15418 }
15419 }
15420 }
15421 else if(res instanceof ParenthesisNode) {
15422 if(res.content) {
15423 res.content = applyRule(res.content, rule);
15424 }
15425 }
15426
15427 // Try to match a rule against this node
15428 var repl = rule.r;
15429 var matches = _ruleMatch(rule.l, res)[0];
15430
15431 // If the rule is associative operator, we can try matching it while allowing additional terms.
15432 // 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.
15433 if (!matches && rule.expanded) {
15434 repl = rule.expanded.r;
15435 matches = _ruleMatch(rule.expanded.l, res)[0];
15436 }
15437
15438 if (matches) {
15439 // var before = res.toString({parenthesis: 'all'});
15440
15441 // Create a new node by cloning the rhs of the matched rule
15442 res = repl.clone();
15443
15444 // Replace placeholders with their respective nodes without traversing deeper into the replaced nodes
15445 var _transform = function(node) {
15446 if(node.isSymbolNode && matches.placeholders.hasOwnProperty(node.name)) {
15447 return matches.placeholders[node.name].clone();
15448 }
15449 else {
15450 return node.map(_transform);
15451 }
15452 }
15453
15454 res = _transform(res);
15455
15456 // var after = res.toString({parenthesis: 'all'});
15457 // console.log('Simplified ' + before + ' to ' + after);
15458 }
15459
15460 return res;
15461 }
15462 });
15463
15464 /**
15465 * Get (binary) combinations of a flattened binary node
15466 * e.g. +(node1, node2, node3) -> [
15467 * +(node1, +(node2, node3)),
15468 * +(node2, +(node1, node3)),
15469 * +(node3, +(node1, node2))]
15470 *
15471 */
15472 function getSplits(node, context) {
15473 var res = [];
15474 var right, rightArgs;
15475 var makeNode = createMakeNodeFunction(node);
15476 if (isCommutative(node, context)) {
15477 for (var i=0; i<node.args.length; i++) {
15478 rightArgs = node.args.slice(0);
15479 rightArgs.splice(i, 1);
15480 right = (rightArgs.length === 1) ? rightArgs[0] : makeNode(rightArgs);
15481 res.push(makeNode([node.args[i], right]));
15482 }
15483 }
15484 else {
15485 rightArgs = node.args.slice(1);
15486 right = (rightArgs.length === 1) ? rightArgs[0] : makeNode(rightArgs);
15487 res.push(makeNode([node.args[0], right]));
15488 }
15489 return res;
15490 }
15491
15492 /**
15493 * Returns the set union of two match-placeholders or null if there is a conflict.
15494 */
15495 function mergeMatch(match1, match2) {
15496 var res = {placeholders:{}};
15497
15498 // Some matches may not have placeholders; this is OK
15499 if (!match1.placeholders && !match2.placeholders) {
15500 return res;
15501 }
15502 else if (!match1.placeholders) {
15503 return match2;
15504 }
15505 else if (!match2.placeholders) {
15506 return match1;
15507 }
15508
15509 // Placeholders with the same key must match exactly
15510 for (var key in match1.placeholders) {
15511 res.placeholders[key] = match1.placeholders[key];
15512 if (match2.placeholders.hasOwnProperty(key)) {
15513 if (!_exactMatch(match1.placeholders[key], match2.placeholders[key] )) {
15514 return null;
15515 }
15516 }
15517 }
15518
15519 for (var key in match2.placeholders) {
15520 res.placeholders[key] = match2.placeholders[key];
15521 }
15522
15523 return res;
15524 }
15525
15526 /**
15527 * Combine two lists of matches by applying mergeMatch to the cartesian product of two lists of matches.
15528 * Each list represents matches found in one child of a node.
15529 */
15530 function combineChildMatches(list1, list2) {
15531 var res = [];
15532
15533 if (list1.length === 0 || list2.length === 0) {
15534 return res;
15535 }
15536
15537 var merged;
15538 for (var i1 = 0; i1 < list1.length; i1++) {
15539 for (var i2 = 0; i2 < list2.length; i2++) {
15540 merged = mergeMatch(list1[i1], list2[i2]);
15541 if (merged) {
15542 res.push(merged);
15543 }
15544 }
15545 }
15546 return res;
15547 }
15548
15549 /**
15550 * Combine multiple lists of matches by applying mergeMatch to the cartesian product of two lists of matches.
15551 * Each list represents matches found in one child of a node.
15552 * Returns a list of unique matches.
15553 */
15554 function mergeChildMatches(childMatches) {
15555 if (childMatches.length === 0) {
15556 return childMatches;
15557 }
15558
15559 var sets = childMatches.reduce(combineChildMatches);
15560 var uniqueSets = [];
15561 var unique = {};
15562 for(var i = 0; i < sets.length; i++) {
15563 var s = JSON.stringify(sets[i]);
15564 if (!unique[s]) {
15565 unique[s] = true;
15566 uniqueSets.push(sets[i]);
15567 }
15568 }
15569 return uniqueSets;
15570 }
15571
15572 /**
15573 * Determines whether node matches rule.
15574 *
15575 * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} rule
15576 * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
15577 * @return {Object} Information about the match, if it exists.
15578 */
15579 function _ruleMatch(rule, node, isSplit) {
15580// console.log('Entering _ruleMatch(' + JSON.stringify(rule) + ', ' + JSON.stringify(node) + ')');
15581// console.log('rule = ' + rule);
15582// console.log('node = ' + node);
15583
15584// console.log('Entering _ruleMatch(' + rule.toString() + ', ' + node.toString() + ')');
15585 var res = [{placeholders:{}}];
15586
15587 if (rule instanceof OperatorNode && node instanceof OperatorNode
15588 || rule instanceof FunctionNode && node instanceof FunctionNode) {
15589
15590 // If the rule is an OperatorNode or a FunctionNode, then node must match exactly
15591 if (rule instanceof OperatorNode) {
15592 if (rule.op !== node.op || rule.fn !== node.fn) {
15593 return [];
15594 }
15595 }
15596 else if (rule instanceof FunctionNode) {
15597 if (rule.name !== node.name) {
15598 return [];
15599 }
15600 }
15601
15602 // rule and node match. Search the children of rule and node.
15603 if (node.args.length === 1 && rule.args.length === 1 || !isAssociative(node) || isSplit) {
15604 // Expect non-associative operators to match exactly
15605 var childMatches = [];
15606 for (var i = 0; i < rule.args.length; i++) {
15607 var childMatch = _ruleMatch(rule.args[i], node.args[i]);
15608 if (childMatch.length === 0) {
15609 // Child did not match, so stop searching immediately
15610 return [];
15611 }
15612 // The child matched, so add the information returned from the child to our result
15613 childMatches.push(childMatch);
15614 }
15615 res = mergeChildMatches(childMatches);
15616 }
15617 else if (node.args.length >= 2 && rule.args.length === 2) { // node is flattened, rule is not
15618 // Associative operators/functions can be split in different ways so we check if the rule matches each
15619 // them and return their union.
15620 var splits = getSplits(node, rule.context);
15621 var splitMatches = [];
15622 for(var i = 0; i < splits.length; i++) {
15623 var matchSet = _ruleMatch(rule, splits[i], true); // recursing at the same tree depth here
15624 splitMatches = splitMatches.concat(matchSet);
15625 }
15626 return splitMatches;
15627 }
15628 else if (rule.args.length > 2) {
15629 throw Error('Unexpected non-binary associative function: ' + rule.toString());
15630 }
15631 else {
15632 // Incorrect number of arguments in rule and node, so no match
15633 return [];
15634 }
15635 }
15636 else if (rule instanceof SymbolNode) {
15637 // If the rule is a SymbolNode, then it carries a special meaning
15638 // according to the first character of the symbol node name.
15639 // c.* matches a ConstantNode
15640 // n.* matches any node
15641 if (rule.name.length === 0) {
15642 throw new Error('Symbol in rule has 0 length...!?');
15643 }
15644 if (math.hasOwnProperty(rule.name)) {
15645 if (!SUPPORTED_CONSTANTS[rule.name]) {
15646 throw new Error('Built in constant: ' + rule.name + ' is not supported by simplify.');
15647 }
15648
15649 // built-in constant must match exactly
15650 if(rule.name !== node.name) {
15651 return [];
15652 }
15653 }
15654 else if (rule.name[0] === 'n' || rule.name.substring(0,2) === '_p') {
15655 // rule matches _anything_, so assign this node to the rule.name placeholder
15656 // Assign node to the rule.name placeholder.
15657 // Our parent will check for matches among placeholders.
15658 res[0].placeholders[rule.name] = node;
15659 }
15660 else if (rule.name[0] === 'v') {
15661 // rule matches any variable thing (not a ConstantNode)
15662 if(!type.isConstantNode(node)) {
15663 res[0].placeholders[rule.name] = node;
15664 }
15665 else {
15666 // Mis-match: rule was expecting something other than a ConstantNode
15667 return [];
15668 }
15669 }
15670 else if (rule.name[0] === 'c') {
15671 // rule matches any ConstantNode
15672 if(node instanceof ConstantNode) {
15673 res[0].placeholders[rule.name] = node;
15674 }
15675 else {
15676 // Mis-match: rule was expecting a ConstantNode
15677 return [];
15678 }
15679 }
15680 else {
15681 throw new Error('Invalid symbol in rule: ' + rule.name);
15682 }
15683 }
15684 else if (rule instanceof ConstantNode) {
15685 // Literal constant must match exactly
15686 if(rule.value !== node.value) {
15687 return [];
15688 }
15689 }
15690 else {
15691 // Some other node was encountered which we aren't prepared for, so no match
15692 return [];
15693 }
15694
15695 // It's a match!
15696
15697 // console.log('_ruleMatch(' + rule.toString() + ', ' + node.toString() + ') found a match');
15698 return res;
15699 }
15700
15701
15702 /**
15703 * Determines whether p and q (and all their children nodes) are identical.
15704 *
15705 * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} p
15706 * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} q
15707 * @return {Object} Information about the match, if it exists.
15708 */
15709 function _exactMatch(p, q) {
15710 if(p instanceof ConstantNode && q instanceof ConstantNode) {
15711 if(p.value !== q.value) {
15712 return false;
15713 }
15714 }
15715 else if(p instanceof SymbolNode && q instanceof SymbolNode) {
15716 if(p.name !== q.name) {
15717 return false;
15718 }
15719 }
15720 else if(p instanceof OperatorNode && q instanceof OperatorNode
15721 || p instanceof FunctionNode && q instanceof FunctionNode) {
15722 if (p instanceof OperatorNode) {
15723 if (p.op !== q.op || p.fn !== q.fn) {
15724 return false;
15725 }
15726 }
15727 else if (p instanceof FunctionNode) {
15728 if (p.name !== q.name) {
15729 return false;
15730 }
15731 }
15732
15733 if(p.args.length !== q.args.length) {
15734 return false;
15735 }
15736
15737 for(var i=0; i<p.args.length; i++) {
15738 if(!_exactMatch(p.args[i], q.args[i])) {
15739 return false;
15740 }
15741 }
15742 }
15743 else {
15744 return false;
15745 }
15746
15747 return true;
15748 }
15749
15750 return simplify;
15751}
15752
15753exports.math = true;
15754exports.name = 'simplify';
15755exports.factory = factory;
15756
15757
15758/***/ }),
15759/* 83 */
15760/***/ (function(module, exports, __webpack_require__) {
15761
15762"use strict";
15763
15764
15765var deepMap = __webpack_require__(1);
15766var number = __webpack_require__(3);
15767
15768function factory (type, config, load, typed) {
15769 /**
15770 * Test whether a value is zero.
15771 * The function can check for zero for types `number`, `BigNumber`, `Fraction`,
15772 * `Complex`, and `Unit`.
15773 *
15774 * The function is evaluated element-wise in case of Array or Matrix input.
15775 *
15776 * Syntax:
15777 *
15778 * math.isZero(x)
15779 *
15780 * Examples:
15781 *
15782 * math.isZero(0); // returns true
15783 * math.isZero(2); // returns false
15784 * math.isZero(0.5); // returns false
15785 * math.isZero(math.bignumber(0)); // returns true
15786 * math.isZero(math.fraction(0)); // returns true
15787 * math.isZero(math.fraction(1,3)); // returns false
15788 * math.isZero(math.complex('2 - 4i'); // returns false
15789 * math.isZero(math.complex('0i'); // returns true
15790 * math.isZero('0'); // returns true
15791 * math.isZero('2'); // returns false
15792 * math.isZero([2, 0, -3]'); // returns [false, true, false]
15793 *
15794 * See also:
15795 *
15796 * isNumeric, isPositive, isNegative, isInteger
15797 *
15798 * @param {number | BigNumber | Complex | Fraction | Unit | Array | Matrix} x Value to be tested
15799 * @return {boolean} Returns true when `x` is zero.
15800 * Throws an error in case of an unknown data type.
15801 */
15802 var isZero = typed('isZero', {
15803 'number': function (x) {
15804 return x === 0;
15805 },
15806
15807 'BigNumber': function (x) {
15808 return x.isZero();
15809 },
15810
15811 'Complex': function (x) {
15812 return x.re === 0 && x.im === 0;
15813 },
15814
15815 'Fraction': function (x) {
15816 return x.d === 1 && x.n === 0;
15817 },
15818
15819 'Unit': function (x) {
15820 return isZero(x.value);
15821 },
15822
15823 'Array | Matrix': function (x) {
15824 return deepMap(x, isZero);
15825 }
15826 });
15827
15828 return isZero;
15829}
15830
15831exports.name = 'isZero';
15832exports.factory = factory;
15833
15834
15835/***/ }),
15836/* 84 */
15837/***/ (function(module, exports, __webpack_require__) {
15838
15839"use strict";
15840
15841
15842function factory () {
15843
15844 /**
15845 * This function "flips" its input about the integer -1.
15846 *
15847 * @param {Number} i The value to flip
15848 *
15849 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
15850 */
15851 var cs_flip = function (i) {
15852 // flip the value
15853 return -i - 2;
15854 };
15855
15856 return cs_flip;
15857}
15858
15859exports.name = 'cs_flip';
15860exports.path = 'sparse';
15861exports.factory = factory;
15862
15863
15864/***/ }),
15865/* 85 */
15866/***/ (function(module, exports, __webpack_require__) {
15867
15868"use strict";
15869
15870
15871var util = __webpack_require__(25);
15872
15873var string = util.string;
15874var array = util.array;
15875
15876var isArray = Array.isArray;
15877
15878function factory (type) {
15879
15880 var DenseMatrix = type.DenseMatrix;
15881
15882 /**
15883 * Validates matrix and column vector b for backward/forward substitution algorithms.
15884 *
15885 * @param {Matrix} m An N x N matrix
15886 * @param {Array | Matrix} b A column vector
15887 * @param {Boolean} copy Return a copy of vector b
15888 *
15889 * @return {DenseMatrix} Dense column vector b
15890 */
15891 var solveValidation = function (m, b, copy) {
15892 // matrix size
15893 var size = m.size();
15894 // validate matrix dimensions
15895 if (size.length !== 2)
15896 throw new RangeError('Matrix must be two dimensional (size: ' + string.format(size) + ')');
15897 // rows & columns
15898 var rows = size[0];
15899 var columns = size[1];
15900 // validate rows & columns
15901 if (rows !== columns)
15902 throw new RangeError('Matrix must be square (size: ' + string.format(size) + ')');
15903 // vars
15904 var data, i, bdata;
15905 // check b is matrix
15906 if (type.isMatrix(b)) {
15907 // matrix size
15908 var msize = b.size();
15909 // vector
15910 if (msize.length === 1) {
15911 // check vector length
15912 if (msize[0] !== rows)
15913 throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
15914 // create data array
15915 data = [];
15916 // matrix data (DenseMatrix)
15917 bdata = b._data;
15918 // loop b data
15919 for (i = 0; i < rows; i++) {
15920 // row array
15921 data[i] = [bdata[i]];
15922 }
15923 // return Dense Matrix
15924 return new DenseMatrix({
15925 data: data,
15926 size: [rows, 1],
15927 datatype: b._datatype
15928 });
15929 }
15930 // two dimensions
15931 if (msize.length === 2) {
15932 // array must be a column vector
15933 if (msize[0] !== rows || msize[1] !== 1)
15934 throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
15935 // check matrix type
15936 if (type.isDenseMatrix(b)) {
15937 // check a copy is needed
15938 if (copy) {
15939 // create data array
15940 data = [];
15941 // matrix data (DenseMatrix)
15942 bdata = b._data;
15943 // loop b data
15944 for (i = 0; i < rows; i++) {
15945 // row array
15946 data[i] = [bdata[i][0]];
15947 }
15948 // return Dense Matrix
15949 return new DenseMatrix({
15950 data: data,
15951 size: [rows, 1],
15952 datatype: b._datatype
15953 });
15954 }
15955 // b is already a column vector
15956 return b;
15957 }
15958 // create data array
15959 data = [];
15960 for (i = 0; i < rows; i++)
15961 data[i] = [0];
15962 // sparse matrix arrays
15963 var values = b._values;
15964 var index = b._index;
15965 var ptr = b._ptr;
15966 // loop values in column 0
15967 for (var k1 = ptr[1], k = ptr[0]; k < k1; k++) {
15968 // row
15969 i = index[k];
15970 // add to data
15971 data[i][0] = values[k];
15972 }
15973 // return Dense Matrix
15974 return new DenseMatrix({
15975 data: data,
15976 size: [rows, 1],
15977 datatype: b._datatype
15978 });
15979 }
15980 // throw error
15981 throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
15982 }
15983 // check b is array
15984 if (isArray(b)) {
15985 // size
15986 var asize = array.size(b);
15987 // check matrix dimensions, vector
15988 if (asize.length === 1) {
15989 // check vector length
15990 if (asize[0] !== rows)
15991 throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
15992 // create data array
15993 data = [];
15994 // loop b
15995 for (i = 0; i < rows; i++) {
15996 // row array
15997 data[i] = [b[i]];
15998 }
15999 // return Dense Matrix
16000 return new DenseMatrix({
16001 data: data,
16002 size: [rows, 1]
16003 });
16004 }
16005 if (asize.length === 2) {
16006 // array must be a column vector
16007 if (asize[0] !== rows || asize[1] !== 1)
16008 throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
16009 // create data array
16010 data = [];
16011 // loop b data
16012 for (i = 0; i < rows; i++) {
16013 // row array
16014 data[i] = [b[i][0]];
16015 }
16016 // return Dense Matrix
16017 return new DenseMatrix({
16018 data: data,
16019 size: [rows, 1]
16020 });
16021 }
16022 // throw error
16023 throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
16024 }
16025 };
16026
16027 return solveValidation;
16028}
16029
16030exports.factory = factory;
16031
16032/***/ }),
16033/* 86 */
16034/***/ (function(module, exports, __webpack_require__) {
16035
16036var bitNot = __webpack_require__(87);
16037
16038/**
16039 * Applies bitwise function to numbers
16040 * @param {BigNumber} x
16041 * @param {BigNumber} y
16042 * @param {function (a, b)} func
16043 * @return {BigNumber}
16044 */
16045module.exports = function bitwise(x, y, func) {
16046 var BigNumber = x.constructor;
16047
16048 var xBits, yBits;
16049 var xSign = +(x.s < 0);
16050 var ySign = +(y.s < 0);
16051 if (xSign) {
16052 xBits = decCoefficientToBinaryString(bitNot(x));
16053 for (var i = 0; i < xBits.length; ++i) {
16054 xBits[i] ^= 1;
16055 }
16056 } else {
16057 xBits = decCoefficientToBinaryString(x);
16058 }
16059 if (ySign) {
16060 yBits = decCoefficientToBinaryString(bitNot(y));
16061 for (var i = 0; i < yBits.length; ++i) {
16062 yBits[i] ^= 1;
16063 }
16064 } else {
16065 yBits = decCoefficientToBinaryString(y);
16066 }
16067
16068 var minBits, maxBits, minSign;
16069 if (xBits.length <= yBits.length) {
16070 minBits = xBits;
16071 maxBits = yBits;
16072 minSign = xSign;
16073 } else {
16074 minBits = yBits;
16075 maxBits = xBits;
16076 minSign = ySign;
16077 }
16078
16079 var shortLen = minBits.length;
16080 var longLen = maxBits.length;
16081 var expFuncVal = func(xSign, ySign) ^ 1;
16082 var outVal = new BigNumber(expFuncVal ^ 1);
16083 var twoPower = new BigNumber(1);
16084 var two = new BigNumber(2);
16085
16086 var prevPrec = BigNumber.precision;
16087 BigNumber.config({precision: 1E9});
16088
16089 while (shortLen > 0) {
16090 if (func(minBits[--shortLen], maxBits[--longLen]) == expFuncVal) {
16091 outVal = outVal.plus(twoPower);
16092 }
16093 twoPower = twoPower.times(two);
16094 }
16095 while (longLen > 0) {
16096 if (func(minSign, maxBits[--longLen]) == expFuncVal) {
16097 outVal = outVal.plus(twoPower);
16098 }
16099 twoPower = twoPower.times(two);
16100 }
16101
16102 BigNumber.config({precision: prevPrec});
16103
16104 if (expFuncVal == 0) {
16105 outVal.s = -outVal.s;
16106 }
16107 return outVal;
16108};
16109
16110/* Extracted from decimal.js, and edited to specialize. */
16111function decCoefficientToBinaryString (x) {
16112 // Convert to string
16113 var a = x.d; // array with digits
16114 var r = a[0] + '';
16115
16116 for (var i = 1; i < a.length; ++i) {
16117 var s = a[i] + '';
16118 for (var z = 7 - s.length; z--; ) {
16119 s = '0' + s;
16120 }
16121
16122 r += s;
16123 }
16124
16125 var j;
16126 for (j = r.length - 1; r.charAt(j) == '0'; --j);
16127
16128 var xe = x.e;
16129 var str = r.slice(0, j + 1 || 1);
16130 var strL = str.length;
16131 if (xe > 0) {
16132 if (++xe > strL) {
16133 // Append zeros.
16134 for (xe -= strL; xe--; str += '0');
16135 } else if (xe < strL) {
16136 str = str.slice(0, xe) + '.' + str.slice(xe);
16137 }
16138 }
16139
16140 // Convert from base 10 (decimal) to base 2
16141 var arr = [0];
16142 for (var i = 0; i < str.length; ) {
16143 for (var arrL = arr.length; arrL--; arr[arrL] *= 10);
16144
16145 arr[0] += str.charAt(i++) << 0; // convert to int
16146 for (var j = 0; j < arr.length; ++j) {
16147 if (arr[j] > 1) {
16148 if (arr[j + 1] == null) {
16149 arr[j + 1] = 0;
16150 }
16151
16152 arr[j + 1] += arr[j] >> 1;
16153 arr[j] &= 1;
16154 }
16155 }
16156 }
16157
16158 return arr.reverse();
16159}
16160
16161
16162/***/ }),
16163/* 87 */
16164/***/ (function(module, exports) {
16165
16166/**
16167 * Bitwise not
16168 * @param {BigNumber} value
16169 * @return {BigNumber} Result of ~`x`, fully precise
16170 *
16171 */
16172module.exports = function bitNot (x) {
16173 if (x.isFinite() && !x.isInteger()) {
16174 throw new Error('Integer expected in function bitNot');
16175 }
16176
16177 var BigNumber = x.constructor;
16178 var prevPrec = BigNumber.precision;
16179 BigNumber.config({precision: 1E9});
16180
16181 var x = x.plus(new BigNumber(1));
16182 x.s = -x.s || null;
16183
16184 BigNumber.config({precision: prevPrec});
16185 return x;
16186};
16187
16188
16189/***/ }),
16190/* 88 */
16191/***/ (function(module, exports, __webpack_require__) {
16192
16193"use strict";
16194
16195
16196var DimensionError = __webpack_require__(11);
16197
16198function factory (type, config, load, typed) {
16199
16200 var equalScalar = load(__webpack_require__(10));
16201
16202 var SparseMatrix = type.SparseMatrix;
16203
16204 /**
16205 * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij).
16206 * Callback function invoked MAX(NNZA, NNZB) times
16207 *
16208 *
16209 * ┌ f(Aij, Bij) ; A(i,j) !== 0 && B(i,j) !== 0
16210 * C(i,j) = ┤ A(i,j) ; A(i,j) !== 0
16211 * └ 0 ; otherwise
16212 *
16213 *
16214 * @param {Matrix} a The SparseMatrix instance (A)
16215 * @param {Matrix} b The SparseMatrix instance (B)
16216 * @param {Function} callback The f(Aij,Bij) operation to invoke
16217 *
16218 * @return {Matrix} SparseMatrix (C)
16219 *
16220 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
16221 */
16222 var algorithm08 = function (a, b, callback) {
16223 // sparse matrix arrays
16224 var avalues = a._values;
16225 var aindex = a._index;
16226 var aptr = a._ptr;
16227 var asize = a._size;
16228 var adt = a._datatype;
16229 // sparse matrix arrays
16230 var bvalues = b._values;
16231 var bindex = b._index;
16232 var bptr = b._ptr;
16233 var bsize = b._size;
16234 var bdt = b._datatype;
16235
16236 // validate dimensions
16237 if (asize.length !== bsize.length)
16238 throw new DimensionError(asize.length, bsize.length);
16239
16240 // check rows & columns
16241 if (asize[0] !== bsize[0] || asize[1] !== bsize[1])
16242 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
16243
16244 // sparse matrix cannot be a Pattern matrix
16245 if (!avalues || !bvalues)
16246 throw new Error('Cannot perform operation on Pattern Sparse Matrices');
16247
16248 // rows & columns
16249 var rows = asize[0];
16250 var columns = asize[1];
16251
16252 // datatype
16253 var dt;
16254 // equal signature to use
16255 var eq = equalScalar;
16256 // zero value
16257 var zero = 0;
16258 // callback signature to use
16259 var cf = callback;
16260
16261 // process data types
16262 if (typeof adt === 'string' && adt === bdt) {
16263 // datatype
16264 dt = adt;
16265 // find signature that matches (dt, dt)
16266 eq = typed.find(equalScalar, [dt, dt]);
16267 // convert 0 to the same datatype
16268 zero = typed.convert(0, dt);
16269 // callback
16270 cf = typed.find(callback, [dt, dt]);
16271 }
16272
16273 // result arrays
16274 var cvalues = [];
16275 var cindex = [];
16276 var cptr = [];
16277 // matrix
16278 var c = new SparseMatrix({
16279 values: cvalues,
16280 index: cindex,
16281 ptr: cptr,
16282 size: [rows, columns],
16283 datatype: dt
16284 });
16285
16286 // workspace
16287 var x = [];
16288 // marks indicating we have a value in x for a given column
16289 var w = [];
16290
16291 // vars
16292 var k, k0, k1, i;
16293
16294 // loop columns
16295 for (var j = 0; j < columns; j++) {
16296 // update cptr
16297 cptr[j] = cindex.length;
16298 // columns mark
16299 var mark = j + 1;
16300 // loop values in a
16301 for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
16302 // row
16303 i = aindex[k];
16304 // mark workspace
16305 w[i] = mark;
16306 // set value
16307 x[i] = avalues[k];
16308 // add index
16309 cindex.push(i);
16310 }
16311 // loop values in b
16312 for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
16313 // row
16314 i = bindex[k];
16315 // check value exists in workspace
16316 if (w[i] === mark) {
16317 // evaluate callback
16318 x[i] = cf(x[i], bvalues[k]);
16319 }
16320 }
16321 // initialize first index in j
16322 k = cptr[j];
16323 // loop index in j
16324 while (k < cindex.length) {
16325 // row
16326 i = cindex[k];
16327 // value @ i
16328 var v = x[i];
16329 // check for zero value
16330 if (!eq(v, zero)) {
16331 // push value
16332 cvalues.push(v);
16333 // increment pointer
16334 k++;
16335 }
16336 else {
16337 // remove value @ i, do not increment pointer
16338 cindex.splice(k, 1);
16339 }
16340 }
16341 }
16342 // update cptr
16343 cptr[columns] = cindex.length;
16344
16345 // return sparse matrix
16346 return c;
16347 };
16348
16349 return algorithm08;
16350}
16351
16352exports.name = 'algorithm08';
16353exports.factory = factory;
16354
16355
16356/***/ }),
16357/* 89 */
16358/***/ (function(module, exports, __webpack_require__) {
16359
16360"use strict";
16361
16362
16363var isInteger = __webpack_require__(3).isInteger;
16364
16365function factory (type, config, load, typed) {
16366 var asc = load(__webpack_require__(52));
16367 function desc(a, b) {
16368 return -asc(a, b);
16369 }
16370
16371 /**
16372 * Partition-based selection of an array or 1D matrix.
16373 * Will find the kth smallest value, and mutates the input array.
16374 * Uses Quickselect.
16375 *
16376 * Syntax:
16377 *
16378 * math.partitionSelect(x, k)
16379 * math.partitionSelect(x, k, compare)
16380 *
16381 * Examples:
16382 *
16383 * math.partitionSelect([5, 10, 1], 2); // returns 10
16384 * math.partitionSelect(['C', 'B', 'A', 'D'], 1); // returns 'B'
16385 *
16386 * function sortByLength (a, b) {
16387 * return a.length - b.length;
16388 * }
16389 * math.partitionSelect(['Langdon', 'Tom', 'Sara'], 2, sortByLength); // returns 'Langdon'
16390 *
16391 * See also:
16392 *
16393 * sort
16394 *
16395 * @param {Matrix | Array} x A one dimensional matrix or array to sort
16396 * @param {Number} k The kth smallest value to be retrieved; zero-based index
16397 * @param {Function | 'asc' | 'desc'} [compare='asc']
16398 * An optional comparator function. The function is called as
16399 * `compare(a, b)`, and must return 1 when a > b, -1 when a < b,
16400 * and 0 when a == b.
16401 * @return {*} Returns the kth lowest value.
16402 */
16403 return typed('partitionSelect', {
16404 'Array | Matrix, number': function (x, k) {
16405 return _partitionSelect(x, k, asc);
16406 },
16407
16408 'Array | Matrix, number, string': function (x, k, compare) {
16409 if (compare === 'asc') {
16410 return _partitionSelect(x, k, asc);
16411 }
16412 else if (compare === 'desc') {
16413 return _partitionSelect(x, k, desc);
16414 }
16415 else {
16416 throw new Error('Compare string must be "asc" or "desc"');
16417 }
16418 },
16419
16420 'Array | Matrix, number, function': _partitionSelect
16421 });
16422
16423 function _partitionSelect(x, k, compare) {
16424 if (!isInteger(k) || k < 0) {
16425 throw new Error('k must be a non-negative integer');
16426 }
16427
16428 if (type.isMatrix(x)) {
16429 var size = x.size();
16430 if (size.length > 1) {
16431 throw new Error('Only one dimensional matrices supported');
16432 }
16433 return quickSelect(x.valueOf(), k, compare);
16434 }
16435
16436 if (Array.isArray(x)) {
16437 return quickSelect(x, k, compare);
16438 }
16439 }
16440
16441 /**
16442 * Quickselect algorithm.
16443 * Code adapted from:
16444 * http://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html
16445 *
16446 * @param {Array} arr
16447 * @param {Number} k
16448 * @param {Function} compare
16449 * @private
16450 */
16451 function quickSelect(arr, k, compare) {
16452 if (k >= arr.length) {
16453 throw new Error('k out of bounds');
16454 }
16455
16456 var from = 0;
16457 var to = arr.length - 1;
16458
16459 // if from == to we reached the kth element
16460 while (from < to) {
16461 var r = from;
16462 var w = to;
16463 var pivot = arr[Math.floor(Math.random() * (to - from + 1)) + from];
16464
16465 // stop if the reader and writer meets
16466 while (r < w) {
16467 // arr[r] >= pivot
16468 if (compare(arr[r], pivot) >= 0) { // put the large values at the end
16469 var tmp = arr[w];
16470 arr[w] = arr[r];
16471 arr[r] = tmp;
16472 --w;
16473 } else { // the value is smaller than the pivot, skip
16474 ++r;
16475 }
16476 }
16477
16478 // if we stepped up (r++) we need to step one down (arr[r] > pivot)
16479 if (compare(arr[r], pivot) > 0) {
16480 --r;
16481 }
16482
16483 // the r pointer is on the end of the first k elements
16484 if (k <= r) {
16485 to = r;
16486 } else {
16487 from = r + 1;
16488 }
16489 }
16490
16491 return arr[k];
16492 }
16493}
16494
16495exports.name = 'partitionSelect';
16496exports.factory = factory;
16497
16498
16499/***/ }),
16500/* 90 */
16501/***/ (function(module, exports, __webpack_require__) {
16502
16503"use strict";
16504
16505
16506var ArgumentsError = __webpack_require__(44);
16507var isCollection = __webpack_require__(48);
16508var isNumber = __webpack_require__(3).isNumber;
16509
16510// TODO: rethink math.distribution
16511// TODO: rework to a typed function
16512function factory (type, config, load, typed, math) {
16513 var matrix = load(__webpack_require__(0));
16514 var array = __webpack_require__(2);
16515
16516 // seeded pseudo random number generator
16517 var rng = load(__webpack_require__(493));
16518
16519 /**
16520 * Create a distribution object with a set of random functions for given
16521 * random distribution.
16522 *
16523 * Syntax:
16524 *
16525 * math.distribution(name)
16526 *
16527 * Examples:
16528 *
16529 * var normalDist = math.distribution('normal'); // create a normal distribution
16530 * normalDist.random(0, 10); // get a random value between 0 and 10
16531 *
16532 * See also:
16533 *
16534 * random, randomInt, pickRandom
16535 *
16536 * @param {string} name Name of a distribution. Choose from 'uniform', 'normal'.
16537 * @return {Object} Returns a distribution object containing functions:
16538 * `random([size] [, min] [, max])`,
16539 * `randomInt([min] [, max])`,
16540 * `pickRandom(array)`
16541 */
16542 function distribution(name) {
16543 if (!distributions.hasOwnProperty(name))
16544 throw new Error('Unknown distribution ' + name);
16545
16546 var args = Array.prototype.slice.call(arguments, 1),
16547 distribution = distributions[name].apply(this, args);
16548
16549 return (function(distribution) {
16550
16551 // This is the public API for all distributions
16552 var randFunctions = {
16553
16554 random: function(arg1, arg2, arg3) {
16555 var size, min, max;
16556
16557 if (arguments.length > 3) {
16558 throw new ArgumentsError('random', arguments.length, 0, 3);
16559 } else if (arguments.length === 1) {
16560 // `random(max)` or `random(size)`
16561 if (isCollection(arg1)) {
16562 size = arg1;
16563 } else {
16564 max = arg1;
16565 }
16566 } else if (arguments.length === 2) {
16567 // `random(min, max)` or `random(size, max)`
16568 if (isCollection(arg1)) {
16569 size = arg1;
16570 max = arg2;
16571 } else {
16572 min = arg1;
16573 max = arg2;
16574 }
16575 } else {
16576 // `random(size, min, max)`
16577 size = arg1;
16578 min = arg2;
16579 max = arg3;
16580 }
16581
16582 // TODO: validate type of size
16583 if ((min !== undefined && !isNumber(min)) || (max !== undefined && !isNumber(max))) {
16584 throw new TypeError('Invalid argument in function random');
16585 }
16586
16587 if (max === undefined) max = 1;
16588 if (min === undefined) min = 0;
16589 if (size !== undefined) {
16590 var res = _randomDataForMatrix(size.valueOf(), min, max, _random);
16591 return type.isMatrix(size) ? matrix(res) : res;
16592 }
16593 return _random(min, max);
16594 },
16595
16596 randomInt: typed({
16597 'number | Array': function(arg) {
16598 var min = 0;
16599
16600 if (isCollection(arg)) {
16601 var size = arg;
16602 var max = 1;
16603 var res = _randomDataForMatrix(size.valueOf(), min, max, _randomInt);
16604 return type.isMatrix(size) ? matrix(res) : res;
16605 } else {
16606 var max = arg;
16607 return _randomInt(min, max);
16608 }
16609 },
16610 'number | Array, number': function(arg1, arg2) {
16611 if (isCollection(arg1)) {
16612 var size = arg1;
16613 var max = arg2;
16614 var min = 0;
16615 var res = _randomDataForMatrix(size.valueOf(), min, max, _randomInt);
16616 return type.isMatrix(size) ? matrix(res) : res;
16617 }
16618 else {
16619 var min = arg1;
16620 var max = arg2;
16621 return _randomInt(min, max);
16622 }
16623 },
16624 'Array, number, number': function(size, min, max) {
16625 var res = _randomDataForMatrix(size.valueOf(), min, max, _randomInt);
16626 return (size && size.isMatrix === true) ? matrix(res) : res;
16627 }
16628 }),
16629
16630 pickRandom: typed({
16631 'Array': function(possibles) {
16632 return _pickRandom(possibles);
16633 },
16634 'Array, number | Array': function(possibles, arg2) {
16635 var number, weights;
16636
16637 if (Array.isArray(arg2)) {
16638 weights = arg2;
16639 } else if (isNumber(arg2)) {
16640 number = arg2;
16641 } else {
16642 throw new TypeError('Invalid argument in function pickRandom')
16643 }
16644
16645 return _pickRandom(possibles, number, weights);
16646 },
16647 'Array, number | Array, Array | number': function(possibles, arg2, arg3) {
16648 var number, weights;
16649
16650 if (Array.isArray(arg2)) {
16651 weights = arg2;
16652 number = arg3;
16653 } else {
16654 weights = arg3;
16655 number = arg2;
16656 }
16657
16658 if (!Array.isArray(weights) || !isNumber(number)) {
16659 throw new TypeError('Invalid argument in function pickRandom');
16660 }
16661
16662 return _pickRandom(possibles, number, weights);
16663 }
16664 })
16665 }
16666
16667 var _pickRandom = function(possibles, number, weights) {
16668 var single = (typeof number === 'undefined');
16669
16670 if (single) {
16671 number = 1;
16672 }
16673
16674 if (type.isMatrix(possibles)) {
16675 possibles = possibles.valueOf(); // get Array
16676 } else if (!Array.isArray(possibles)) {
16677 throw new TypeError('Unsupported type of value in function pickRandom');
16678 }
16679
16680 if (array.size(possibles).length > 1) {
16681 throw new Error('Only one dimensional vectors supported');
16682 }
16683
16684 if (typeof weights !== 'undefined') {
16685 if (weights.length != possibles.length) {
16686 throw new Error('Weights must have the same length as possibles');
16687 }
16688
16689 var totalWeights = 0;
16690
16691 for (var i = 0, len = weights.length; i < len; i++) {
16692 if (!isNumber(weights[i]) || weights[i] < 0) {
16693 throw new Error('Weights must be an array of positive numbers');
16694 }
16695
16696 totalWeights += weights[i];
16697 }
16698 }
16699
16700 var length = possibles.length;
16701
16702 if (length == 0) {
16703 return [];
16704 } else if (number >= length) {
16705 return number > 1 ? possibles : possibles[0];
16706 }
16707
16708 var result = [];
16709 var pick;
16710
16711 while (result.length < number) {
16712 if (typeof weights === 'undefined') {
16713 pick = possibles[Math.floor(rng() * length)];
16714 } else {
16715 var randKey = rng() * totalWeights;
16716
16717 for (var i = 0, len = possibles.length; i < len; i++) {
16718 randKey -= weights[i];
16719
16720 if (randKey < 0) {
16721 pick = possibles[i];
16722 break;
16723 }
16724 }
16725 }
16726
16727 if (result.indexOf(pick) == -1) {
16728 result.push(pick);
16729 }
16730 }
16731
16732 return single ? result[0] : result;
16733
16734 // TODO: add support for multi dimensional matrices
16735 }
16736
16737 var _random = function(min, max) {
16738 return min + distribution() * (max - min);
16739 };
16740
16741 var _randomInt = function(min, max) {
16742 return Math.floor(min + distribution() * (max - min));
16743 };
16744
16745 // This is a function for generating a random matrix recursively.
16746 var _randomDataForMatrix = function(size, min, max, randFunc) {
16747 var data = [], length, i;
16748 size = size.slice(0);
16749
16750 if (size.length > 1) {
16751 for (var i = 0, length = size.shift(); i < length; i++) {
16752 data.push(_randomDataForMatrix(size, min, max, randFunc));
16753 }
16754 } else {
16755 for (var i = 0, length = size.shift(); i < length; i++) {
16756 data.push(randFunc(min, max));
16757 }
16758 }
16759
16760 return data;
16761 };
16762
16763 return randFunctions;
16764
16765 })(distribution);
16766 }
16767
16768 // Each distribution is a function that takes no argument and when called returns
16769 // a number between 0 and 1.
16770 var distributions = {
16771
16772 uniform: function() {
16773 return rng;
16774 },
16775
16776 // Implementation of normal distribution using Box-Muller transform
16777 // ref : http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
16778 // We take : mean = 0.5, standard deviation = 1/6
16779 // so that 99.7% values are in [0, 1].
16780 normal: function() {
16781 return function() {
16782 var u1, u2,
16783 picked = -1;
16784 // We reject values outside of the interval [0, 1]
16785 // TODO: check if it is ok to do that?
16786 while (picked < 0 || picked > 1) {
16787 u1 = rng();
16788 u2 = rng();
16789 picked = 1/6 * Math.pow(-2 * Math.log(u1), 0.5) * Math.cos(2 * Math.PI * u2) + 0.5;
16790 }
16791 return picked;
16792 }
16793 }
16794 };
16795
16796 distribution.toTex = undefined; // use default template
16797
16798 return distribution;
16799}
16800
16801exports.name = 'distribution';
16802exports.factory = factory;
16803
16804
16805/***/ }),
16806/* 91 */
16807/***/ (function(module, exports, __webpack_require__) {
16808
16809var Emitter = __webpack_require__(156);
16810
16811/**
16812 * Extend given object with emitter functions `on`, `off`, `once`, `emit`
16813 * @param {Object} obj
16814 * @return {Object} obj
16815 */
16816exports.mixin = function (obj) {
16817 // create event emitter
16818 var emitter = new Emitter();
16819
16820 // bind methods to obj (we don't want to expose the emitter.e Array...)
16821 obj.on = emitter.on.bind(emitter);
16822 obj.off = emitter.off.bind(emitter);
16823 obj.once = emitter.once.bind(emitter);
16824 obj.emit = emitter.emit.bind(emitter);
16825
16826 return obj;
16827};
16828
16829
16830/***/ }),
16831/* 92 */
16832/***/ (function(module, exports, __webpack_require__) {
16833
16834var Complex = __webpack_require__(171);
16835var format = __webpack_require__(3).format;
16836var isNumber = __webpack_require__(3).isNumber;
16837
16838function factory (type, config, load, typed, math) {
16839
16840 /**
16841 * Attach type information
16842 */
16843 Complex.prototype.type = 'Complex';
16844 Complex.prototype.isComplex = true;
16845
16846
16847 /**
16848 * Get a JSON representation of the complex number
16849 * @returns {Object} Returns a JSON object structured as:
16850 * `{"mathjs": "Complex", "re": 2, "im": 3}`
16851 */
16852 Complex.prototype.toJSON = function () {
16853 return {
16854 mathjs: 'Complex',
16855 re: this.re,
16856 im: this.im
16857 };
16858 };
16859
16860 /*
16861 * Return the value of the complex number in polar notation
16862 * The angle phi will be set in the interval of [-pi, pi].
16863 * @return {{r: number, phi: number}} Returns and object with properties r and phi.
16864 */
16865 Complex.prototype.toPolar = function () {
16866 return {
16867 r: this.abs(),
16868 phi: this.arg()
16869 };
16870 };
16871
16872 /**
16873 * Get a string representation of the complex number,
16874 * with optional formatting options.
16875 * @param {Object | number | Function} [options] Formatting options. See
16876 * lib/utils/number:format for a
16877 * description of the available
16878 * options.
16879 * @return {string} str
16880 */
16881 Complex.prototype.format = function (options) {
16882 var str = '';
16883 var im = this.im;
16884 var re = this.re;
16885 var strRe = format(this.re, options);
16886 var strIm = format(this.im, options);
16887
16888 // round either re or im when smaller than the configured precision
16889 var precision = isNumber(options) ? options : options ? options.precision : null;
16890 if (precision !== null) {
16891 var epsilon = Math.pow(10, -precision);
16892 if (Math.abs(re / im) < epsilon) {
16893 re = 0;
16894 }
16895 if (Math.abs(im / re) < epsilon) {
16896 im = 0;
16897 }
16898 }
16899
16900 if (im == 0) {
16901 // real value
16902 str = strRe;
16903 } else if (re == 0) {
16904 // purely complex value
16905 if (im == 1) {
16906 str = 'i';
16907 } else if (im == -1) {
16908 str = '-i';
16909 } else {
16910 str = strIm + 'i';
16911 }
16912 } else {
16913 // complex value
16914 if (im < 0) {
16915 if (im == -1) {
16916 str = strRe + ' - i';
16917 } else {
16918 str = strRe + ' - ' + strIm.substring(1) + 'i';
16919 }
16920 } else {
16921 if (im == 1) {
16922 str = strRe + ' + i';
16923 } else {
16924 str = strRe + ' + ' + strIm + 'i';
16925 }
16926 }
16927 }
16928 return str;
16929 };
16930
16931 /**
16932 * Create a complex number from polar coordinates
16933 *
16934 * Usage:
16935 *
16936 * Complex.fromPolar(r: number, phi: number) : Complex
16937 * Complex.fromPolar({r: number, phi: number}) : Complex
16938 *
16939 * @param {*} args...
16940 * @return {Complex}
16941 */
16942 Complex.fromPolar = function (args) {
16943 switch (arguments.length) {
16944 case 1:
16945 var arg = arguments[0];
16946 if (typeof arg === 'object') {
16947 return Complex(arg);
16948 }
16949 throw new TypeError('Input has to be an object with r and phi keys.');
16950
16951 case 2:
16952 var r = arguments[0],
16953 phi = arguments[1];
16954 if (isNumber(r)) {
16955 if (type.isUnit(phi) && phi.hasBase('ANGLE')) {
16956 // convert unit to a number in radians
16957 phi = phi.toNumber('rad');
16958 }
16959
16960 if (isNumber(phi)) {
16961 return new Complex({r: r, phi: phi});
16962 }
16963
16964 throw new TypeError('Phi is not a number nor an angle unit.');
16965 } else {
16966 throw new TypeError('Radius r is not a number.');
16967 }
16968
16969 default:
16970 throw new SyntaxError('Wrong number of arguments in function fromPolar');
16971 }
16972 };
16973
16974
16975 Complex.prototype.valueOf = Complex.prototype.toString;
16976
16977 /**
16978 * Create a Complex number from a JSON object
16979 * @param {Object} json A JSON Object structured as
16980 * {"mathjs": "Complex", "re": 2, "im": 3}
16981 * All properties are optional, default values
16982 * for `re` and `im` are 0.
16983 * @return {Complex} Returns a new Complex number
16984 */
16985 Complex.fromJSON = function (json) {
16986 return new Complex(json);
16987 };
16988
16989 // apply the current epsilon
16990 Complex.EPSILON = config.epsilon;
16991
16992 // listen for changed in the configuration, automatically apply changed epsilon
16993 math.on('config', function (curr, prev) {
16994 if (curr.epsilon !== prev.epsilon) {
16995 Complex.EPSILON = curr.epsilon;
16996 }
16997 });
16998
16999 /**
17000 * Compare two complex numbers, `a` and `b`:
17001 *
17002 * - Returns 1 when the real part of `a` is larger than the real part of `b`
17003 * - Returns -1 when the real part of `a` is smaller than the real part of `b`
17004 * - Returns 1 when the real parts are equal
17005 * and the imaginary part of `a` is larger than the imaginary part of `b`
17006 * - Returns -1 when the real parts are equal
17007 * and the imaginary part of `a` is smaller than the imaginary part of `b`
17008 * - Returns 0 when both real and imaginary parts are equal.
17009 *
17010 * @params {Complex} a
17011 * @params {Complex} b
17012 * @returns {number} Returns the comparison result: -1, 0, or 1
17013 */
17014 Complex.compare = function (a, b) {
17015 if (a.re > b.re) { return 1; }
17016 if (a.re < b.re) { return -1; }
17017
17018 if (a.im > b.im) { return 1; }
17019 if (a.im < b.im) { return -1; }
17020
17021 return 0;
17022 }
17023
17024 return Complex;
17025}
17026
17027exports.name = 'Complex';
17028exports.path = 'type';
17029exports.factory = factory;
17030exports.math = true; // request access to the math namespace
17031
17032
17033/***/ }),
17034/* 93 */
17035/***/ (function(module, exports, __webpack_require__) {
17036
17037"use strict";
17038
17039
17040var deepMap = __webpack_require__(1);
17041
17042function factory (type, config, load, typed) {
17043 /**
17044 * Create a fraction convert a value to a fraction.
17045 *
17046 * Syntax:
17047 * math.fraction(numerator, denominator)
17048 * math.fraction({n: numerator, d: denominator})
17049 * math.fraction(matrix: Array | Matrix) Turn all matrix entries
17050 * into fractions
17051 *
17052 * Examples:
17053 *
17054 * math.fraction(1, 3);
17055 * math.fraction('2/3');
17056 * math.fraction({n: 2, d: 3});
17057 * math.fraction([0.2, 0.25, 1.25]);
17058 *
17059 * See also:
17060 *
17061 * bignumber, number, string, unit
17062 *
17063 * @param {number | string | Fraction | BigNumber | Array | Matrix} [args]
17064 * Arguments specifying the numerator and denominator of
17065 * the fraction
17066 * @return {Fraction | Array | Matrix} Returns a fraction
17067 */
17068 var fraction = typed('fraction', {
17069 'number': function (x) {
17070 if (!isFinite(x) || isNaN(x)) {
17071 throw new Error(x + ' cannot be represented as a fraction');
17072 }
17073
17074 return new type.Fraction(x);
17075 },
17076
17077 'string': function (x) {
17078 return new type.Fraction(x);
17079 },
17080
17081 'number, number': function (numerator, denominator) {
17082 return new type.Fraction(numerator, denominator);
17083 },
17084
17085 'BigNumber': function (x) {
17086 return new type.Fraction(x.toString());
17087 },
17088
17089 'Fraction': function (x) {
17090 return x; // fractions are immutable
17091 },
17092
17093 'Object': function (x) {
17094 return new type.Fraction(x);
17095 },
17096
17097 'Array | Matrix': function (x) {
17098 return deepMap(x, fraction);
17099 }
17100 });
17101
17102 return fraction;
17103}
17104
17105exports.name = 'fraction';
17106exports.factory = factory;
17107
17108
17109/***/ }),
17110/* 94 */
17111/***/ (function(module, exports, __webpack_require__) {
17112
17113"use strict";
17114
17115
17116var number = __webpack_require__(3);
17117
17118function factory (type, config, load, typed) {
17119 /**
17120 * Create a range. A range has a start, step, and end, and contains functions
17121 * to iterate over the range.
17122 *
17123 * A range can be constructed as:
17124 * var range = new Range(start, end);
17125 * var range = new Range(start, end, step);
17126 *
17127 * To get the result of the range:
17128 * range.forEach(function (x) {
17129 * console.log(x);
17130 * });
17131 * range.map(function (x) {
17132 * return math.sin(x);
17133 * });
17134 * range.toArray();
17135 *
17136 * Example usage:
17137 * var c = new Range(2, 6); // 2:1:5
17138 * c.toArray(); // [2, 3, 4, 5]
17139 * var d = new Range(2, -3, -1); // 2:-1:-2
17140 * d.toArray(); // [2, 1, 0, -1, -2]
17141 *
17142 * @class Range
17143 * @constructor Range
17144 * @param {number} start included lower bound
17145 * @param {number} end excluded upper bound
17146 * @param {number} [step] step size, default value is 1
17147 */
17148 function Range(start, end, step) {
17149 if (!(this instanceof Range)) {
17150 throw new SyntaxError('Constructor must be called with the new operator');
17151 }
17152
17153 if (start != null) {
17154 if (type.isBigNumber(start))
17155 start = start.toNumber();
17156 else if (typeof start !== 'number')
17157 throw new TypeError('Parameter start must be a number');
17158 }
17159 if (end != null) {
17160 if (type.isBigNumber(end))
17161 end = end.toNumber();
17162 else if (typeof end !== 'number')
17163 throw new TypeError('Parameter end must be a number');
17164 }
17165 if (step != null) {
17166 if (type.isBigNumber(step))
17167 step = step.toNumber();
17168 else if (typeof step !== 'number')
17169 throw new TypeError('Parameter step must be a number');
17170 }
17171
17172 this.start = (start != null) ? parseFloat(start) : 0;
17173 this.end = (end != null) ? parseFloat(end) : 0;
17174 this.step = (step != null) ? parseFloat(step) : 1;
17175 }
17176
17177 /**
17178 * Attach type information
17179 */
17180 Range.prototype.type = 'Range';
17181 Range.prototype.isRange = true;
17182
17183 /**
17184 * Parse a string into a range,
17185 * The string contains the start, optional step, and end, separated by a colon.
17186 * If the string does not contain a valid range, null is returned.
17187 * For example str='0:2:11'.
17188 * @memberof Range
17189 * @param {string} str
17190 * @return {Range | null} range
17191 */
17192 Range.parse = function (str) {
17193 if (typeof str !== 'string') {
17194 return null;
17195 }
17196
17197 var args = str.split(':');
17198 var nums = args.map(function (arg) {
17199 return parseFloat(arg);
17200 });
17201
17202 var invalid = nums.some(function (num) {
17203 return isNaN(num);
17204 });
17205 if (invalid) {
17206 return null;
17207 }
17208
17209 switch (nums.length) {
17210 case 2:
17211 return new Range(nums[0], nums[1]);
17212 case 3:
17213 return new Range(nums[0], nums[2], nums[1]);
17214 default:
17215 return null;
17216 }
17217 };
17218
17219 /**
17220 * Create a clone of the range
17221 * @return {Range} clone
17222 */
17223 Range.prototype.clone = function () {
17224 return new Range(this.start, this.end, this.step);
17225 };
17226
17227 /**
17228 * Retrieve the size of the range.
17229 * Returns an array containing one number, the number of elements in the range.
17230 * @memberof Range
17231 * @returns {number[]} size
17232 */
17233 Range.prototype.size = function () {
17234 var len = 0,
17235 start = this.start,
17236 step = this.step,
17237 end = this.end,
17238 diff = end - start;
17239
17240 if (number.sign(step) == number.sign(diff)) {
17241 len = Math.ceil((diff) / step);
17242 }
17243 else if (diff == 0) {
17244 len = 0;
17245 }
17246
17247 if (isNaN(len)) {
17248 len = 0;
17249 }
17250 return [len];
17251 };
17252
17253 /**
17254 * Calculate the minimum value in the range
17255 * @memberof Range
17256 * @return {number | undefined} min
17257 */
17258 Range.prototype.min = function () {
17259 var size = this.size()[0];
17260
17261 if (size > 0) {
17262 if (this.step > 0) {
17263 // positive step
17264 return this.start;
17265 }
17266 else {
17267 // negative step
17268 return this.start + (size - 1) * this.step;
17269 }
17270 }
17271 else {
17272 return undefined;
17273 }
17274 };
17275
17276 /**
17277 * Calculate the maximum value in the range
17278 * @memberof Range
17279 * @return {number | undefined} max
17280 */
17281 Range.prototype.max = function () {
17282 var size = this.size()[0];
17283
17284 if (size > 0) {
17285 if (this.step > 0) {
17286 // positive step
17287 return this.start + (size - 1) * this.step;
17288 }
17289 else {
17290 // negative step
17291 return this.start;
17292 }
17293 }
17294 else {
17295 return undefined;
17296 }
17297 };
17298
17299
17300 /**
17301 * Execute a callback function for each value in the range.
17302 * @memberof Range
17303 * @param {function} callback The callback method is invoked with three
17304 * parameters: the value of the element, the index
17305 * of the element, and the Range being traversed.
17306 */
17307 Range.prototype.forEach = function (callback) {
17308 var x = this.start;
17309 var step = this.step;
17310 var end = this.end;
17311 var i = 0;
17312
17313 if (step > 0) {
17314 while (x < end) {
17315 callback(x, [i], this);
17316 x += step;
17317 i++;
17318 }
17319 }
17320 else if (step < 0) {
17321 while (x > end) {
17322 callback(x, [i], this);
17323 x += step;
17324 i++;
17325 }
17326 }
17327 };
17328
17329 /**
17330 * Execute a callback function for each value in the Range, and return the
17331 * results as an array
17332 * @memberof Range
17333 * @param {function} callback The callback method is invoked with three
17334 * parameters: the value of the element, the index
17335 * of the element, and the Matrix being traversed.
17336 * @returns {Array} array
17337 */
17338 Range.prototype.map = function (callback) {
17339 var array = [];
17340 this.forEach(function (value, index, obj) {
17341 array[index[0]] = callback(value, index, obj);
17342 });
17343 return array;
17344 };
17345
17346 /**
17347 * Create an Array with a copy of the Ranges data
17348 * @memberof Range
17349 * @returns {Array} array
17350 */
17351 Range.prototype.toArray = function () {
17352 var array = [];
17353 this.forEach(function (value, index) {
17354 array[index[0]] = value;
17355 });
17356 return array;
17357 };
17358
17359 /**
17360 * Get the primitive value of the Range, a one dimensional array
17361 * @memberof Range
17362 * @returns {Array} array
17363 */
17364 Range.prototype.valueOf = function () {
17365 // TODO: implement a caching mechanism for range.valueOf()
17366 return this.toArray();
17367 };
17368
17369 /**
17370 * Get a string representation of the range, with optional formatting options.
17371 * Output is formatted as 'start:step:end', for example '2:6' or '0:0.2:11'
17372 * @memberof Range
17373 * @param {Object | number | function} [options] Formatting options. See
17374 * lib/utils/number:format for a
17375 * description of the available
17376 * options.
17377 * @returns {string} str
17378 */
17379 Range.prototype.format = function (options) {
17380 var str = number.format(this.start, options);
17381
17382 if (this.step != 1) {
17383 str += ':' + number.format(this.step, options);
17384 }
17385 str += ':' + number.format(this.end, options);
17386 return str;
17387 };
17388
17389 /**
17390 * Get a string representation of the range.
17391 * @memberof Range
17392 * @returns {string}
17393 */
17394 Range.prototype.toString = function () {
17395 return this.format();
17396 };
17397
17398 /**
17399 * Get a JSON representation of the range
17400 * @memberof Range
17401 * @returns {Object} Returns a JSON object structured as:
17402 * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}`
17403 */
17404 Range.prototype.toJSON = function () {
17405 return {
17406 mathjs: 'Range',
17407 start: this.start,
17408 end: this.end,
17409 step: this.step
17410 };
17411 };
17412
17413 /**
17414 * Instantiate a Range from a JSON object
17415 * @memberof Range
17416 * @param {Object} json A JSON object structured as:
17417 * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}`
17418 * @return {Range}
17419 */
17420 Range.fromJSON = function (json) {
17421 return new Range(json.start, json.end, json.step);
17422 };
17423
17424 return Range;
17425}
17426
17427exports.name = 'Range';
17428exports.path = 'type';
17429exports.factory = factory;
17430
17431
17432/***/ }),
17433/* 95 */
17434/***/ (function(module, exports, __webpack_require__) {
17435
17436"use strict";
17437
17438
17439function factory (type, config, load, typed) {
17440 /**
17441 * A ResultSet contains a list or results
17442 * @class ResultSet
17443 * @param {Array} entries
17444 * @constructor ResultSet
17445 */
17446 function ResultSet(entries) {
17447 if (!(this instanceof ResultSet)) {
17448 throw new SyntaxError('Constructor must be called with the new operator');
17449 }
17450
17451 this.entries = entries || [];
17452 }
17453
17454 /**
17455 * Attach type information
17456 */
17457 ResultSet.prototype.type = 'ResultSet';
17458 ResultSet.prototype.isResultSet = true;
17459
17460 /**
17461 * Returns the array with results hold by this ResultSet
17462 * @memberof ResultSet
17463 * @returns {Array} entries
17464 */
17465 ResultSet.prototype.valueOf = function () {
17466 return this.entries;
17467 };
17468
17469 /**
17470 * Returns the stringified results of the ResultSet
17471 * @memberof ResultSet
17472 * @returns {string} string
17473 */
17474 ResultSet.prototype.toString = function () {
17475 return '[' + this.entries.join(', ') + ']';
17476 };
17477
17478 /**
17479 * Get a JSON representation of the ResultSet
17480 * @memberof ResultSet
17481 * @returns {Object} Returns a JSON object structured as:
17482 * `{"mathjs": "ResultSet", "entries": [...]}`
17483 */
17484 ResultSet.prototype.toJSON = function () {
17485 return {
17486 mathjs: 'ResultSet',
17487 entries: this.entries
17488 };
17489 };
17490
17491 /**
17492 * Instantiate a ResultSet from a JSON object
17493 * @memberof ResultSet
17494 * @param {Object} json A JSON object structured as:
17495 * `{"mathjs": "ResultSet", "entries": [...]}`
17496 * @return {ResultSet}
17497 */
17498 ResultSet.fromJSON = function (json) {
17499 return new ResultSet(json.entries);
17500 };
17501
17502 return ResultSet;
17503}
17504
17505exports.name = 'ResultSet';
17506exports.path = 'type';
17507exports.factory = factory;
17508
17509
17510/***/ }),
17511/* 96 */
17512/***/ (function(module, exports, __webpack_require__) {
17513
17514var memoize = __webpack_require__(32).memoize;
17515
17516/**
17517 * Calculate BigNumber e
17518 * @param {function} BigNumber BigNumber constructor
17519 * @returns {BigNumber} Returns e
17520 */
17521exports.e = memoize(function (BigNumber) {
17522 return new BigNumber(1).exp();
17523}, hasher);
17524
17525/**
17526 * Calculate BigNumber golden ratio, phi = (1+sqrt(5))/2
17527 * @param {function} BigNumber BigNumber constructor
17528 * @returns {BigNumber} Returns phi
17529 */
17530exports.phi = memoize(function (BigNumber) {
17531 return new BigNumber(1).plus(new BigNumber(5).sqrt()).div(2);
17532}, hasher);
17533
17534/**
17535 * Calculate BigNumber pi.
17536 * @param {function} BigNumber BigNumber constructor
17537 * @returns {BigNumber} Returns pi
17538 */
17539exports.pi = memoize(function (BigNumber) {
17540 return BigNumber.acos(-1);
17541}, hasher);
17542
17543/**
17544 * Calculate BigNumber tau, tau = 2 * pi
17545 * @param {function} BigNumber BigNumber constructor
17546 * @returns {BigNumber} Returns tau
17547 */
17548exports.tau = memoize(function (BigNumber) {
17549 return exports.pi(BigNumber).times(2);
17550}, hasher);
17551
17552/**
17553 * Create a hash for a BigNumber constructor function. The created has is
17554 * the configured precision
17555 * @param {Array} args Supposed to contain a single entry with
17556 * a BigNumber constructor
17557 * @return {number} precision
17558 * @private
17559 */
17560function hasher (args) {
17561 return args[0].precision;
17562}
17563
17564
17565/***/ }),
17566/* 97 */
17567/***/ (function(module, exports, __webpack_require__) {
17568
17569"use strict";
17570
17571
17572var deepMap = __webpack_require__(1);
17573
17574function factory (type, config, load, typed) {
17575 /**
17576 * Round a value towards zero.
17577 * For matrices, the function is evaluated element wise.
17578 *
17579 * Syntax:
17580 *
17581 * math.fix(x)
17582 *
17583 * Examples:
17584 *
17585 * math.fix(3.2); // returns number 3
17586 * math.fix(3.8); // returns number 3
17587 * math.fix(-4.2); // returns number -4
17588 * math.fix(-4.7); // returns number -4
17589 *
17590 * var c = math.complex(3.2, -2.7);
17591 * math.fix(c); // returns Complex 3 - 2i
17592 *
17593 * math.fix([3.2, 3.8, -4.7]); // returns Array [3, 3, -4]
17594 *
17595 * See also:
17596 *
17597 * ceil, floor, round
17598 *
17599 * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
17600 * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
17601 */
17602 var fix = typed('fix', {
17603 'number': function (x) {
17604 return (x > 0) ? Math.floor(x) : Math.ceil(x);
17605 },
17606
17607 'Complex': function (x) {
17608 return new type.Complex(
17609 (x.re > 0) ? Math.floor(x.re) : Math.ceil(x.re),
17610 (x.im > 0) ? Math.floor(x.im) : Math.ceil(x.im)
17611 );
17612 },
17613
17614 'BigNumber': function (x) {
17615 return x.isNegative() ? x.ceil() : x.floor();
17616 },
17617
17618 'Fraction': function (x) {
17619 return x.s < 0 ? x.ceil() : x.floor();
17620 },
17621
17622 'Array | Matrix': function (x) {
17623 // deep map collection, skip zeros since fix(0) = 0
17624 return deepMap(x, fix, true);
17625 }
17626 });
17627
17628 fix.toTex = {1: '\\mathrm{${name}}\\left(${args[0]}\\right)'};
17629
17630 return fix;
17631}
17632
17633exports.name = 'fix';
17634exports.factory = factory;
17635
17636
17637/***/ }),
17638/* 98 */
17639/***/ (function(module, exports, __webpack_require__) {
17640
17641"use strict";
17642
17643
17644var isInteger = __webpack_require__(3).isInteger;
17645var toFixed = __webpack_require__(3).toFixed;
17646var deepMap = __webpack_require__(1);
17647
17648var NO_INT = 'Number of decimals in function round must be an integer';
17649
17650function factory (type, config, load, typed) {
17651 var matrix = load(__webpack_require__(0));
17652 var equalScalar = load(__webpack_require__(10));
17653 var zeros = load(__webpack_require__(40));
17654
17655 var algorithm11 = load(__webpack_require__(19));
17656 var algorithm12 = load(__webpack_require__(18));
17657 var algorithm14 = load(__webpack_require__(6));
17658
17659 /**
17660 * Round a value towards the nearest integer.
17661 * For matrices, the function is evaluated element wise.
17662 *
17663 * Syntax:
17664 *
17665 * math.round(x)
17666 * math.round(x, n)
17667 *
17668 * Examples:
17669 *
17670 * math.round(3.2); // returns number 3
17671 * math.round(3.8); // returns number 4
17672 * math.round(-4.2); // returns number -4
17673 * math.round(-4.7); // returns number -5
17674 * math.round(math.pi, 3); // returns number 3.142
17675 * math.round(123.45678, 2); // returns number 123.46
17676 *
17677 * var c = math.complex(3.2, -2.7);
17678 * math.round(c); // returns Complex 3 - 3i
17679 *
17680 * math.round([3.2, 3.8, -4.7]); // returns Array [3, 4, -5]
17681 *
17682 * See also:
17683 *
17684 * ceil, fix, floor
17685 *
17686 * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
17687 * @param {number | BigNumber | Array} [n=0] Number of decimals
17688 * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
17689 */
17690 var round = typed('round', {
17691
17692 'number': Math.round,
17693
17694 'number, number': function (x, n) {
17695 if (!isInteger(n)) {throw new TypeError(NO_INT);}
17696 if (n < 0 || n > 15) {throw new Error('Number of decimals in function round must be in te range of 0-15');}
17697
17698 return _round(x, n);
17699 },
17700
17701 'Complex': function (x) {
17702 return x.round();
17703 },
17704
17705 'Complex, number': function (x, n) {
17706 if (n % 1) {throw new TypeError(NO_INT);}
17707
17708 return x.round(n);
17709 },
17710
17711 'Complex, BigNumber': function (x, n) {
17712 if (!n.isInteger()) {throw new TypeError(NO_INT);}
17713
17714 var _n = n.toNumber();
17715 return x.round(_n);
17716 },
17717
17718 'number, BigNumber': function (x, n) {
17719 if (!n.isInteger()) {throw new TypeError(NO_INT);}
17720
17721 return new type.BigNumber(x).toDecimalPlaces(n.toNumber());
17722 },
17723
17724 'BigNumber': function (x) {
17725 return x.toDecimalPlaces(0);
17726 },
17727
17728 'BigNumber, BigNumber': function (x, n) {
17729 if (!n.isInteger()) {throw new TypeError(NO_INT);}
17730
17731 return x.toDecimalPlaces(n.toNumber());
17732 },
17733
17734 'Fraction': function (x) {
17735 return x.round();
17736 },
17737
17738 'Fraction, number': function (x, n) {
17739 if (n % 1) {throw new TypeError(NO_INT);}
17740 return x.round(n);
17741 },
17742
17743 'Array | Matrix': function (x) {
17744 // deep map collection, skip zeros since round(0) = 0
17745 return deepMap(x, round, true);
17746 },
17747
17748 'Matrix, number | BigNumber': function (x, y) {
17749 // result
17750 var c;
17751 // check storage format
17752 switch (x.storage()) {
17753 case 'sparse':
17754 c = algorithm11(x, y, round, false);
17755 break;
17756 default:
17757 c = algorithm14(x, y, round, false);
17758 break;
17759 }
17760 return c;
17761 },
17762
17763 'number | Complex | BigNumber, Matrix': function (x, y) {
17764 // check scalar is zero
17765 if (!equalScalar(x, 0)) {
17766 // result
17767 var c;
17768 // check storage format
17769 switch (y.storage()) {
17770 case 'sparse':
17771 c = algorithm12(y, x, round, true);
17772 break;
17773 default:
17774 c = algorithm14(y, x, round, true);
17775 break;
17776 }
17777 return c;
17778 }
17779 // do not execute algorithm, result will be a zero matrix
17780 return zeros(y.size(), y.storage());
17781 },
17782
17783 'Array, number | BigNumber': function (x, y) {
17784 // use matrix implementation
17785 return algorithm14(matrix(x), y, round, false).valueOf();
17786 },
17787
17788 'number | Complex | BigNumber, Array': function (x, y) {
17789 // use matrix implementation
17790 return algorithm14(matrix(y), x, round, true).valueOf();
17791 }
17792 });
17793
17794 round.toTex = {
17795 1: '\\left\\lfloor${args[0]}\\right\\rceil',
17796 2: undefined // use default template
17797 };
17798
17799 return round;
17800}
17801
17802/**
17803 * round a number to the given number of decimals, or to zero if decimals is
17804 * not provided
17805 * @param {number} value
17806 * @param {number} decimals number of decimals, between 0 and 15 (0 by default)
17807 * @return {number} roundedValue
17808 * @private
17809 */
17810function _round (value, decimals) {
17811 return parseFloat(toFixed(value, decimals));
17812}
17813
17814exports.name = 'round';
17815exports.factory = factory;
17816
17817
17818/***/ }),
17819/* 99 */
17820/***/ (function(module, exports, __webpack_require__) {
17821
17822"use strict";
17823
17824
17825var string = __webpack_require__(9);
17826
17827function factory (type, config, load, typed) {
17828 /**
17829 * Format a value of any type into a string.
17830 *
17831 * Syntax:
17832 *
17833 * math.format(value)
17834 * math.format(value, options)
17835 * math.format(value, precision)
17836 * math.format(value, callback)
17837 *
17838 * Where:
17839 *
17840 * - `value: *`
17841 * The value to be formatted
17842 * - `options: Object`
17843 * An object with formatting options. Available options:
17844 * - `notation: string`
17845 * Number notation. Choose from:
17846 * - 'fixed'
17847 * Always use regular number notation.
17848 * For example '123.40' and '14000000'
17849 * - 'exponential'
17850 * Always use exponential notation.
17851 * For example '1.234e+2' and '1.4e+7'
17852 * - 'engineering'
17853 * Always use engineering notation.
17854 * For example '123.4e+0' and '14.0e+6'
17855 * - 'auto' (default)
17856 * Regular number notation for numbers having an absolute value between
17857 * `lower` and `upper` bounds, and uses exponential notation elsewhere.
17858 * Lower bound is included, upper bound is excluded.
17859 * For example '123.4' and '1.4e7'.
17860 * - `precision: number`
17861 * A number between 0 and 16 to round the digits of the number. In case
17862 * of notations 'exponential' and 'auto', `precision` defines the total
17863 * number of significant digits returned and is undefined by default.
17864 * In case of notation 'fixed', `precision` defines the number of
17865 * significant digits after the decimal point, and is 0 by default.
17866 * - `exponential: Object`
17867 * An object containing two parameters, {number} lower and {number} upper,
17868 * used by notation 'auto' to determine when to return exponential
17869 * notation. Default values are `lower=1e-3` and `upper=1e5`. Only
17870 * applicable for notation `auto`.
17871 * - `fraction: string`. Available values: 'ratio' (default) or 'decimal'.
17872 * For example `format(fraction(1, 3))` will output '1/3' when 'ratio' is
17873 * configured, and will output `0.(3)` when 'decimal' is configured.
17874 * - `callback: function`
17875 * A custom formatting function, invoked for all numeric elements in `value`,
17876 * for example all elements of a matrix, or the real and imaginary
17877 * parts of a complex number. This callback can be used to override the
17878 * built-in numeric notation with any type of formatting. Function `callback`
17879 * is called with `value` as parameter and must return a string.
17880 *
17881 * When `value` is an Object:
17882 *
17883 * - When the object contains a property `format` being a function, this function
17884 * is invoked as `value.format(options)` and the result is returned.
17885 * - When the object has its own `toString` method, this method is invoked
17886 * and the result is returned.
17887 * - In other cases the function will loop over all object properties and
17888 * return JSON object notation like '{"a": 2, "b": 3}'.
17889 *
17890 * When value is a function:
17891 *
17892 * - When the function has a property `syntax`, it returns this
17893 * syntax description.
17894 * - In other cases, a string `'function'` is returned.
17895 *
17896 * Examples:
17897 *
17898 * math.format(6.4); // returns '6.4'
17899 * math.format(1240000); // returns '1.24e6'
17900 * math.format(1/3); // returns '0.3333333333333333'
17901 * math.format(1/3, 3); // returns '0.333'
17902 * math.format(21385, 2); // returns '21000'
17903 * math.format(12.071, {notation: 'fixed'}); // returns '12'
17904 * math.format(2.3, {notation: 'fixed', precision: 2}); // returns '2.30'
17905 * math.format(52.8, {notation: 'exponential'}); // returns '5.28e+1'
17906 * math.format(12400, {notation: 'engineering'}); // returns '12.400e+3'
17907 *
17908 * function formatCurrency(value) {
17909 * // return currency notation with two digits:
17910 * return '$' + value.toFixed(2);
17911 *
17912 * // you could also use math.format inside the callback:
17913 * // return '$' + math.format(value, {notation: 'fixed', precision: 2});
17914 * }
17915 * math.format([2.1, 3, 0.016], formatCurrency}; // returns '[$2.10, $3.00, $0.02]'
17916 *
17917 * See also:
17918 *
17919 * print
17920 *
17921 * @param {*} value Value to be stringified
17922 * @param {Object | Function | number} [options] Formatting options
17923 * @return {string} The formatted value
17924 */
17925 var format = typed('format', {
17926 'any': string.format,
17927 'any, Object | function | number': string.format
17928 });
17929
17930 format.toTex = undefined; // use default template
17931
17932 return format;
17933}
17934
17935exports.name = 'format';
17936exports.factory = factory;
17937
17938
17939/***/ }),
17940/* 100 */
17941/***/ (function(module, exports, __webpack_require__) {
17942
17943function factory (construction, config, load, typed) {
17944 var docs = {};
17945
17946
17947 // construction functions
17948 docs.bignumber = __webpack_require__(196);
17949 docs['boolean'] = __webpack_require__(197);
17950 docs.complex = __webpack_require__(198);
17951 docs.createUnit = __webpack_require__(199);
17952 docs.fraction = __webpack_require__(200);
17953 docs.index = __webpack_require__(201);
17954 docs.matrix = __webpack_require__(202);
17955 docs.number = __webpack_require__(203);
17956 docs.sparse = __webpack_require__(204);
17957 docs.splitUnit = __webpack_require__(205);
17958 docs.string = __webpack_require__(206);
17959 docs.unit = __webpack_require__(207);
17960
17961 // constants
17962 docs.e = __webpack_require__(101);
17963 docs.E = __webpack_require__(101);
17964 docs['false'] = __webpack_require__(208);
17965 docs.i = __webpack_require__(209);
17966 docs['Infinity'] = __webpack_require__(210);
17967 docs.LN2 = __webpack_require__(211);
17968 docs.LN10 = __webpack_require__(212);
17969 docs.LOG2E = __webpack_require__(213);
17970 docs.LOG10E = __webpack_require__(214);
17971 docs.NaN = __webpack_require__(215);
17972 docs['null'] = __webpack_require__(216);
17973 docs.pi = __webpack_require__(102);
17974 docs.PI = __webpack_require__(102);
17975 docs.phi = __webpack_require__(217);
17976 docs.SQRT1_2 = __webpack_require__(218);
17977 docs.SQRT2 = __webpack_require__(219);
17978 docs.tau = __webpack_require__(220);
17979 docs['true'] = __webpack_require__(221);
17980 docs.version = __webpack_require__(222);
17981
17982 // physical constants
17983 // TODO: more detailed docs for physical constants
17984 docs.speedOfLight = {description: 'Speed of light in vacuum', examples: ['speedOfLight']};
17985 docs.gravitationConstant = {description: 'Newtonian constant of gravitation', examples: ['gravitationConstant']};
17986 docs.planckConstant = {description: 'Planck constant', examples: ['planckConstant']};
17987 docs.reducedPlanckConstant = {description: 'Reduced Planck constant', examples: ['reducedPlanckConstant']};
17988
17989 docs.magneticConstant = {description: 'Magnetic constant (vacuum permeability)', examples: ['magneticConstant']};
17990 docs.electricConstant = {description: 'Electric constant (vacuum permeability)', examples: ['electricConstant']};
17991 docs.vacuumImpedance = {description: 'Characteristic impedance of vacuum', examples: ['vacuumImpedance']};
17992 docs.coulomb = {description: 'Coulomb\'s constant', examples: ['coulomb']};
17993 docs.elementaryCharge = {description: 'Elementary charge', examples: ['elementaryCharge']};
17994 docs.bohrMagneton = {description: 'Borh magneton', examples: ['bohrMagneton']};
17995 docs.conductanceQuantum = {description: 'Conductance quantum', examples: ['conductanceQuantum']};
17996 docs.inverseConductanceQuantum = {description: 'Inverse conductance quantum', examples: ['inverseConductanceQuantum']};
17997 //docs.josephson = {description: 'Josephson constant', examples: ['josephson']};
17998 docs.magneticFluxQuantum = {description: 'Magnetic flux quantum', examples: ['magneticFluxQuantum']};
17999 docs.nuclearMagneton = {description: 'Nuclear magneton', examples: ['nuclearMagneton']};
18000 docs.klitzing = {description: 'Von Klitzing constant', examples: ['klitzing']};
18001
18002 docs.bohrRadius = {description: 'Borh radius', examples: ['bohrRadius']};
18003 docs.classicalElectronRadius = {description: 'Classical electron radius', examples: ['classicalElectronRadius']};
18004 docs.electronMass = {description: 'Electron mass', examples: ['electronMass']};
18005 docs.fermiCoupling = {description: 'Fermi coupling constant', examples: ['fermiCoupling']};
18006 docs.fineStructure = {description: 'Fine-structure constant', examples: ['fineStructure']};
18007 docs.hartreeEnergy = {description: 'Hartree energy', examples: ['hartreeEnergy']};
18008 docs.protonMass = {description: 'Proton mass', examples: ['protonMass']};
18009 docs.deuteronMass = {description: 'Deuteron Mass', examples: ['deuteronMass']};
18010 docs.neutronMass = {description: 'Neutron mass', examples: ['neutronMass']};
18011 docs.quantumOfCirculation = {description: 'Quantum of circulation', examples: ['quantumOfCirculation']};
18012 docs.rydberg = {description: 'Rydberg constant', examples: ['rydberg']};
18013 docs.thomsonCrossSection = {description: 'Thomson cross section', examples: ['thomsonCrossSection']};
18014 docs.weakMixingAngle = {description: 'Weak mixing angle', examples: ['weakMixingAngle']};
18015 docs.efimovFactor = {description: 'Efimov factor', examples: ['efimovFactor']};
18016
18017 docs.atomicMass = {description: 'Atomic mass constant', examples: ['atomicMass']};
18018 docs.avogadro = {description: 'Avogadro\'s number', examples: ['avogadro']};
18019 docs.boltzmann = {description: 'Boltzmann constant', examples: ['boltzmann']};
18020 docs.faraday = {description: 'Faraday constant', examples: ['faraday']};
18021 docs.firstRadiation = {description: 'First radiation constant', examples: ['firstRadiation']};
18022 docs.loschmidt = {description: 'Loschmidt constant at T=273.15 K and p=101.325 kPa', examples: ['loschmidt']};
18023 docs.gasConstant = {description: 'Gas constant', examples: ['gasConstant']};
18024 docs.molarPlanckConstant = {description: 'Molar Planck constant', examples: ['molarPlanckConstant']};
18025 docs.molarVolume = {description: 'Molar volume of an ideal gas at T=273.15 K and p=101.325 kPa', examples: ['molarVolume']};
18026 docs.sackurTetrode = {description: 'Sackur-Tetrode constant at T=1 K and p=101.325 kPa', examples: ['sackurTetrode']};
18027 docs.secondRadiation = {description: 'Second radiation constant', examples: ['secondRadiation']};
18028 docs.stefanBoltzmann = {description: 'Stefan-Boltzmann constant', examples: ['stefanBoltzmann']};
18029 docs.wienDisplacement = {description: 'Wien displacement law constant', examples: ['wienDisplacement']};
18030 //docs.spectralRadiance = {description: 'First radiation constant for spectral radiance', examples: ['spectralRadiance']};
18031
18032 docs.molarMass = {description: 'Molar mass constant', examples: ['molarMass']};
18033 docs.molarMassC12 = {description: 'Molar mass constant of carbon-12', examples: ['molarMassC12']};
18034 docs.gravity = {description: 'Standard acceleration of gravity (standard acceleration of free-fall on Earth)', examples: ['gravity']};
18035
18036 docs.planckLength = {description: 'Planck length', examples: ['planckLength']};
18037 docs.planckMass = {description: 'Planck mass', examples: ['planckMass']};
18038 docs.planckTime = {description: 'Planck time', examples: ['planckTime']};
18039 docs.planckCharge = {description: 'Planck charge', examples: ['planckCharge']};
18040 docs.planckTemperature = {description: 'Planck temperature', examples: ['planckTemperature']};
18041
18042 // functions - algebra
18043 docs.derivative = __webpack_require__(223);
18044 docs.lsolve = __webpack_require__(224);
18045 docs.lup = __webpack_require__(225);
18046 docs.lusolve = __webpack_require__(226);
18047 docs.simplify = __webpack_require__(227);
18048 docs.rationalize = __webpack_require__(228);
18049 docs.slu = __webpack_require__(229);
18050 docs.usolve = __webpack_require__(230);
18051 docs.qr = __webpack_require__(231);
18052
18053 // functions - arithmetic
18054 docs.abs = __webpack_require__(232);
18055 docs.add = __webpack_require__(233);
18056 docs.cbrt = __webpack_require__(234);
18057 docs.ceil = __webpack_require__(235);
18058 docs.cube = __webpack_require__(236);
18059 docs.divide = __webpack_require__(237);
18060 docs.dotDivide = __webpack_require__(238);
18061 docs.dotMultiply = __webpack_require__(239);
18062 docs.dotPow = __webpack_require__(240);
18063 docs.exp = __webpack_require__(241);
18064 docs.fix = __webpack_require__(242);
18065 docs.floor = __webpack_require__(243);
18066 docs.gcd = __webpack_require__(244);
18067 docs.hypot = __webpack_require__(245);
18068 docs.lcm = __webpack_require__(246);
18069 docs.log = __webpack_require__(247);
18070 docs.log10 = __webpack_require__(248);
18071 docs.mod = __webpack_require__(249);
18072 docs.multiply = __webpack_require__(250);
18073 docs.norm = __webpack_require__(251);
18074 docs.nthRoot = __webpack_require__(252);
18075 docs.pow = __webpack_require__(253);
18076 docs.round = __webpack_require__(254);
18077 docs.sign = __webpack_require__(255);
18078 docs.sqrt = __webpack_require__(256);
18079 docs.square = __webpack_require__(257);
18080 docs.subtract = __webpack_require__(258);
18081 docs.unaryMinus = __webpack_require__(259);
18082 docs.unaryPlus = __webpack_require__(260);
18083 docs.xgcd = __webpack_require__(261);
18084
18085 // functions - bitwise
18086 docs.bitAnd = __webpack_require__(262);
18087 docs.bitNot = __webpack_require__(263);
18088 docs.bitOr = __webpack_require__(264);
18089 docs.bitXor = __webpack_require__(265);
18090 docs.leftShift = __webpack_require__(266);
18091 docs.rightArithShift = __webpack_require__(267);
18092 docs.rightLogShift = __webpack_require__(268);
18093
18094 // functions - combinatorics
18095 docs.bellNumbers = __webpack_require__(269);
18096 docs.catalan = __webpack_require__(270);
18097 docs.composition = __webpack_require__(271);
18098 docs.stirlingS2 = __webpack_require__(272);
18099
18100 // functions - core
18101 docs['config'] = __webpack_require__(273);
18102 docs['import'] = __webpack_require__(274);
18103 docs['typed'] = __webpack_require__(275);
18104
18105 // functions - complex
18106 docs.arg = __webpack_require__(276);
18107 docs.conj = __webpack_require__(277);
18108 docs.re = __webpack_require__(278);
18109 docs.im = __webpack_require__(279);
18110
18111 // functions - expression
18112 docs['eval'] = __webpack_require__(280);
18113 docs.help = __webpack_require__(281);
18114
18115 // functions - geometry
18116 docs.distance = __webpack_require__(282);
18117 docs.intersect = __webpack_require__(283);
18118
18119 // functions - logical
18120 docs['and'] = __webpack_require__(284);
18121 docs['not'] = __webpack_require__(285);
18122 docs['or'] = __webpack_require__(286);
18123 docs['xor'] = __webpack_require__(287);
18124
18125 // functions - matrix
18126 docs['concat'] = __webpack_require__(288);
18127 docs.cross = __webpack_require__(289);
18128 docs.det = __webpack_require__(290);
18129 docs.diag = __webpack_require__(291);
18130 docs.dot = __webpack_require__(292);
18131 docs.eye = __webpack_require__(293);
18132 docs.filter = __webpack_require__(294);
18133 docs.flatten = __webpack_require__(295);
18134 docs.forEach = __webpack_require__(296);
18135 docs.inv = __webpack_require__(297);
18136 docs.kron = __webpack_require__(298);
18137 docs.map = __webpack_require__(299);
18138 docs.ones = __webpack_require__(300);
18139 docs.partitionSelect = __webpack_require__(301);
18140 docs.range = __webpack_require__(302);
18141 docs.resize = __webpack_require__(303);
18142 docs.reshape = __webpack_require__(304);
18143 docs.size = __webpack_require__(305);
18144 docs.sort = __webpack_require__(306);
18145 docs.squeeze = __webpack_require__(307);
18146 docs.subset = __webpack_require__(308);
18147 docs.trace = __webpack_require__(309);
18148 docs.transpose = __webpack_require__(310);
18149 docs.zeros = __webpack_require__(311);
18150
18151 // functions - probability
18152 docs.combinations = __webpack_require__(312);
18153 //docs.distribution = require('./function/probability/distribution');
18154 docs.factorial = __webpack_require__(313);
18155 docs.gamma = __webpack_require__(314);
18156 docs.kldivergence = __webpack_require__(315);
18157 docs.multinomial = __webpack_require__(316);
18158 docs.permutations = __webpack_require__(317);
18159 docs.pickRandom = __webpack_require__(318);
18160 docs.random = __webpack_require__(319);
18161 docs.randomInt = __webpack_require__(320);
18162
18163 // functions - relational
18164 docs.compare = __webpack_require__(321);
18165 docs.compareNatural = __webpack_require__(322);
18166 docs.deepEqual = __webpack_require__(323);
18167 docs['equal'] = __webpack_require__(324);
18168 docs.larger = __webpack_require__(325);
18169 docs.largerEq = __webpack_require__(326);
18170 docs.smaller = __webpack_require__(327);
18171 docs.smallerEq = __webpack_require__(328);
18172 docs.unequal = __webpack_require__(329);
18173
18174 // functions - set
18175 docs.setCartesian = __webpack_require__(330);
18176 docs.setDifference = __webpack_require__(331);
18177 docs.setDistinct = __webpack_require__(332);
18178 docs.setIntersect = __webpack_require__(333);
18179 docs.setIsSubset = __webpack_require__(334);
18180 docs.setMultiplicity = __webpack_require__(335);
18181 docs.setPowerset = __webpack_require__(336);
18182 docs.setSize = __webpack_require__(337);
18183 docs.setSymDifference = __webpack_require__(338);
18184 docs.setUnion = __webpack_require__(339);
18185
18186 // functions - special
18187 docs.erf = __webpack_require__(340);
18188
18189 // functions - statistics
18190 docs.mad = __webpack_require__(341);
18191 docs.max = __webpack_require__(342);
18192 docs.mean = __webpack_require__(343);
18193 docs.median = __webpack_require__(344);
18194 docs.min = __webpack_require__(345);
18195 docs.mode = __webpack_require__(346);
18196 docs.prod = __webpack_require__(347);
18197 docs.quantileSeq = __webpack_require__(348);
18198 docs.std = __webpack_require__(349);
18199 docs.sum = __webpack_require__(350);
18200 docs['var'] = __webpack_require__(351);
18201
18202 // functions - trigonometry
18203 docs.acos = __webpack_require__(352);
18204 docs.acosh = __webpack_require__(353);
18205 docs.acot = __webpack_require__(354);
18206 docs.acoth = __webpack_require__(355);
18207 docs.acsc = __webpack_require__(356);
18208 docs.acsch = __webpack_require__(357);
18209 docs.asec = __webpack_require__(358);
18210 docs.asech = __webpack_require__(359);
18211 docs.asin = __webpack_require__(360);
18212 docs.asinh = __webpack_require__(361);
18213 docs.atan = __webpack_require__(362);
18214 docs.atanh = __webpack_require__(363);
18215 docs.atan2 = __webpack_require__(364);
18216 docs.cos = __webpack_require__(365);
18217 docs.cosh = __webpack_require__(366);
18218 docs.cot = __webpack_require__(367);
18219 docs.coth = __webpack_require__(368);
18220 docs.csc = __webpack_require__(369);
18221 docs.csch = __webpack_require__(370);
18222 docs.sec = __webpack_require__(371);
18223 docs.sech = __webpack_require__(372);
18224 docs.sin = __webpack_require__(373);
18225 docs.sinh = __webpack_require__(374);
18226 docs.tan = __webpack_require__(375);
18227 docs.tanh = __webpack_require__(376);
18228
18229 // functions - units
18230 docs.to = __webpack_require__(377);
18231
18232 // functions - utils
18233 docs.clone = __webpack_require__(378);
18234 docs.format = __webpack_require__(379);
18235 docs.isNaN = __webpack_require__(380);
18236 docs.isInteger = __webpack_require__(381);
18237 docs.isNegative = __webpack_require__(382);
18238 docs.isNumeric = __webpack_require__(383);
18239 docs.isPositive = __webpack_require__(384);
18240 docs.isPrime = __webpack_require__(385);
18241 docs.isZero = __webpack_require__(386);
18242 // docs.print = require('./function/utils/print'); // TODO: add documentation for print as soon as the parser supports objects.
18243 docs['typeof'] = __webpack_require__(387);
18244
18245 return docs;
18246}
18247
18248exports.name = 'docs';
18249exports.path = 'expression';
18250exports.factory = factory;
18251
18252
18253/***/ }),
18254/* 101 */
18255/***/ (function(module, exports) {
18256
18257module.exports = {
18258 'name': 'e',
18259 'category': 'Constants',
18260 'syntax': [
18261 'e'
18262 ],
18263 'description': 'Euler\'s number, the base of the natural logarithm. Approximately equal to 2.71828',
18264 'examples': [
18265 'e',
18266 'e ^ 2',
18267 'exp(2)',
18268 'log(e)'
18269 ],
18270 'seealso': ['exp']
18271};
18272
18273
18274/***/ }),
18275/* 102 */
18276/***/ (function(module, exports) {
18277
18278module.exports = {
18279 'name': 'pi',
18280 'category': 'Constants',
18281 'syntax': [
18282 'pi'
18283 ],
18284 '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',
18285 'examples': [
18286 'pi',
18287 'sin(pi/2)'
18288 ],
18289 'seealso': ['tau']
18290};
18291
18292
18293/***/ }),
18294/* 103 */
18295/***/ (function(module, exports, __webpack_require__) {
18296
18297"use strict";
18298
18299
18300var stringify = __webpack_require__(9).stringify;
18301var getSafeProperty = __webpack_require__(13).getSafeProperty;
18302
18303function factory (type, config, load, typed) {
18304 var register = load(__webpack_require__(7)).register;
18305 var compile = load(__webpack_require__(7)).compile;
18306 var Node = load(__webpack_require__(15));
18307 var IndexNode = load(__webpack_require__(78));
18308 var access = load(__webpack_require__(104));
18309
18310 /**
18311 * @constructor AccessorNode
18312 * @extends {Node}
18313 * Access an object property or get a matrix subset
18314 *
18315 * @param {Node} object The object from which to retrieve
18316 * a property or subset.
18317 * @param {IndexNode} index IndexNode containing ranges
18318 */
18319 function AccessorNode(object, index) {
18320 if (!(this instanceof AccessorNode)) {
18321 throw new SyntaxError('Constructor must be called with the new operator');
18322 }
18323
18324 if (!type.isNode(object)) {
18325 throw new TypeError('Node expected for parameter "object"');
18326 }
18327 if (!type.isIndexNode(index)) {
18328 throw new TypeError('IndexNode expected for parameter "index"');
18329 }
18330
18331 this.object = object || null;
18332 this.index = index;
18333
18334 // readonly property name
18335 Object.defineProperty(this, 'name', {
18336 get: function () {
18337 if (this.index) {
18338 return (this.index.isObjectProperty())
18339 ? this.index.getObjectProperty()
18340 : '';
18341 }
18342 else {
18343 return this.object.name || '';
18344 }
18345 }.bind(this),
18346 set: function () {
18347 throw new Error('Cannot assign a new name, name is read-only');
18348 }
18349 });
18350 }
18351
18352 AccessorNode.prototype = new Node();
18353
18354 AccessorNode.prototype.type = 'AccessorNode';
18355
18356 AccessorNode.prototype.isAccessorNode = true;
18357
18358 /**
18359 * Compile the node to javascript code
18360 * @param {AccessorNode} node Node to be compiled
18361 * @param {Object} defs Object which can be used to define functions
18362 * or constants globally available for the compiled
18363 * expression
18364 * @param {Object} args Object with local function arguments, the key is
18365 * the name of the argument, and the value is `true`.
18366 * The object may not be mutated, but must be
18367 * extended instead.
18368 * @return {string} js
18369 * @private
18370 */
18371 function compileAccessorNode(node, defs, args) {
18372 if (!(node instanceof AccessorNode)) {
18373 throw new TypeError('No valid AccessorNode')
18374 }
18375
18376 defs.access = access;
18377 defs.getSafeProperty = getSafeProperty;
18378
18379 var object = compile(node.object, defs, args);
18380 var index = compile(node.index, defs, args);
18381
18382 if (node.index.isObjectProperty()) {
18383 var jsProp = stringify(node.index.getObjectProperty());
18384 return 'getSafeProperty(' + object + ', ' + jsProp + ')';
18385 }
18386 else if (node.index.needsSize()) {
18387 // if some parameters use the 'end' parameter, we need to calculate the size
18388 return '(function () {' +
18389 ' var object = ' + object + ';' +
18390 ' var size = math.size(object).valueOf();' +
18391 ' return access(object, ' + index + ');' +
18392 '})()';
18393 }
18394 else {
18395 return 'access(' + object + ', ' + index + ')';
18396 }
18397 }
18398
18399 // register the compile function
18400 register(AccessorNode.prototype.type, compileAccessorNode);
18401
18402 /**
18403 * Execute a callback for each of the child nodes of this node
18404 * @param {function(child: Node, path: string, parent: Node)} callback
18405 */
18406 AccessorNode.prototype.forEach = function (callback) {
18407 callback(this.object, 'object', this);
18408 callback(this.index, 'index', this);
18409 };
18410
18411 /**
18412 * Create a new AccessorNode having it's childs be the results of calling
18413 * the provided callback function for each of the childs of the original node.
18414 * @param {function(child: Node, path: string, parent: Node): Node} callback
18415 * @returns {AccessorNode} Returns a transformed copy of the node
18416 */
18417 AccessorNode.prototype.map = function (callback) {
18418 return new AccessorNode(
18419 this._ifNode(callback(this.object, 'object', this)),
18420 this._ifNode(callback(this.index, 'index', this))
18421 );
18422 };
18423
18424 /**
18425 * Create a clone of this node, a shallow copy
18426 * @return {AccessorNode}
18427 */
18428 AccessorNode.prototype.clone = function () {
18429 return new AccessorNode(this.object, this.index);
18430 };
18431
18432 /**
18433 * Get string representation
18434 * @param {Object} options
18435 * @return {string}
18436 */
18437 AccessorNode.prototype._toString = function (options) {
18438 var object = this.object.toString(options);
18439 if (needParenthesis(this.object)) {
18440 object = '(' + object + ')';
18441 }
18442
18443 return object + this.index.toString(options);
18444 };
18445
18446 /**
18447 * Get HTML representation
18448 * @param {Object} options
18449 * @return {string}
18450 */
18451 AccessorNode.prototype.toHTML = function (options) {
18452 var object = this.object.toHTML(options);
18453 if (needParenthesis(this.object)) {
18454 object = '<span class="math-parenthesis math-round-parenthesis">(</span>' + object + '<span class="math-parenthesis math-round-parenthesis">)</span>';
18455 }
18456
18457 return object + this.index.toHTML(options);
18458 };
18459
18460 /**
18461 * Get LaTeX representation
18462 * @param {Object} options
18463 * @return {string}
18464 */
18465 AccessorNode.prototype._toTex = function (options) {
18466 var object = this.object.toTex(options);
18467 if (needParenthesis(this.object)) {
18468 object = '\\left(' + object + '\\right)';
18469 }
18470
18471 return object + this.index.toTex(options);
18472 };
18473
18474 /**
18475 * Are parenthesis needed?
18476 * @private
18477 */
18478 function needParenthesis(node) {
18479 // TODO: maybe make a method on the nodes which tells whether they need parenthesis?
18480 return !(
18481 type.isAccessorNode(node) ||
18482 type.isArrayNode(node) ||
18483 type.isConstantNode(node) ||
18484 type.isFunctionNode(node) ||
18485 type.isObjectNode(node) ||
18486 type.isParenthesisNode(node) ||
18487 type.isSymbolNode(node));
18488 }
18489
18490 return AccessorNode;
18491}
18492
18493exports.name = 'AccessorNode';
18494exports.path = 'expression.node';
18495exports.factory = factory;
18496
18497
18498/***/ }),
18499/* 104 */
18500/***/ (function(module, exports, __webpack_require__) {
18501
18502"use strict";
18503
18504
18505var errorTransform = __webpack_require__(42).transform;
18506var getSafeProperty = __webpack_require__(13).getSafeProperty;
18507
18508function factory (type, config, load, typed) {
18509 var subset = load(__webpack_require__(23));
18510
18511 /**
18512 * Retrieve part of an object:
18513 *
18514 * - Retrieve a property from an object
18515 * - Retrieve a part of a string
18516 * - Retrieve a matrix subset
18517 *
18518 * @param {Object | Array | Matrix | string} object
18519 * @param {Index} index
18520 * @return {Object | Array | Matrix | string} Returns the subset
18521 */
18522 return function access(object, index) {
18523 try {
18524 if (Array.isArray(object)) {
18525 return subset(object, index);
18526 }
18527 else if (object && typeof object.subset === 'function') { // Matrix
18528 return object.subset(index);
18529 }
18530 else if (typeof object === 'string') {
18531 // TODO: move getStringSubset into a separate util file, use that
18532 return subset(object, index);
18533 }
18534 else if (typeof object === 'object') {
18535 if (!index.isObjectProperty()) {
18536 throw new TypeError('Cannot apply a numeric index as object property');
18537 }
18538
18539 return getSafeProperty(object, index.getObjectProperty());
18540 }
18541 else {
18542 throw new TypeError('Cannot apply index: unsupported type of object');
18543 }
18544 }
18545 catch (err) {
18546 throw errorTransform(err);
18547 }
18548 }
18549}
18550
18551exports.factory = factory;
18552
18553
18554/***/ }),
18555/* 105 */
18556/***/ (function(module, exports, __webpack_require__) {
18557
18558"use strict";
18559
18560
18561var latex = __webpack_require__(4);
18562var stringify = __webpack_require__(9).stringify;
18563var getSafeProperty = __webpack_require__(13).getSafeProperty;
18564var setSafeProperty = __webpack_require__(13).setSafeProperty;
18565
18566function factory (type, config, load, typed) {
18567 var register = load(__webpack_require__(7)).register;
18568 var compile = load(__webpack_require__(7)).compile;
18569 var Node = load(__webpack_require__(15));
18570 var ArrayNode = load(__webpack_require__(80));
18571 var matrix = load(__webpack_require__(0));
18572 var assign = load(__webpack_require__(390));
18573 var access = load(__webpack_require__(104));
18574
18575 var keywords = __webpack_require__(77);
18576 var operators = __webpack_require__(54);
18577
18578 /**
18579 * @constructor AssignmentNode
18580 * @extends {Node}
18581 *
18582 * Define a symbol, like `a=3.2`, update a property like `a.b=3.2`, or
18583 * replace a subset of a matrix like `A[2,2]=42`.
18584 *
18585 * Syntax:
18586 *
18587 * new AssignmentNode(symbol, value)
18588 * new AssignmentNode(object, index, value)
18589 *
18590 * Usage:
18591 *
18592 * new AssignmentNode(new SymbolNode('a'), new ConstantNode(2)); // a=2
18593 * new AssignmentNode(new SymbolNode('a'), new IndexNode('b'), new ConstantNode(2)) // a.b=2
18594 * new AssignmentNode(new SymbolNode('a'), new IndexNode(1, 2), new ConstantNode(3)) // a[1,2]=3
18595 *
18596 * @param {SymbolNode | AccessorNode} object Object on which to assign a value
18597 * @param {IndexNode} [index=null] Index, property name or matrix
18598 * index. Optional. If not provided
18599 * and `object` is a SymbolNode,
18600 * the property is assigned to the
18601 * global scope.
18602 * @param {Node} value The value to be assigned
18603 */
18604 function AssignmentNode(object, index, value) {
18605 if (!(this instanceof AssignmentNode)) {
18606 throw new SyntaxError('Constructor must be called with the new operator');
18607 }
18608
18609 this.object = object;
18610 this.index = value ? index : null;
18611 this.value = value ? value : index;
18612
18613 // validate input
18614 if (!type.isSymbolNode(object) && !type.isAccessorNode(object)) {
18615 throw new TypeError('SymbolNode or AccessorNode expected as "object"');
18616 }
18617 if (type.isSymbolNode(object) && object.name === 'end') {
18618 throw new Error('Cannot assign to symbol "end"');
18619 }
18620 if (this.index && !type.isIndexNode(this.index)) { // index is optional
18621 throw new TypeError('IndexNode expected as "index"');
18622 }
18623 if (!type.isNode(this.value)) {
18624 throw new TypeError('Node expected as "value"');
18625 }
18626
18627 // readonly property name
18628 Object.defineProperty(this, 'name', {
18629 get: function () {
18630 if (this.index) {
18631 return (this.index.isObjectProperty())
18632 ? this.index.getObjectProperty()
18633 : '';
18634 }
18635 else {
18636 return this.object.name || '';
18637 }
18638 }.bind(this),
18639 set: function () {
18640 throw new Error('Cannot assign a new name, name is read-only');
18641 }
18642 });
18643 }
18644
18645 AssignmentNode.prototype = new Node();
18646
18647 AssignmentNode.prototype.type = 'AssignmentNode';
18648
18649 AssignmentNode.prototype.isAssignmentNode = true;
18650
18651 /**
18652 * Compile the node to javascript code
18653 * @param {AssignmentNode} node The node to be compiled
18654 * @param {Object} defs Object which can be used to define functions
18655 * or constants globally available for the compiled
18656 * expression
18657 * @param {Object} args Object with local function arguments, the key is
18658 * the name of the argument, and the value is `true`.
18659 * The object may not be mutated, but must be
18660 * extended instead.
18661 * @private
18662 */
18663 function compileAssignmentNode (node, defs, args) {
18664 if (!(node instanceof AssignmentNode)) {
18665 throw new TypeError('No valid AssignmentNode')
18666 }
18667
18668 defs.assign = assign;
18669 defs.access = access;
18670 defs.getSafeProperty = getSafeProperty;
18671 defs.setSafeProperty = setSafeProperty;
18672
18673 var size;
18674 var object = compile(node.object, defs, args);
18675 var index = node.index ? compile(node.index, defs, args) : null;
18676 var value = compile(node.value, defs, args);
18677 var jsName = stringify(node.object.name);
18678
18679 if (!node.index) {
18680 // apply a variable to the scope, for example `a=2`
18681 if (!type.isSymbolNode(node.object)) {
18682 throw new TypeError('SymbolNode expected as object');
18683 }
18684
18685 return 'setSafeProperty(scope, ' + jsName + ', ' + value + ')';
18686 }
18687 else if (node.index.isObjectProperty()) {
18688 // apply an object property for example `a.b=2`
18689 var jsProp = stringify(node.index.getObjectProperty());
18690 return 'setSafeProperty(' + object + ', ' + jsProp + ', ' + value + ')';
18691 }
18692 else if (type.isSymbolNode(node.object)) {
18693 // update a matrix subset, for example `a[2]=3`
18694 size = node.index.needsSize() ? 'var size = math.size(object).valueOf();' : '';
18695
18696 // apply updated object to scope
18697 return '(function () {' +
18698 ' var object = ' + object + ';' +
18699 ' var value = ' + value + ';' +
18700 ' ' + size +
18701 ' setSafeProperty(scope, ' + jsName + ', assign(object, ' + index + ', value));' +
18702 ' return value;' +
18703 '})()';
18704 }
18705 else { // type.isAccessorNode(node.object) === true
18706 // update a matrix subset, for example `a.b[2]=3`
18707 size = node.index.needsSize() ? 'var size = math.size(object).valueOf();' : '';
18708
18709 // we will not use the compile function of the AccessorNode, but compile it
18710 // ourselves here as we need the parent object of the AccessorNode:
18711 // wee need to apply the updated object to parent object
18712 var parentObject = compile(node.object.object, defs, args);
18713
18714 if (node.object.index.isObjectProperty()) {
18715 var jsParentProperty = stringify(node.object.index.getObjectProperty());
18716 return '(function () {' +
18717 ' var parent = ' + parentObject + ';' +
18718 ' var object = getSafeProperty(parent, ' + jsParentProperty + ');' + // parentIndex is a property
18719 ' var value = ' + value + ';' +
18720 size +
18721 ' setSafeProperty(parent, ' + jsParentProperty + ', assign(object, ' + index + ', value));' +
18722 ' return value;' +
18723 '})()';
18724 }
18725 else {
18726 // if some parameters use the 'end' parameter, we need to calculate the size
18727 var parentSize = node.object.index.needsSize() ? 'var size = math.size(parent).valueOf();' : '';
18728 var parentIndex = compile(node.object.index, defs, args);
18729
18730 return '(function () {' +
18731 ' var parent = ' + parentObject + ';' +
18732 ' ' + parentSize +
18733 ' var parentIndex = ' + parentIndex + ';' +
18734 ' var object = access(parent, parentIndex);' +
18735 ' var value = ' + value + ';' +
18736 ' ' + size +
18737 ' assign(parent, parentIndex, assign(object, ' + index + ', value));' +
18738 ' return value;' +
18739 '})()';
18740 }
18741 }
18742 }
18743
18744 // register the compile function
18745 register(AssignmentNode.prototype.type, compileAssignmentNode);
18746
18747 /**
18748 * Execute a callback for each of the child nodes of this node
18749 * @param {function(child: Node, path: string, parent: Node)} callback
18750 */
18751 AssignmentNode.prototype.forEach = function (callback) {
18752 callback(this.object, 'object', this);
18753 if (this.index) {
18754 callback(this.index, 'index', this);
18755 }
18756 callback(this.value, 'value', this);
18757 };
18758
18759 /**
18760 * Create a new AssignmentNode having it's childs be the results of calling
18761 * the provided callback function for each of the childs of the original node.
18762 * @param {function(child: Node, path: string, parent: Node): Node} callback
18763 * @returns {AssignmentNode} Returns a transformed copy of the node
18764 */
18765 AssignmentNode.prototype.map = function (callback) {
18766 var object = this._ifNode(callback(this.object, 'object', this));
18767 var index = this.index
18768 ? this._ifNode(callback(this.index, 'index', this))
18769 : null;
18770 var value = this._ifNode(callback(this.value, 'value', this));
18771
18772 return new AssignmentNode(object, index, value);
18773 };
18774
18775 /**
18776 * Create a clone of this node, a shallow copy
18777 * @return {AssignmentNode}
18778 */
18779 AssignmentNode.prototype.clone = function() {
18780 return new AssignmentNode(this.object, this.index, this.value);
18781 };
18782
18783 /*
18784 * Is parenthesis needed?
18785 * @param {node} node
18786 * @param {string} [parenthesis='keep']
18787 * @private
18788 */
18789 function needParenthesis(node, parenthesis) {
18790 if (!parenthesis) {
18791 parenthesis = 'keep';
18792 }
18793
18794 var precedence = operators.getPrecedence(node, parenthesis);
18795 var exprPrecedence = operators.getPrecedence(node.value, parenthesis);
18796 return (parenthesis === 'all')
18797 || ((exprPrecedence !== null) && (exprPrecedence <= precedence));
18798 }
18799
18800 /**
18801 * Get string representation
18802 * @param {Object} options
18803 * @return {string}
18804 */
18805 AssignmentNode.prototype._toString = function(options) {
18806 var object = this.object.toString(options);
18807 var index = this.index ? this.index.toString(options) : '';
18808 var value = this.value.toString(options);
18809 if (needParenthesis(this, options && options.parenthesis)) {
18810 value = '(' + value + ')';
18811 }
18812
18813 return object + index + ' = ' + value;
18814 };
18815
18816 /**
18817 * Get HTML representation
18818 * @param {Object} options
18819 * @return {string}
18820 */
18821 AssignmentNode.prototype.toHTML = function(options) {
18822 var object = this.object.toHTML(options);
18823 var index = this.index ? this.index.toHTML(options) : '';
18824 var value = this.value.toHTML(options);
18825 if (needParenthesis(this, options && options.parenthesis)) {
18826 value = '<span class="math-paranthesis math-round-parenthesis">(</span>' + value + '<span class="math-paranthesis math-round-parenthesis">)</span>';
18827 }
18828
18829 return object + index + '<span class="math-operator math-assignment-operator math-variable-assignment-operator math-binary-operator">=</span>' + value;
18830 };
18831
18832 /**
18833 * Get LaTeX representation
18834 * @param {Object} options
18835 * @return {string}
18836 */
18837 AssignmentNode.prototype._toTex = function(options) {
18838 var object = this.object.toTex(options);
18839 var index = this.index ? this.index.toTex(options) : '';
18840 var value = this.value.toTex(options);
18841 if (needParenthesis(this, options && options.parenthesis)) {
18842 value = '\\left(' + value + '\\right)';
18843 }
18844
18845 return object + index + ':=' + value;
18846 };
18847
18848 return AssignmentNode;
18849}
18850
18851exports.name = 'AssignmentNode';
18852exports.path = 'expression.node';
18853exports.factory = factory;
18854
18855
18856/***/ }),
18857/* 106 */
18858/***/ (function(module, exports, __webpack_require__) {
18859
18860"use strict";
18861
18862
18863var map = __webpack_require__(2).map;
18864var join = __webpack_require__(2).join;
18865
18866function factory (type, config, load, typed) {
18867 var register = load(__webpack_require__(7)).register;
18868 var compile = load(__webpack_require__(7)).compile;
18869 var Node = load(__webpack_require__(15));
18870 var ResultSet = load(__webpack_require__(95));
18871
18872 /**
18873 * @constructor BlockNode
18874 * @extends {Node}
18875 * Holds a set with blocks
18876 * @param {Array.<{node: Node} | {node: Node, visible: boolean}>} blocks
18877 * An array with blocks, where a block is constructed as an Object
18878 * with properties block, which is a Node, and visible, which is
18879 * a boolean. The property visible is optional and is true by default
18880 */
18881 function BlockNode(blocks) {
18882 if (!(this instanceof BlockNode)) {
18883 throw new SyntaxError('Constructor must be called with the new operator');
18884 }
18885
18886 // validate input, copy blocks
18887 if (!Array.isArray(blocks)) throw new Error('Array expected');
18888 this.blocks = blocks.map(function (block) {
18889 var node = block && block.node;
18890 var visible = block && block.visible !== undefined ? block.visible : true;
18891
18892 if (!type.isNode(node)) throw new TypeError('Property "node" must be a Node');
18893 if (typeof visible !== 'boolean') throw new TypeError('Property "visible" must be a boolean');
18894
18895 return {
18896 node: node,
18897 visible: visible
18898 }
18899 });
18900 }
18901
18902 BlockNode.prototype = new Node();
18903
18904 BlockNode.prototype.type = 'BlockNode';
18905
18906 BlockNode.prototype.isBlockNode = true;
18907
18908 /**
18909 * Compile the node to javascript code
18910 * @param {BlockNode} node The node to be compiled
18911 * @param {Object} defs Object which can be used to define functions
18912 * or constants globally available for the compiled
18913 * expression
18914 * @param {Object} args Object with local function arguments, the key is
18915 * the name of the argument, and the value is `true`.
18916 * The object may not be mutated, but must be
18917 * extended instead.
18918 * @return {string} js
18919 * @private
18920 */
18921 function compileBlockNode (node, defs, args) {
18922 if (!(node instanceof BlockNode)) {
18923 throw new TypeError('No valid BlockNode')
18924 }
18925
18926 defs.ResultSet = ResultSet;
18927 var blocks = map(node.blocks, function (param) {
18928 var js = compile(param.node, defs, args);
18929 if (param.visible) {
18930 return 'results.push(' + js + ');';
18931 }
18932 else {
18933 return js + ';';
18934 }
18935 });
18936
18937 return '(function () {' +
18938 'var results = [];' +
18939 join(blocks, '') +
18940 'return new ResultSet(results);' +
18941 '})()';
18942 }
18943
18944 // register the compile function
18945 register(BlockNode.prototype.type, compileBlockNode);
18946
18947 /**
18948 * Execute a callback for each of the child blocks of this node
18949 * @param {function(child: Node, path: string, parent: Node)} callback
18950 */
18951 BlockNode.prototype.forEach = function (callback) {
18952 for (var i = 0; i < this.blocks.length; i++) {
18953 callback(this.blocks[i].node, 'blocks[' + i + '].node', this);
18954 }
18955 };
18956
18957 /**
18958 * Create a new BlockNode having it's childs be the results of calling
18959 * the provided callback function for each of the childs of the original node.
18960 * @param {function(child: Node, path: string, parent: Node): Node} callback
18961 * @returns {BlockNode} Returns a transformed copy of the node
18962 */
18963 BlockNode.prototype.map = function (callback) {
18964 var blocks = [];
18965 for (var i = 0; i < this.blocks.length; i++) {
18966 var block = this.blocks[i];
18967 var node = this._ifNode(callback(block.node, 'blocks[' + i + '].node', this));
18968 blocks[i] = {
18969 node: node,
18970 visible: block.visible
18971 };
18972 }
18973 return new BlockNode(blocks);
18974 };
18975
18976 /**
18977 * Create a clone of this node, a shallow copy
18978 * @return {BlockNode}
18979 */
18980 BlockNode.prototype.clone = function () {
18981 var blocks = this.blocks.map(function (block) {
18982 return {
18983 node: block.node,
18984 visible: block.visible
18985 };
18986 });
18987
18988 return new BlockNode(blocks);
18989 };
18990
18991 /**
18992 * Get string representation
18993 * @param {Object} options
18994 * @return {string} str
18995 * @override
18996 */
18997 BlockNode.prototype._toString = function (options) {
18998 return this.blocks.map(function (param) {
18999 return param.node.toString(options) + (param.visible ? '' : ';');
19000 }).join('\n');
19001 };
19002
19003 /**
19004 * Get HTML representation
19005 * @param {Object} options
19006 * @return {string} str
19007 * @override
19008 */
19009 BlockNode.prototype.toHTML = function (options) {
19010 return this.blocks.map(function (param) {
19011 return param.node.toHTML(options) + (param.visible ? '' : '<span class="math-separator">;</span>');
19012 }).join('<span class="math-separator"><br /></span>');
19013 };
19014
19015 /**
19016 * Get LaTeX representation
19017 * @param {Object} options
19018 * @return {string} str
19019 */
19020 BlockNode.prototype._toTex = function (options) {
19021 return this.blocks.map(function (param) {
19022 return param.node.toTex(options) + (param.visible ? '' : ';');
19023 }).join('\\;\\;\n');
19024 };
19025
19026 return BlockNode;
19027}
19028
19029exports.name = 'BlockNode';
19030exports.path = 'expression.node';
19031exports.factory = factory;
19032
19033
19034/***/ }),
19035/* 107 */
19036/***/ (function(module, exports, __webpack_require__) {
19037
19038"use strict";
19039
19040
19041var latex = __webpack_require__(4);
19042var operators = __webpack_require__(54);
19043
19044function factory (type, config, load, typed) {
19045 var register = load(__webpack_require__(7)).register;
19046 var compile = load(__webpack_require__(7)).compile;
19047 var Node = load(__webpack_require__(15));
19048
19049 /**
19050 * A lazy evaluating conditional operator: 'condition ? trueExpr : falseExpr'
19051 *
19052 * @param {Node} condition Condition, must result in a boolean
19053 * @param {Node} trueExpr Expression evaluated when condition is true
19054 * @param {Node} falseExpr Expression evaluated when condition is true
19055 *
19056 * @constructor ConditionalNode
19057 * @extends {Node}
19058 */
19059 function ConditionalNode(condition, trueExpr, falseExpr) {
19060 if (!(this instanceof ConditionalNode)) {
19061 throw new SyntaxError('Constructor must be called with the new operator');
19062 }
19063 if (!type.isNode(condition)) throw new TypeError('Parameter condition must be a Node');
19064 if (!type.isNode(trueExpr)) throw new TypeError('Parameter trueExpr must be a Node');
19065 if (!type.isNode(falseExpr)) throw new TypeError('Parameter falseExpr must be a Node');
19066
19067 this.condition = condition;
19068 this.trueExpr = trueExpr;
19069 this.falseExpr = falseExpr;
19070 }
19071
19072 ConditionalNode.prototype = new Node();
19073
19074 ConditionalNode.prototype.type = 'ConditionalNode';
19075
19076 ConditionalNode.prototype.isConditionalNode = true;
19077
19078 /**
19079 * Compile the node to javascript code
19080 * @param {ConditionalNode} node The node to be compiled
19081 * @param {Object} defs Object which can be used to define functions
19082 * or constants globally available for the compiled
19083 * expression
19084 * @param {Object} args Object with local function arguments, the key is
19085 * the name of the argument, and the value is `true`.
19086 * The object may not be mutated, but must be
19087 * extended instead.
19088 * @return {string} js
19089 * @private
19090 */
19091 function compileConditionalNode(node, defs, args) {
19092 if (!(node instanceof ConditionalNode)) {
19093 throw new TypeError('No valid ConditionalNode')
19094 }
19095
19096 /**
19097 * Test whether a condition is met
19098 * @param {*} condition
19099 * @returns {boolean} true if condition is true or non-zero, else false
19100 */
19101 defs.testCondition = function (condition) {
19102 if (typeof condition === 'number'
19103 || typeof condition === 'boolean'
19104 || typeof condition === 'string') {
19105 return condition ? true : false;
19106 }
19107
19108 if (condition) {
19109 if (type.isBigNumber(condition)) {
19110 return condition.isZero() ? false : true;
19111 }
19112
19113 if (type.isComplex(condition)) {
19114 return (condition.re || condition.im) ? true : false;
19115 }
19116
19117 if (type.isUnit(condition)) {
19118 return condition.value ? true : false;
19119 }
19120 }
19121
19122 if (condition === null || condition === undefined) {
19123 return false;
19124 }
19125
19126 throw new TypeError('Unsupported type of condition "' + defs.math['typeof'](condition) + '"');
19127 };
19128
19129 return (
19130 'testCondition(' + compile(node.condition, defs, args) + ') ? ' +
19131 '( ' + compile(node.trueExpr, defs, args) + ') : ' +
19132 '( ' + compile(node.falseExpr, defs, args) + ')'
19133 );
19134 }
19135
19136 // register the compile function
19137 register(ConditionalNode.prototype.type, compileConditionalNode);
19138
19139 /**
19140 * Execute a callback for each of the child nodes of this node
19141 * @param {function(child: Node, path: string, parent: Node)} callback
19142 */
19143 ConditionalNode.prototype.forEach = function (callback) {
19144 callback(this.condition, 'condition', this);
19145 callback(this.trueExpr, 'trueExpr', this);
19146 callback(this.falseExpr, 'falseExpr', this);
19147 };
19148
19149 /**
19150 * Create a new ConditionalNode having it's childs be the results of calling
19151 * the provided callback function for each of the childs of the original node.
19152 * @param {function(child: Node, path: string, parent: Node): Node} callback
19153 * @returns {ConditionalNode} Returns a transformed copy of the node
19154 */
19155 ConditionalNode.prototype.map = function (callback) {
19156 return new ConditionalNode(
19157 this._ifNode(callback(this.condition, 'condition', this)),
19158 this._ifNode(callback(this.trueExpr, 'trueExpr', this)),
19159 this._ifNode(callback(this.falseExpr, 'falseExpr', this))
19160 );
19161 };
19162
19163 /**
19164 * Create a clone of this node, a shallow copy
19165 * @return {ConditionalNode}
19166 */
19167 ConditionalNode.prototype.clone = function () {
19168 return new ConditionalNode(this.condition, this.trueExpr, this.falseExpr);
19169 };
19170
19171 /**
19172 * Get string representation
19173 * @param {Object} options
19174 * @return {string} str
19175 */
19176 ConditionalNode.prototype._toString = function (options) {
19177 var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep';
19178 var precedence = operators.getPrecedence(this, parenthesis);
19179
19180 //Enclose Arguments in parentheses if they are an OperatorNode
19181 //or have lower or equal precedence
19182 //NOTE: enclosing all OperatorNodes in parentheses is a decision
19183 //purely based on aesthetics and readability
19184 var condition = this.condition.toString(options);
19185 var conditionPrecedence = operators.getPrecedence(this.condition, parenthesis);
19186 if ((parenthesis === 'all')
19187 || (this.condition.type === 'OperatorNode')
19188 || ((conditionPrecedence !== null) && (conditionPrecedence <= precedence))) {
19189 condition = '(' + condition + ')';
19190 }
19191
19192 var trueExpr = this.trueExpr.toString(options);
19193 var truePrecedence = operators.getPrecedence(this.trueExpr, parenthesis);
19194 if ((parenthesis === 'all')
19195 || (this.trueExpr.type === 'OperatorNode')
19196 || ((truePrecedence !== null) && (truePrecedence <= precedence))) {
19197 trueExpr = '(' + trueExpr + ')';
19198 }
19199
19200 var falseExpr = this.falseExpr.toString(options);
19201 var falsePrecedence = operators.getPrecedence(this.falseExpr, parenthesis);
19202 if ((parenthesis === 'all')
19203 || (this.falseExpr.type === 'OperatorNode')
19204 || ((falsePrecedence !== null) && (falsePrecedence <= precedence))) {
19205 falseExpr = '(' + falseExpr + ')';
19206 }
19207 return condition + ' ? ' + trueExpr + ' : ' + falseExpr;
19208 };
19209
19210 /**
19211 * Get HTML representation
19212 * @param {Object} options
19213 * @return {string} str
19214 */
19215 ConditionalNode.prototype.toHTML = function (options) {
19216 var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep';
19217 var precedence = operators.getPrecedence(this, parenthesis);
19218
19219 //Enclose Arguments in parentheses if they are an OperatorNode
19220 //or have lower or equal precedence
19221 //NOTE: enclosing all OperatorNodes in parentheses is a decision
19222 //purely based on aesthetics and readability
19223 var condition = this.condition.toHTML(options);
19224 var conditionPrecedence = operators.getPrecedence(this.condition, parenthesis);
19225 if ((parenthesis === 'all')
19226 || (this.condition.type === 'OperatorNode')
19227 || ((conditionPrecedence !== null) && (conditionPrecedence <= precedence))) {
19228 condition = '<span class="math-parenthesis math-round-parenthesis">(</span>' + condition + '<span class="math-parenthesis math-round-parenthesis">)</span>';
19229 }
19230
19231 var trueExpr = this.trueExpr.toHTML(options);
19232 var truePrecedence = operators.getPrecedence(this.trueExpr, parenthesis);
19233 if ((parenthesis === 'all')
19234 || (this.trueExpr.type === 'OperatorNode')
19235 || ((truePrecedence !== null) && (truePrecedence <= precedence))) {
19236 trueExpr = '<span class="math-parenthesis math-round-parenthesis">(</span>' + trueExpr + '<span class="math-parenthesis math-round-parenthesis">)</span>';
19237 }
19238
19239 var falseExpr = this.falseExpr.toHTML(options);
19240 var falsePrecedence = operators.getPrecedence(this.falseExpr, parenthesis);
19241 if ((parenthesis === 'all')
19242 || (this.falseExpr.type === 'OperatorNode')
19243 || ((falsePrecedence !== null) && (falsePrecedence <= precedence))) {
19244 falseExpr = '<span class="math-parenthesis math-round-parenthesis">(</span>' + falseExpr + '<span class="math-parenthesis math-round-parenthesis">)</span>';
19245 }
19246 return condition + '<span class="math-operator math-conditional-operator">?</span>' + trueExpr + '<span class="math-operator math-conditional-operator">:</span>' + falseExpr;
19247 };
19248
19249 /**
19250 * Get LaTeX representation
19251 * @param {Object} options
19252 * @return {string} str
19253 */
19254 ConditionalNode.prototype._toTex = function (options) {
19255 return '\\begin{cases} {'
19256 + this.trueExpr.toTex(options) + '}, &\\quad{\\text{if }\\;'
19257 + this.condition.toTex(options)
19258 + '}\\\\{' + this.falseExpr.toTex(options)
19259 + '}, &\\quad{\\text{otherwise}}\\end{cases}';
19260 };
19261
19262 return ConditionalNode;
19263}
19264
19265exports.name = 'ConditionalNode';
19266exports.path = 'expression.node';
19267exports.factory = factory;
19268
19269
19270/***/ }),
19271/* 108 */
19272/***/ (function(module, exports, __webpack_require__) {
19273
19274"use strict";
19275
19276
19277var keywords = __webpack_require__(77);
19278var stringify = __webpack_require__(9).stringify;
19279var escape = __webpack_require__(9).escape;
19280var map = __webpack_require__(2).map;
19281var join = __webpack_require__(2).join;
19282var latex = __webpack_require__(4);
19283var operators = __webpack_require__(54);
19284var setSafeProperty = __webpack_require__(13).setSafeProperty;
19285var getUniqueArgumentName = __webpack_require__(109);
19286
19287function factory (type, config, load, typed) {
19288 var register = load(__webpack_require__(7)).register;
19289 var compile = load(__webpack_require__(7)).compile;
19290 var Node = load(__webpack_require__(15));
19291
19292 /**
19293 * @constructor FunctionAssignmentNode
19294 * @extends {Node}
19295 * Function assignment
19296 *
19297 * @param {string} name Function name
19298 * @param {string[] | Array.<{name: string, type: string}>} params
19299 * Array with function parameter names, or an
19300 * array with objects containing the name
19301 * and type of the parameter
19302 * @param {Node} expr The function expression
19303 */
19304 function FunctionAssignmentNode(name, params, expr) {
19305 if (!(this instanceof FunctionAssignmentNode)) {
19306 throw new SyntaxError('Constructor must be called with the new operator');
19307 }
19308
19309 // validate input
19310 if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"');
19311 if (!Array.isArray(params)) throw new TypeError('Array containing strings or objects expected for parameter "params"');
19312 if (!type.isNode(expr)) throw new TypeError('Node expected for parameter "expr"');
19313 if (name in keywords) throw new Error('Illegal function name, "' + name + '" is a reserved keyword');
19314
19315 this.name = name;
19316 this.params = params.map(function (param) {
19317 return param && param.name || param;
19318 });
19319 this.types = params.map(function (param) {
19320 return param && param.type || 'any'
19321 });
19322 this.expr = expr;
19323 }
19324
19325 FunctionAssignmentNode.prototype = new Node();
19326
19327 FunctionAssignmentNode.prototype.type = 'FunctionAssignmentNode';
19328
19329 FunctionAssignmentNode.prototype.isFunctionAssignmentNode = true;
19330
19331 /**
19332 * Compile the node to javascript code
19333 * @param {FunctionAssignmentNode} node The node to be compiled
19334 * @param {Object} defs Object which can be used to define functions
19335 * or constants globally available for the compiled
19336 * expression
19337 * @param {Object} args Object with local function arguments, the key is
19338 * the name of the argument, and the value is `true`.
19339 * The object may not be mutated, but must be
19340 * extended instead.
19341 * @return {string} js
19342 * @private
19343 */
19344 function compileFunctionAssignmentNode(node, defs, args) {
19345 if (!(node instanceof FunctionAssignmentNode)) {
19346 throw new TypeError('No valid FunctionAssignmentNode')
19347 }
19348
19349 defs.typed = typed;
19350 defs.setSafeProperty = setSafeProperty;
19351
19352 // validate params
19353 // FIXME: rename parameters to safe, internal names
19354
19355 // we extend the original args and add the args to the child object
19356 // and create a mapping from the unsafe param name to a safe, internal one
19357 var childArgs = Object.create(args);
19358 var jsParams = map(node.params, function (param) {
19359 childArgs[param] = getUniqueArgumentName(childArgs);
19360 return childArgs[param];
19361 });
19362
19363 // compile the function expression with the child args
19364 var jsExpr = compile(node.expr, defs, childArgs);
19365 var jsName = stringify(node.name);
19366
19367 return 'setSafeProperty(scope, ' + jsName + ', ' +
19368 ' (function () {' +
19369 ' var fn = typed(' + jsName + ', {' +
19370 ' ' + stringify(join(node.types, ',')) + ': function (' + join(jsParams, ',') + ') {' +
19371 ' return ' + jsExpr + '' +
19372 ' }' +
19373 ' });' +
19374 ' fn.syntax = ' + stringify(node.name + '(' + join(node.params, ', ') + ')') + ';' +
19375 ' return fn;' +
19376 ' })())';
19377 }
19378
19379 // register the compile function
19380 register(FunctionAssignmentNode.prototype.type, compileFunctionAssignmentNode);
19381
19382 /**
19383 * Execute a callback for each of the child nodes of this node
19384 * @param {function(child: Node, path: string, parent: Node)} callback
19385 */
19386 FunctionAssignmentNode.prototype.forEach = function (callback) {
19387 callback(this.expr, 'expr', this);
19388 };
19389
19390 /**
19391 * Create a new FunctionAssignmentNode having it's childs be the results of calling
19392 * the provided callback function for each of the childs of the original node.
19393 * @param {function(child: Node, path: string, parent: Node): Node} callback
19394 * @returns {FunctionAssignmentNode} Returns a transformed copy of the node
19395 */
19396 FunctionAssignmentNode.prototype.map = function (callback) {
19397 var expr = this._ifNode(callback(this.expr, 'expr', this));
19398
19399 return new FunctionAssignmentNode(this.name, this.params.slice(0), expr);
19400 };
19401
19402 /**
19403 * Create a clone of this node, a shallow copy
19404 * @return {FunctionAssignmentNode}
19405 */
19406 FunctionAssignmentNode.prototype.clone = function () {
19407 return new FunctionAssignmentNode(this.name, this.params.slice(0), this.expr);
19408 };
19409
19410 /**
19411 * Is parenthesis needed?
19412 * @param {Node} node
19413 * @param {Object} parenthesis
19414 * @private
19415 */
19416 function needParenthesis(node, parenthesis) {
19417 var precedence = operators.getPrecedence(node, parenthesis);
19418 var exprPrecedence = operators.getPrecedence(node.expr, parenthesis);
19419
19420 return (parenthesis === 'all')
19421 || ((exprPrecedence !== null) && (exprPrecedence <= precedence));
19422 }
19423
19424 /**
19425 * get string representation
19426 * @param {Object} options
19427 * @return {string} str
19428 */
19429 FunctionAssignmentNode.prototype._toString = function (options) {
19430 var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep';
19431 var expr = this.expr.toString(options);
19432 if (needParenthesis(this, parenthesis)) {
19433 expr = '(' + expr + ')';
19434 }
19435 return this.name + '(' + this.params.join(', ') + ') = ' + expr;
19436 };
19437
19438 /**
19439 * get HTML representation
19440 * @param {Object} options
19441 * @return {string} str
19442 */
19443 FunctionAssignmentNode.prototype.toHTML = function (options) {
19444 var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep';
19445 var params = [];
19446 for (var i=0; i<this.params.length; i++) {
19447 params.push('<span class="math-symbol math-parameter">' + escape(this.params[i]) + '</span>');
19448 }
19449 var expr = this.expr.toHTML(options);
19450 if (needParenthesis(this, parenthesis)) {
19451 expr = '<span class="math-parenthesis math-round-parenthesis">(</span>' + expr + '<span class="math-parenthesis math-round-parenthesis">)</span>';
19452 }
19453 return '<span class="math-function">' + 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;
19454 };
19455
19456 /**
19457 * get LaTeX representation
19458 * @param {Object} options
19459 * @return {string} str
19460 */
19461 FunctionAssignmentNode.prototype._toTex = function (options) {
19462 var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep';
19463 var expr = this.expr.toTex(options);
19464 if (needParenthesis(this, parenthesis)) {
19465 expr = '\\left(' + expr + '\\right)';
19466 }
19467
19468 return '\\mathrm{' + this.name
19469 + '}\\left(' + this.params.map(latex.toSymbol).join(',') + '\\right):=' + expr;
19470 };
19471
19472 return FunctionAssignmentNode;
19473}
19474exports.name = 'FunctionAssignmentNode';
19475exports.path = 'expression.node';
19476exports.factory = factory;
19477
19478
19479/***/ }),
19480/* 109 */
19481/***/ (function(module, exports) {
19482
19483/**
19484 * Get a unique name for an argument name to store in defs
19485 * @param {Object} defs
19486 * @return {string} A string like 'arg1', 'arg2', ...
19487 * @private
19488 */
19489function getUniqueArgumentName (defs) {
19490 return 'arg' + Object.keys(defs).length
19491}
19492
19493module.exports = getUniqueArgumentName;
19494
19495
19496/***/ }),
19497/* 110 */
19498/***/ (function(module, exports, __webpack_require__) {
19499
19500"use strict";
19501
19502
19503var stringify = __webpack_require__(9).stringify;
19504var escape = __webpack_require__(9).escape;
19505var isSafeProperty = __webpack_require__(13).isSafeProperty;
19506var hasOwnProperty = __webpack_require__(5).hasOwnProperty;
19507
19508function factory (type, config, load, typed) {
19509 var register = load(__webpack_require__(7)).register;
19510 var compile = load(__webpack_require__(7)).compile;
19511 var Node = load(__webpack_require__(15));
19512
19513 /**
19514 * @constructor ObjectNode
19515 * @extends {Node}
19516 * Holds an object with keys/values
19517 * @param {Object.<string, Node>} [properties] array with key/value pairs
19518 */
19519 function ObjectNode(properties) {
19520 if (!(this instanceof ObjectNode)) {
19521 throw new SyntaxError('Constructor must be called with the new operator');
19522 }
19523
19524 this.properties = properties || {};
19525
19526 // validate input
19527 if (properties) {
19528 if (!(typeof properties === 'object') || !Object.keys(properties).every(function (key) {
19529 return type.isNode(properties[key]);
19530 })) {
19531 throw new TypeError('Object containing Nodes expected');
19532 }
19533 }
19534 }
19535
19536 ObjectNode.prototype = new Node();
19537
19538 ObjectNode.prototype.type = 'ObjectNode';
19539
19540 ObjectNode.prototype.isObjectNode = true;
19541
19542 /**
19543 * Compile the node to javascript code
19544 * @param {ObjectNode} node The node to be compiled
19545 * @param {Object} defs Object which can be used to define functions
19546 * or constants globally available for the compiled
19547 * expression
19548 * @param {Object} args Object with local function arguments, the key is
19549 * the name of the argument, and the value is `true`.
19550 * The object may not be mutated, but must be
19551 * extended instead.
19552 * @return {string} code
19553 * @private
19554 */
19555 function compileObjectNode(node, defs, args) {
19556 if (!(node instanceof ObjectNode)) {
19557 throw new TypeError('No valid ObjectNode')
19558 }
19559
19560 var entries = [];
19561 for (var key in node.properties) {
19562 if (hasOwnProperty(node.properties, key)) {
19563 // we stringify/parse the key here to resolve unicode characters,
19564 // so you cannot create a key like {"co\\u006Estructor": null}
19565 var stringifiedKey = stringify(key)
19566 var parsedKey = JSON.parse(stringifiedKey)
19567 if (!isSafeProperty(node.properties, parsedKey)) {
19568 throw new Error('No access to property "' + parsedKey + '"');
19569 }
19570
19571 entries.push(stringifiedKey + ': ' + compile(node.properties[key], defs, args));
19572 }
19573 }
19574 return '{' + entries.join(', ') + '}';
19575 }
19576
19577 // register the compile function
19578 register(ObjectNode.prototype.type, compileObjectNode);
19579
19580 /**
19581 * Execute a callback for each of the child nodes of this node
19582 * @param {function(child: Node, path: string, parent: Node)} callback
19583 */
19584 ObjectNode.prototype.forEach = function (callback) {
19585 for (var key in this.properties) {
19586 if (this.properties.hasOwnProperty(key)) {
19587 callback(this.properties[key], 'properties[' + stringify(key) + ']', this);
19588 }
19589 }
19590 };
19591
19592 /**
19593 * Create a new ObjectNode having it's childs be the results of calling
19594 * the provided callback function for each of the childs of the original node.
19595 * @param {function(child: Node, path: string, parent: Node): Node} callback
19596 * @returns {ObjectNode} Returns a transformed copy of the node
19597 */
19598 ObjectNode.prototype.map = function (callback) {
19599 var properties = {};
19600 for (var key in this.properties) {
19601 if (this.properties.hasOwnProperty(key)) {
19602 properties[key] = this._ifNode(callback(this.properties[key],
19603 'properties[' + stringify(key) + ']', this));
19604 }
19605 }
19606 return new ObjectNode(properties);
19607 };
19608
19609 /**
19610 * Create a clone of this node, a shallow copy
19611 * @return {ObjectNode}
19612 */
19613 ObjectNode.prototype.clone = function() {
19614 var properties = {};
19615 for (var key in this.properties) {
19616 if (this.properties.hasOwnProperty(key)) {
19617 properties[key] = this.properties[key];
19618 }
19619 }
19620 return new ObjectNode(properties);
19621 };
19622
19623 /**
19624 * Get string representation
19625 * @param {Object} options
19626 * @return {string} str
19627 * @override
19628 */
19629 ObjectNode.prototype._toString = function(options) {
19630 var entries = [];
19631 for (var key in this.properties) {
19632 if (this.properties.hasOwnProperty(key)) {
19633 entries.push(stringify(key) + ': ' + this.properties[key].toString(options));
19634 }
19635 }
19636 return '{' + entries.join(', ') + '}';
19637 };
19638
19639 /**
19640 * Get HTML representation
19641 * @param {Object} options
19642 * @return {string} str
19643 * @override
19644 */
19645 ObjectNode.prototype.toHTML = function(options) {
19646 var entries = [];
19647 for (var key in this.properties) {
19648 if (this.properties.hasOwnProperty(key)) {
19649 entries.push('<span class="math-symbol math-property">' + escape(key) + '</span>' + '<span class="math-operator math-assignment-operator math-property-assignment-operator math-binary-operator">:</span>' + this.properties[key].toHTML(options));
19650 }
19651 }
19652 return '<span class="math-parenthesis math-curly-parenthesis">{</span>' + entries.join('<span class="math-separator">,</span>') + '<span class="math-parenthesis math-curly-parenthesis">}</span>';
19653 };
19654
19655 /**
19656 * Get LaTeX representation
19657 * @param {Object} options
19658 * @return {string} str
19659 */
19660 ObjectNode.prototype._toTex = function(options) {
19661 var entries = [];
19662 for (var key in this.properties) {
19663 if (this.properties.hasOwnProperty(key)) {
19664 entries.push("\\mathbf{" + key + ':} & ' + this.properties[key].toTex(options) + "\\\\");
19665 }
19666 }
19667 return '\\left\\{\\begin{array}{ll}' + entries.join('\n') + '\\end{array}\\right\\}';
19668 };
19669
19670 return ObjectNode;
19671}
19672
19673exports.name = 'ObjectNode';
19674exports.path = 'expression.node';
19675exports.factory = factory;
19676
19677
19678/***/ }),
19679/* 111 */
19680/***/ (function(module, exports, __webpack_require__) {
19681
19682"use strict";
19683
19684
19685function factory (type, config, load, typed) {
19686 var parse = load(__webpack_require__(41));
19687
19688 /**
19689 * Parse an expression. Returns a node tree, which can be evaluated by
19690 * invoking node.eval();
19691 *
19692 * Note the evaluating arbitrary expressions may involve security risks,
19693 * see [http://mathjs.org/docs/expressions/security.html](http://mathjs.org/docs/expressions/security.html) for more information.
19694 *
19695 * Syntax:
19696 *
19697 * math.parse(expr)
19698 * math.parse(expr, options)
19699 * math.parse([expr1, expr2, expr3, ...])
19700 * math.parse([expr1, expr2, expr3, ...], options)
19701 *
19702 * Example:
19703 *
19704 * var node = math.parse('sqrt(3^2 + 4^2)');
19705 * node.compile().eval(); // 5
19706 *
19707 * var scope = {a:3, b:4}
19708 * var node = math.parse('a * b'); // 12
19709 * var code = node.compile();
19710 * code.eval(scope); // 12
19711 * scope.a = 5;
19712 * code.eval(scope); // 20
19713 *
19714 * var nodes = math.parse(['a = 3', 'b = 4', 'a * b']);
19715 * nodes[2].compile().eval(); // 12
19716 *
19717 * See also:
19718 *
19719 * eval, compile
19720 *
19721 * @param {string | string[] | Matrix} expr Expression to be parsed
19722 * @param {{nodes: Object<string, Node>}} [options] Available options:
19723 * - `nodes` a set of custom nodes
19724 * @return {Node | Node[]} node
19725 * @throws {Error}
19726 */
19727 return typed('parse', {
19728 'string | Array | Matrix': parse,
19729 'string | Array | Matrix, Object': parse
19730 });
19731}
19732
19733exports.name = 'parse';
19734exports.factory = factory;
19735
19736
19737/***/ }),
19738/* 112 */
19739/***/ (function(module, exports, __webpack_require__) {
19740
19741"use strict";
19742
19743
19744function factory (type, config, load, typed, math) {
19745 var Parser = load(__webpack_require__(113));
19746
19747 /**
19748 * Create a parser. The function creates a new `math.expression.Parser` object.
19749 *
19750 * Syntax:
19751 *
19752 * math.parser()
19753 *
19754 * Examples:
19755 *
19756 * var parser = new math.parser();
19757 *
19758 * // evaluate expressions
19759 * var a = parser.eval('sqrt(3^2 + 4^2)'); // 5
19760 * var b = parser.eval('sqrt(-4)'); // 2i
19761 * var c = parser.eval('2 inch in cm'); // 5.08 cm
19762 * var d = parser.eval('cos(45 deg)'); // 0.7071067811865476
19763 *
19764 * // define variables and functions
19765 * parser.eval('x = 7 / 2'); // 3.5
19766 * parser.eval('x + 3'); // 6.5
19767 * parser.eval('function f(x, y) = x^y'); // f(x, y)
19768 * parser.eval('f(2, 3)'); // 8
19769 *
19770 * // get and set variables and functions
19771 * var x = parser.get('x'); // 7
19772 * var f = parser.get('f'); // function
19773 * var g = f(3, 2); // 9
19774 * parser.set('h', 500);
19775 * var i = parser.eval('h / 2'); // 250
19776 * parser.set('hello', function (name) {
19777 * return 'hello, ' + name + '!';
19778 * });
19779 * parser.eval('hello("user")'); // "hello, user!"
19780 *
19781 * // clear defined functions and variables
19782 * parser.clear();
19783 *
19784 * See also:
19785 *
19786 * eval, compile, parse
19787 *
19788 * @return {Parser} Parser
19789 */
19790 return typed('parser', {
19791 '': function () {
19792 return new Parser(math);
19793 }
19794 });
19795}
19796
19797exports.name = 'parser';
19798exports.factory = factory;
19799exports.math = true; // requires the math namespace as 5th argument
19800
19801
19802/***/ }),
19803/* 113 */
19804/***/ (function(module, exports, __webpack_require__) {
19805
19806"use strict";
19807
19808
19809var extend = __webpack_require__(5).extend;
19810var customs = __webpack_require__(13);
19811
19812function factory (type, config, load, typed, math) {
19813 var _parse = load(__webpack_require__(41));
19814
19815 /**
19816 * @constructor Parser
19817 * Parser contains methods to evaluate or parse expressions, and has a number
19818 * of convenience methods to get, set, and remove variables from memory. Parser
19819 * keeps a scope containing variables in memory, which is used for all
19820 * evaluations.
19821 *
19822 * Methods:
19823 * var result = parser.eval(expr); // evaluate an expression
19824 * var value = parser.get(name); // retrieve a variable from the parser
19825 * var values = parser.getAll(); // retrieve all defined variables
19826 * parser.set(name, value); // set a variable in the parser
19827 * parser.remove(name); // clear a variable from the
19828 * // parsers scope
19829 * parser.clear(); // clear the parsers scope
19830 *
19831 * Example usage:
19832 * var parser = new Parser();
19833 * // Note: there is a convenience method which can be used instead:
19834 * // var parser = new math.parser();
19835 *
19836 * // evaluate expressions
19837 * parser.eval('sqrt(3^2 + 4^2)'); // 5
19838 * parser.eval('sqrt(-4)'); // 2i
19839 * parser.eval('2 inch in cm'); // 5.08 cm
19840 * parser.eval('cos(45 deg)'); // 0.7071067811865476
19841 *
19842 * // define variables and functions
19843 * parser.eval('x = 7 / 2'); // 3.5
19844 * parser.eval('x + 3'); // 6.5
19845 * parser.eval('function f(x, y) = x^y'); // f(x, y)
19846 * parser.eval('f(2, 3)'); // 8
19847 *
19848 * // get and set variables and functions
19849 * var x = parser.get('x'); // 7
19850 * var f = parser.get('f'); // function
19851 * var g = f(3, 2); // 9
19852 * parser.set('h', 500);
19853 * var i = parser.eval('h / 2'); // 250
19854 * parser.set('hello', function (name) {
19855 * return 'hello, ' + name + '!';
19856 * });
19857 * parser.eval('hello("user")'); // "hello, user!"
19858 *
19859 * // clear defined functions and variables
19860 * parser.clear();
19861 *
19862 */
19863 function Parser() {
19864 if (!(this instanceof Parser)) {
19865 throw new SyntaxError(
19866 'Constructor must be called with the new operator');
19867 }
19868 this.scope = {};
19869 }
19870
19871 /**
19872 * Attach type information
19873 */
19874 Parser.prototype.type = 'Parser';
19875 Parser.prototype.isParser = true;
19876
19877 /**
19878 * Parse an expression and return the parsed function node.
19879 * The node tree can be compiled via `code = node.compile(math)`,
19880 * and the compiled code can be executed as `code.eval([scope])`
19881 * @param {string} expr
19882 * @return {Node} node
19883 * @throws {Error}
19884 */
19885 Parser.prototype.parse = function (expr) {
19886 throw new Error('Parser.parse is deprecated. Use math.parse instead.');
19887 };
19888
19889 /**
19890 * Parse and compile an expression, return the compiled javascript code.
19891 * The node can be evaluated via code.eval([scope])
19892 * @param {string} expr
19893 * @return {{eval: function}} code
19894 * @throws {Error}
19895 */
19896 Parser.prototype.compile = function (expr) {
19897 throw new Error('Parser.compile is deprecated. Use math.compile instead.');
19898 };
19899
19900 /**
19901 * Parse and evaluate the given expression
19902 * @param {string} expr A string containing an expression, for example "2+3"
19903 * @return {*} result The result, or undefined when the expression was empty
19904 * @throws {Error}
19905 */
19906 Parser.prototype.eval = function (expr) {
19907 // TODO: validate arguments
19908 return _parse(expr)
19909 .compile()
19910 .eval(this.scope);
19911 };
19912
19913 /**
19914 * Get a variable (a function or variable) by name from the parsers scope.
19915 * Returns undefined when not found
19916 * @param {string} name
19917 * @return {* | undefined} value
19918 */
19919 Parser.prototype.get = function (name) {
19920 // TODO: validate arguments
19921 return name in this.scope
19922 ? customs.getSafeProperty(this.scope, name)
19923 : undefined;
19924 };
19925
19926 /**
19927 * Get a map with all defined variables
19928 * @return {Object} values
19929 */
19930 Parser.prototype.getAll = function () {
19931 return extend({}, this.scope);
19932 };
19933
19934 /**
19935 * Set a symbol (a function or variable) by name from the parsers scope.
19936 * @param {string} name
19937 * @param {* | undefined} value
19938 */
19939 Parser.prototype.set = function (name, value) {
19940 // TODO: validate arguments
19941 return customs.setSafeProperty(this.scope, name, value);
19942 };
19943
19944 /**
19945 * Remove a variable from the parsers scope
19946 * @param {string} name
19947 */
19948 Parser.prototype.remove = function (name) {
19949 // TODO: validate arguments
19950 delete this.scope[name];
19951 };
19952
19953 /**
19954 * Clear the scope with variables and functions
19955 */
19956 Parser.prototype.clear = function () {
19957 for (var name in this.scope) {
19958 if (this.scope.hasOwnProperty(name)) {
19959 delete this.scope[name];
19960 }
19961 }
19962 };
19963
19964 return Parser;
19965}
19966
19967exports.name = 'Parser';
19968exports.path = 'expression';
19969exports.factory = factory;
19970exports.math = true; // requires the math namespace as 5th argument
19971
19972
19973/***/ }),
19974/* 114 */
19975/***/ (function(module, exports, __webpack_require__) {
19976
19977"use strict";
19978
19979
19980var deepForEach = __webpack_require__(43);
19981var reduce = __webpack_require__(65);
19982var containsCollections = __webpack_require__(66);
19983
19984function factory (type, config, load, typed) {
19985 var larger = load(__webpack_require__(34));
19986
19987 /**
19988 * Compute the maximum value of a matrix or a list with values.
19989 * In case of a multi dimensional array, the maximum of the flattened array
19990 * will be calculated. When `dim` is provided, the maximum over the selected
19991 * dimension will be calculated. Parameter `dim` is zero-based.
19992 *
19993 * Syntax:
19994 *
19995 * math.max(a, b, c, ...)
19996 * math.max(A)
19997 * math.max(A, dim)
19998 *
19999 * Examples:
20000 *
20001 * math.max(2, 1, 4, 3); // returns 4
20002 * math.max([2, 1, 4, 3]); // returns 4
20003 *
20004 * // maximum over a specified dimension (zero-based)
20005 * math.max([[2, 5], [4, 3], [1, 7]], 0); // returns [4, 7]
20006 * math.max([[2, 5], [4, 3]], [1, 7], 1); // returns [5, 4, 7]
20007 *
20008 * math.max(2.7, 7.1, -4.5, 2.0, 4.1); // returns 7.1
20009 * math.min(2.7, 7.1, -4.5, 2.0, 4.1); // returns -4.5
20010 *
20011 * See also:
20012 *
20013 * mean, median, min, prod, std, sum, var
20014 *
20015 * @param {... *} args A single matrix or or multiple scalar values
20016 * @return {*} The maximum value
20017 */
20018 var max = typed('max', {
20019 // max([a, b, c, d, ...])
20020 'Array | Matrix': _max,
20021
20022 // max([a, b, c, d, ...], dim)
20023 'Array | Matrix, number | BigNumber': function (array, dim) {
20024 return reduce(array, dim.valueOf(), _largest);
20025 },
20026
20027 // max(a, b, c, d, ...)
20028 '...': function (args) {
20029 if (containsCollections(args)) {
20030 throw new TypeError('Scalar values expected in function max');
20031 }
20032
20033 return _max(args);
20034 }
20035 });
20036
20037 max.toTex = '\\max\\left(${args}\\right)';
20038
20039 return max;
20040
20041 /**
20042 * Return the largest of two values
20043 * @param {*} x
20044 * @param {*} y
20045 * @returns {*} Returns x when x is largest, or y when y is largest
20046 * @private
20047 */
20048 function _largest(x, y){
20049 return larger(x, y) ? x : y;
20050 }
20051
20052 /**
20053 * Recursively calculate the maximum value in an n-dimensional array
20054 * @param {Array} array
20055 * @return {number} max
20056 * @private
20057 */
20058 function _max(array) {
20059 var max = undefined;
20060
20061 deepForEach(array, function (value) {
20062 if (max === undefined || larger(value, max)) {
20063 max = value;
20064 }
20065 });
20066
20067 if (max === undefined) {
20068 throw new Error('Cannot calculate max of an empty array');
20069 }
20070
20071 return max;
20072 }
20073}
20074
20075exports.name = 'max';
20076exports.factory = factory;
20077
20078
20079/***/ }),
20080/* 115 */
20081/***/ (function(module, exports, __webpack_require__) {
20082
20083"use strict";
20084
20085
20086var size = __webpack_require__(2).size;
20087var deepForEach = __webpack_require__(43);
20088var reduce = __webpack_require__(65);
20089var containsCollections = __webpack_require__(66);
20090
20091function factory (type, config, load, typed) {
20092 var add = load(__webpack_require__(20));
20093 var divide = load(__webpack_require__(49));
20094
20095 /**
20096 * Compute the mean value of matrix or a list with values.
20097 * In case of a multi dimensional array, the mean of the flattened array
20098 * will be calculated. When `dim` is provided, the maximum over the selected
20099 * dimension will be calculated. Parameter `dim` is zero-based.
20100 *
20101 * Syntax:
20102 *
20103 * math.mean(a, b, c, ...)
20104 * math.mean(A)
20105 * math.mean(A, dim)
20106 *
20107 * Examples:
20108 *
20109 * math.mean(2, 1, 4, 3); // returns 2.5
20110 * math.mean([1, 2.7, 3.2, 4]); // returns 2.725
20111 *
20112 * math.mean([[2, 5], [6, 3], [1, 7]], 0); // returns [3, 5]
20113 * math.mean([[2, 5], [6, 3], [1, 7]], 1); // returns [3.5, 4.5, 4]
20114 *
20115 * See also:
20116 *
20117 * median, min, max, sum, prod, std, var
20118 *
20119 * @param {... *} args A single matrix or or multiple scalar values
20120 * @return {*} The mean of all values
20121 */
20122 var mean = typed('mean', {
20123 // mean([a, b, c, d, ...])
20124 'Array | Matrix': _mean,
20125
20126 // mean([a, b, c, d, ...], dim)
20127 'Array | Matrix, number | BigNumber': _nmean,
20128
20129 // mean(a, b, c, d, ...)
20130 '...': function (args) {
20131 if (containsCollections(args)) {
20132 throw new TypeError('Scalar values expected in function mean');
20133 }
20134
20135 return _mean(args);
20136 }
20137 });
20138
20139 mean.toTex = undefined; // use default template
20140
20141 return mean;
20142
20143 /**
20144 * Calculate the mean value in an n-dimensional array, returning a
20145 * n-1 dimensional array
20146 * @param {Array} array
20147 * @param {number} dim
20148 * @return {number} mean
20149 * @private
20150 */
20151 function _nmean(array, dim){
20152 var sum = reduce(array, dim, add);
20153 var s = Array.isArray(array) ? size(array) : array.size();
20154 return divide(sum, s[dim]);
20155 }
20156
20157 /**
20158 * Recursively calculate the mean value in an n-dimensional array
20159 * @param {Array} array
20160 * @return {number} mean
20161 * @private
20162 */
20163 function _mean(array) {
20164 var sum = 0;
20165 var num = 0;
20166
20167 deepForEach(array, function (value) {
20168 sum = add(sum, value);
20169 num++;
20170 });
20171
20172 if (num === 0) {
20173 throw new Error('Cannot calculate mean of an empty array');
20174 }
20175
20176 return divide(sum, num);
20177 }
20178}
20179
20180exports.name = 'mean';
20181exports.factory = factory;
20182
20183
20184/***/ }),
20185/* 116 */
20186/***/ (function(module, exports, __webpack_require__) {
20187
20188"use strict";
20189
20190
20191var util = __webpack_require__(25);
20192
20193function factory (type, config, load, typed) {
20194 var matrix = load(__webpack_require__(0));
20195 var divideScalar = load(__webpack_require__(14));
20196 var addScalar = load(__webpack_require__(16));
20197 var multiply = load(__webpack_require__(12));
20198 var unaryMinus = load(__webpack_require__(35));
20199 var det = load(__webpack_require__(117));
20200 var eye = load(__webpack_require__(62));
20201
20202 /**
20203 * Calculate the inverse of a square matrix.
20204 *
20205 * Syntax:
20206 *
20207 * math.inv(x)
20208 *
20209 * Examples:
20210 *
20211 * math.inv([[1, 2], [3, 4]]); // returns [[-2, 1], [1.5, -0.5]]
20212 * math.inv(4); // returns 0.25
20213 * 1 / 4; // returns 0.25
20214 *
20215 * See also:
20216 *
20217 * det, transpose
20218 *
20219 * @param {number | Complex | Array | Matrix} x Matrix to be inversed
20220 * @return {number | Complex | Array | Matrix} The inverse of `x`.
20221 */
20222 var inv = typed('inv', {
20223 'Array | Matrix': function (x) {
20224 var size = type.isMatrix(x) ? x.size() : util.array.size(x);
20225 switch (size.length) {
20226 case 1:
20227 // vector
20228 if (size[0] == 1) {
20229 if (type.isMatrix(x)) {
20230 return matrix([
20231 divideScalar(1, x.valueOf()[0])
20232 ]);
20233 }
20234 else {
20235 return [
20236 divideScalar(1, x[0])
20237 ];
20238 }
20239 }
20240 else {
20241 throw new RangeError('Matrix must be square ' +
20242 '(size: ' + util.string.format(size) + ')');
20243 }
20244
20245 case 2:
20246 // two dimensional array
20247 var rows = size[0];
20248 var cols = size[1];
20249 if (rows == cols) {
20250 if (type.isMatrix(x)) {
20251 return matrix(
20252 _inv(x.valueOf(), rows, cols),
20253 x.storage()
20254 );
20255 }
20256 else {
20257 // return an Array
20258 return _inv(x, rows, cols);
20259 }
20260 }
20261 else {
20262 throw new RangeError('Matrix must be square ' +
20263 '(size: ' + util.string.format(size) + ')');
20264 }
20265
20266 default:
20267 // multi dimensional array
20268 throw new RangeError('Matrix must be two dimensional ' +
20269 '(size: ' + util.string.format(size) + ')');
20270 }
20271 },
20272
20273 'any': function (x) {
20274 // scalar
20275 return divideScalar(1, x); // FIXME: create a BigNumber one when configured for bignumbers
20276 }
20277 });
20278
20279 /**
20280 * Calculate the inverse of a square matrix
20281 * @param {Array[]} mat A square matrix
20282 * @param {number} rows Number of rows
20283 * @param {number} cols Number of columns, must equal rows
20284 * @return {Array[]} inv Inverse matrix
20285 * @private
20286 */
20287 function _inv (mat, rows, cols){
20288 var r, s, f, value, temp;
20289
20290 if (rows == 1) {
20291 // this is a 1 x 1 matrix
20292 value = mat[0][0];
20293 if (value == 0) {
20294 throw Error('Cannot calculate inverse, determinant is zero');
20295 }
20296 return [[
20297 divideScalar(1, value)
20298 ]];
20299 }
20300 else if (rows == 2) {
20301 // this is a 2 x 2 matrix
20302 var d = det(mat);
20303 if (d == 0) {
20304 throw Error('Cannot calculate inverse, determinant is zero');
20305 }
20306 return [
20307 [
20308 divideScalar(mat[1][1], d),
20309 divideScalar(unaryMinus(mat[0][1]), d)
20310 ],
20311 [
20312 divideScalar(unaryMinus(mat[1][0]), d),
20313 divideScalar(mat[0][0], d)
20314 ]
20315 ];
20316 }
20317 else {
20318 // this is a matrix of 3 x 3 or larger
20319 // calculate inverse using gauss-jordan elimination
20320 // http://en.wikipedia.org/wiki/Gaussian_elimination
20321 // http://mathworld.wolfram.com/MatrixInverse.html
20322 // http://math.uww.edu/~mcfarlat/inverse.htm
20323
20324 // make a copy of the matrix (only the arrays, not of the elements)
20325 var A = mat.concat();
20326 for (r = 0; r < rows; r++) {
20327 A[r] = A[r].concat();
20328 }
20329
20330 // create an identity matrix which in the end will contain the
20331 // matrix inverse
20332 var B = eye(rows).valueOf();
20333
20334 // loop over all columns, and perform row reductions
20335 for (var c = 0; c < cols; c++) {
20336 // element Acc should be non zero. if not, swap content
20337 // with one of the lower rows
20338 r = c;
20339 while (r < rows && A[r][c] == 0) {
20340 r++;
20341 }
20342 if (r == rows || A[r][c] == 0) {
20343 // TODO: in case of zero det, just return a matrix wih Infinity values? (like octave)
20344 throw Error('Cannot calculate inverse, determinant is zero');
20345 }
20346 if (r != c) {
20347 temp = A[c]; A[c] = A[r]; A[r] = temp;
20348 temp = B[c]; B[c] = B[r]; B[r] = temp;
20349 }
20350
20351 // eliminate non-zero values on the other rows at column c
20352 var Ac = A[c],
20353 Bc = B[c];
20354 for (r = 0; r < rows; r++) {
20355 var Ar = A[r],
20356 Br = B[r];
20357 if(r != c) {
20358 // eliminate value at column c and row r
20359 if (Ar[c] != 0) {
20360 f = divideScalar(unaryMinus(Ar[c]), Ac[c]);
20361
20362 // add (f * row c) to row r to eliminate the value
20363 // at column c
20364 for (s = c; s < cols; s++) {
20365 Ar[s] = addScalar(Ar[s], multiply(f, Ac[s]));
20366 }
20367 for (s = 0; s < cols; s++) {
20368 Br[s] = addScalar(Br[s], multiply(f, Bc[s]));
20369 }
20370 }
20371 }
20372 else {
20373 // normalize value at Acc to 1,
20374 // divide each value on row r with the value at Acc
20375 f = Ac[c];
20376 for (s = c; s < cols; s++) {
20377 Ar[s] = divideScalar(Ar[s], f);
20378 }
20379 for (s = 0; s < cols; s++) {
20380 Br[s] = divideScalar(Br[s], f);
20381 }
20382 }
20383 }
20384 }
20385 return B;
20386 }
20387 }
20388
20389 inv.toTex = {1: '\\left(${args[0]}\\right)^{-1}'};
20390
20391 return inv;
20392}
20393
20394exports.name = 'inv';
20395exports.factory = factory;
20396
20397
20398/***/ }),
20399/* 117 */
20400/***/ (function(module, exports, __webpack_require__) {
20401
20402"use strict";
20403
20404
20405var util = __webpack_require__(25);
20406var object = util.object;
20407var string = util.string;
20408
20409function factory (type, config, load, typed) {
20410 var matrix = load(__webpack_require__(0));
20411 var add = load(__webpack_require__(20));
20412 var subtract = load(__webpack_require__(21));
20413 var multiply = load(__webpack_require__(12));
20414 var unaryMinus = load(__webpack_require__(35));
20415
20416 /**
20417 * Calculate the determinant of a matrix.
20418 *
20419 * Syntax:
20420 *
20421 * math.det(x)
20422 *
20423 * Examples:
20424 *
20425 * math.det([[1, 2], [3, 4]]); // returns -2
20426 *
20427 * var A = [
20428 * [-2, 2, 3],
20429 * [-1, 1, 3],
20430 * [2, 0, -1]
20431 * ]
20432 * math.det(A); // returns 6
20433 *
20434 * See also:
20435 *
20436 * inv
20437 *
20438 * @param {Array | Matrix} x A matrix
20439 * @return {number} The determinant of `x`
20440 */
20441 var det = typed('det', {
20442 'any': function (x) {
20443 return object.clone(x);
20444 },
20445
20446 'Array | Matrix': function det (x) {
20447 var size;
20448 if (type.isMatrix(x)) {
20449 size = x.size();
20450 }
20451 else if (Array.isArray(x)) {
20452 x = matrix(x);
20453 size = x.size();
20454 }
20455 else {
20456 // a scalar
20457 size = [];
20458 }
20459
20460 switch (size.length) {
20461 case 0:
20462 // scalar
20463 return object.clone(x);
20464
20465 case 1:
20466 // vector
20467 if (size[0] == 1) {
20468 return object.clone(x.valueOf()[0]);
20469 }
20470 else {
20471 throw new RangeError('Matrix must be square ' +
20472 '(size: ' + string.format(size) + ')');
20473 }
20474
20475 case 2:
20476 // two dimensional array
20477 var rows = size[0];
20478 var cols = size[1];
20479 if (rows == cols) {
20480 return _det(x.clone().valueOf(), rows, cols);
20481 }
20482 else {
20483 throw new RangeError('Matrix must be square ' +
20484 '(size: ' + string.format(size) + ')');
20485 }
20486
20487 default:
20488 // multi dimensional array
20489 throw new RangeError('Matrix must be two dimensional ' +
20490 '(size: ' + string.format(size) + ')');
20491 }
20492 }
20493 });
20494
20495 det.toTex = {1: '\\det\\left(${args[0]}\\right)'};
20496
20497 return det;
20498
20499 /**
20500 * Calculate the determinant of a matrix
20501 * @param {Array[]} matrix A square, two dimensional matrix
20502 * @param {number} rows Number of rows of the matrix (zero-based)
20503 * @param {number} cols Number of columns of the matrix (zero-based)
20504 * @returns {number} det
20505 * @private
20506 */
20507 function _det (matrix, rows, cols) {
20508 if (rows == 1) {
20509 // this is a 1 x 1 matrix
20510 return object.clone(matrix[0][0]);
20511 }
20512 else if (rows == 2) {
20513 // this is a 2 x 2 matrix
20514 // the determinant of [a11,a12;a21,a22] is det = a11*a22-a21*a12
20515 return subtract(
20516 multiply(matrix[0][0], matrix[1][1]),
20517 multiply(matrix[1][0], matrix[0][1])
20518 );
20519 }
20520 else {
20521 // this is an n x n matrix
20522 var compute_mu = function (matrix) {
20523 var i, j;
20524
20525 // Compute the matrix with zero lower triangle, same upper triangle,
20526 // and diagonals given by the negated sum of the below diagonal
20527 // elements.
20528 var mu = new Array(matrix.length);
20529 var sum = 0;
20530 for (i = 1; i < matrix.length; i++) {
20531 sum = add(sum, matrix[i][i]);
20532 }
20533
20534 for (i = 0; i < matrix.length; i++) {
20535 mu[i] = new Array(matrix.length);
20536 mu[i][i] = unaryMinus(sum);
20537
20538 for (j = 0; j < i; j++) {
20539 mu[i][j] = 0; // TODO: make bignumber 0 in case of bignumber computation
20540 }
20541
20542 for (j = i + 1; j < matrix.length; j++) {
20543 mu[i][j] = matrix[i][j];
20544 }
20545
20546 if (i+1 < matrix.length) {
20547 sum = subtract(sum, matrix[i + 1][i + 1]);
20548 }
20549 }
20550
20551 return mu;
20552 };
20553
20554 var fa = matrix;
20555 for (var i = 0; i < rows - 1; i++) {
20556 fa = multiply(compute_mu(fa), matrix);
20557 }
20558
20559 if (rows % 2 == 0) {
20560 return unaryMinus(fa[0][0]);
20561 } else {
20562 return fa[0][0];
20563 }
20564 }
20565 }
20566}
20567
20568exports.name = 'det';
20569exports.factory = factory;
20570
20571
20572
20573/***/ }),
20574/* 118 */
20575/***/ (function(module, exports, __webpack_require__) {
20576
20577"use strict";
20578
20579
20580var deepForEach = __webpack_require__(43);
20581var reduce = __webpack_require__(65);
20582var containsCollections = __webpack_require__(66);
20583
20584function factory (type, config, load, typed) {
20585 var smaller = load(__webpack_require__(39));
20586
20587 /**
20588 * Compute the maximum value of a matrix or a list of values.
20589 * In case of a multi dimensional array, the maximum of the flattened array
20590 * will be calculated. When `dim` is provided, the maximum over the selected
20591 * dimension will be calculated. Parameter `dim` is zero-based.
20592 *
20593 * Syntax:
20594 *
20595 * math.min(a, b, c, ...)
20596 * math.min(A)
20597 * math.min(A, dim)
20598 *
20599 * Examples:
20600 *
20601 * math.min(2, 1, 4, 3); // returns 1
20602 * math.min([2, 1, 4, 3]); // returns 1
20603 *
20604 * // maximum over a specified dimension (zero-based)
20605 * math.min([[2, 5], [4, 3], [1, 7]], 0); // returns [1, 3]
20606 * math.min([[2, 5], [4, 3], [1, 7]], 1); // returns [2, 3, 1]
20607 *
20608 * math.max(2.7, 7.1, -4.5, 2.0, 4.1); // returns 7.1
20609 * math.min(2.7, 7.1, -4.5, 2.0, 4.1); // returns -4.5
20610 *
20611 * See also:
20612 *
20613 * mean, median, max, prod, std, sum, var
20614 *
20615 * @param {... *} args A single matrix or or multiple scalar values
20616 * @return {*} The minimum value
20617 */
20618 var min = typed('min', {
20619 // min([a, b, c, d, ...])
20620 'Array | Matrix': _min,
20621
20622 // min([a, b, c, d, ...], dim)
20623 'Array | Matrix, number | BigNumber': function (array, dim) {
20624 return reduce(array, dim.valueOf(), _smallest);
20625 },
20626
20627 // min(a, b, c, d, ...)
20628 '...': function (args) {
20629 if (containsCollections(args)) {
20630 throw new TypeError('Scalar values expected in function min');
20631 }
20632
20633 return _min(args);
20634 }
20635 });
20636
20637 min.toTex = '\\min\\left(${args}\\right)';
20638
20639 return min;
20640
20641 /**
20642 * Return the smallest of two values
20643 * @param {*} x
20644 * @param {*} y
20645 * @returns {*} Returns x when x is smallest, or y when y is smallest
20646 * @private
20647 */
20648 function _smallest(x, y) {
20649 return smaller(x, y) ? x : y;
20650 }
20651
20652 /**
20653 * Recursively calculate the minimum value in an n-dimensional array
20654 * @param {Array} array
20655 * @return {number} min
20656 * @private
20657 */
20658 function _min(array) {
20659 var min = undefined;
20660
20661 deepForEach(array, function (value) {
20662 if (min === undefined || smaller(value, min)) {
20663 min = value;
20664 }
20665 });
20666
20667 if (min === undefined) {
20668 throw new Error('Cannot calculate min of an empty array');
20669 }
20670
20671 return min;
20672 }
20673}
20674
20675exports.name = 'min';
20676exports.factory = factory;
20677
20678
20679/***/ }),
20680/* 119 */
20681/***/ (function(module, exports, __webpack_require__) {
20682
20683"use strict";
20684
20685
20686function factory (type, config, load, typed) {
20687 var matrix = load(__webpack_require__(0));
20688
20689 var ZERO = new type.BigNumber(0);
20690 var ONE = new type.BigNumber(1);
20691
20692 /**
20693 * Create an array from a range.
20694 * By default, the range end is excluded. This can be customized by providing
20695 * an extra parameter `includeEnd`.
20696 *
20697 * Syntax:
20698 *
20699 * math.range(str [, includeEnd]) // Create a range from a string,
20700 * // where the string contains the
20701 * // start, optional step, and end,
20702 * // separated by a colon.
20703 * math.range(start, end [, includeEnd]) // Create a range with start and
20704 * // end and a step size of 1.
20705 * math.range(start, end, step [, includeEnd]) // Create a range with start, step,
20706 * // and end.
20707 *
20708 * Where:
20709 *
20710 * - `str: string`
20711 * A string 'start:end' or 'start:step:end'
20712 * - `start: {number | BigNumber}`
20713 * Start of the range
20714 * - `end: number | BigNumber`
20715 * End of the range, excluded by default, included when parameter includeEnd=true
20716 * - `step: number | BigNumber`
20717 * Step size. Default value is 1.
20718 * - `includeEnd: boolean`
20719 * Option to specify whether to include the end or not. False by default.
20720 *
20721 * Examples:
20722 *
20723 * math.range(2, 6); // [2, 3, 4, 5]
20724 * math.range(2, -3, -1); // [2, 1, 0, -1, -2]
20725 * math.range('2:1:6'); // [2, 3, 4, 5]
20726 * math.range(2, 6, true); // [2, 3, 4, 5, 6]
20727 *
20728 * See also:
20729 *
20730 * ones, zeros, size, subset
20731 *
20732 * @param {*} args Parameters describing the ranges `start`, `end`, and optional `step`.
20733 * @return {Array | Matrix} range
20734 */
20735 var range = typed('range', {
20736 // TODO: simplify signatures when typed-function supports default values and optional arguments
20737
20738 // TODO: a number or boolean should not be converted to string here
20739 'string': _strRange,
20740 'string, boolean': _strRange,
20741
20742 'number, number': function (start, end) {
20743 return _out(_rangeEx(start, end, 1));
20744 },
20745 'number, number, number': function (start, end, step) {
20746 return _out(_rangeEx(start, end, step));
20747 },
20748 'number, number, boolean': function (start, end, includeEnd) {
20749 return includeEnd
20750 ? _out(_rangeInc(start, end, 1))
20751 : _out(_rangeEx(start, end, 1));
20752 },
20753 'number, number, number, boolean': function (start, end, step, includeEnd) {
20754 return includeEnd
20755 ? _out(_rangeInc(start, end, step))
20756 : _out(_rangeEx(start, end, step));
20757 },
20758
20759 'BigNumber, BigNumber': function (start, end) {
20760 return _out(_bigRangeEx(start, end, ONE));
20761 },
20762 'BigNumber, BigNumber, BigNumber': function (start, end, step) {
20763 return _out(_bigRangeEx(start, end, step));
20764 },
20765 'BigNumber, BigNumber, boolean': function (start, end, includeEnd) {
20766 return includeEnd
20767 ? _out(_bigRangeInc(start, end, ONE))
20768 : _out(_bigRangeEx(start, end, ONE));
20769 },
20770 'BigNumber, BigNumber, BigNumber, boolean': function (start, end, step, includeEnd) {
20771 return includeEnd
20772 ? _out(_bigRangeInc(start, end, step))
20773 : _out(_bigRangeEx(start, end, step));
20774 }
20775
20776 });
20777
20778 range.toTex = undefined; // use default template
20779
20780 return range;
20781
20782 function _out(arr) {
20783 return config.matrix === 'Array' ? arr : matrix(arr);
20784 }
20785
20786 function _strRange (str, includeEnd) {
20787 var r = _parse(str);
20788 if (!r){
20789 throw new SyntaxError('String "' + str + '" is no valid range');
20790 }
20791
20792 var fn;
20793 if (config.number === 'BigNumber') {
20794 fn = includeEnd ? _bigRangeInc : _bigRangeEx;
20795 return _out(fn(
20796 new type.BigNumber(r.start),
20797 new type.BigNumber(r.end),
20798 new type.BigNumber(r.step)));
20799 }
20800 else {
20801 fn = includeEnd ? _rangeInc : _rangeEx;
20802 return _out(fn(r.start, r.end, r.step));
20803 }
20804 }
20805
20806 /**
20807 * Create a range with numbers. End is excluded
20808 * @param {number} start
20809 * @param {number} end
20810 * @param {number} step
20811 * @returns {Array} range
20812 * @private
20813 */
20814 function _rangeEx (start, end, step) {
20815 var array = [],
20816 x = start;
20817 if (step > 0) {
20818 while (x < end) {
20819 array.push(x);
20820 x += step;
20821 }
20822 }
20823 else if (step < 0) {
20824 while (x > end) {
20825 array.push(x);
20826 x += step;
20827 }
20828 }
20829
20830 return array;
20831 }
20832
20833 /**
20834 * Create a range with numbers. End is included
20835 * @param {number} start
20836 * @param {number} end
20837 * @param {number} step
20838 * @returns {Array} range
20839 * @private
20840 */
20841 function _rangeInc (start, end, step) {
20842 var array = [],
20843 x = start;
20844 if (step > 0) {
20845 while (x <= end) {
20846 array.push(x);
20847 x += step;
20848 }
20849 }
20850 else if (step < 0) {
20851 while (x >= end) {
20852 array.push(x);
20853 x += step;
20854 }
20855 }
20856
20857 return array;
20858 }
20859
20860 /**
20861 * Create a range with big numbers. End is excluded
20862 * @param {BigNumber} start
20863 * @param {BigNumber} end
20864 * @param {BigNumber} step
20865 * @returns {Array} range
20866 * @private
20867 */
20868 function _bigRangeEx (start, end, step) {
20869 var array = [],
20870 x = start;
20871 if (step.gt(ZERO)) {
20872 while (x.lt(end)) {
20873 array.push(x);
20874 x = x.plus(step);
20875 }
20876 }
20877 else if (step.lt(ZERO)) {
20878 while (x.gt(end)) {
20879 array.push(x);
20880 x = x.plus(step);
20881 }
20882 }
20883
20884 return array;
20885 }
20886
20887 /**
20888 * Create a range with big numbers. End is included
20889 * @param {BigNumber} start
20890 * @param {BigNumber} end
20891 * @param {BigNumber} step
20892 * @returns {Array} range
20893 * @private
20894 */
20895 function _bigRangeInc (start, end, step) {
20896 var array = [],
20897 x = start;
20898 if (step.gt(ZERO)) {
20899 while (x.lte(end)) {
20900 array.push(x);
20901 x = x.plus(step);
20902 }
20903 }
20904 else if (step.lt(ZERO)) {
20905 while (x.gte(end)) {
20906 array.push(x);
20907 x = x.plus(step);
20908 }
20909 }
20910
20911 return array;
20912 }
20913
20914 /**
20915 * Parse a string into a range,
20916 * The string contains the start, optional step, and end, separated by a colon.
20917 * If the string does not contain a valid range, null is returned.
20918 * For example str='0:2:11'.
20919 * @param {string} str
20920 * @return {{start: number, end: number, step: number} | null} range Object containing properties start, end, step
20921 * @private
20922 */
20923 function _parse (str) {
20924 var args = str.split(':');
20925
20926 // number
20927 var nums = args.map(function (arg) {
20928 // use Number and not parseFloat as Number returns NaN on invalid garbage in the string
20929 return Number(arg);
20930 });
20931
20932 var invalid = nums.some(function (num) {
20933 return isNaN(num);
20934 });
20935 if(invalid) {
20936 return null;
20937 }
20938
20939 switch (nums.length) {
20940 case 2:
20941 return {
20942 start: nums[0],
20943 end: nums[1],
20944 step: 1
20945 };
20946
20947 case 3:
20948 return {
20949 start: nums[0],
20950 end: nums[2],
20951 step: nums[1]
20952 };
20953
20954 default:
20955 return null;
20956 }
20957 }
20958
20959}
20960
20961exports.name = 'range';
20962exports.factory = factory;
20963
20964
20965/***/ }),
20966/* 120 */
20967/***/ (function(module, exports, __webpack_require__) {
20968
20969"use strict";
20970
20971
20972var digits = __webpack_require__(3).digits;
20973// TODO this could be improved by simplifying seperated constants under associative and commutative operators
20974function factory(type, config, load, typed, math) {
20975 var util = load(__webpack_require__(121));
20976 var isCommutative = util.isCommutative;
20977 var isAssociative = util.isAssociative;
20978 var allChildren = util.allChildren;
20979 var createMakeNodeFunction = util.createMakeNodeFunction;
20980 var ConstantNode = math.expression.node.ConstantNode;
20981 var OperatorNode = math.expression.node.OperatorNode;
20982 var FunctionNode = math.expression.node.FunctionNode;
20983
20984 function simplifyConstant(expr) {
20985 var res = foldFraction(expr);
20986 return type.isNode(res) ? res : _toNode(res);
20987 }
20988
20989 function _eval(fnname, args) {
20990 try {
20991 return _toNumber(math[fnname].apply(null, args));
20992 }
20993 catch (ignore) {
20994 // sometimes the implicit type conversion causes the evaluation to fail, so we'll try again after removing Fractions
20995 args = args.map(function(x){
20996 if (type.isFraction(x)) {
20997 return x.valueOf();
20998 }
20999 return x;
21000 });
21001 return _toNumber(math[fnname].apply(null, args));
21002 }
21003 }
21004
21005 var _toNode = typed({
21006 'Fraction': _fractionToNode,
21007 'number': function(n) {
21008 if (n < 0) {
21009 return unaryMinusNode(new ConstantNode(-n));
21010 }
21011 return new ConstantNode(n);
21012 },
21013 'BigNumber': function(n) {
21014 if (n < 0) {
21015 return unaryMinusNode(new ConstantNode(n.negated().toString(), 'number'));
21016 }
21017 return new ConstantNode(n.toString(), 'number');
21018 },
21019 'Complex': function(s) {
21020 throw 'Cannot convert Complex number to Node';
21021 }
21022 });
21023
21024 // convert a number to a fraction only if it can be expressed exactly
21025 function _exactFraction(n) {
21026 if (isFinite(n)) {
21027 var f = math.fraction(n);
21028 if (f.valueOf() === n) {
21029 return f;
21030 }
21031 }
21032 return n;
21033 }
21034
21035 // Convert numbers to a preferred number type in preference order: Fraction, number, Complex
21036 // BigNumbers are left alone
21037 var _toNumber = typed({
21038 'string': function(s) {
21039 if (config.number === 'BigNumber') {
21040 return math.bignumber(s);
21041 }
21042 else if (config.number === 'Fraction') {
21043 return math.fraction(s);
21044 }
21045 else {
21046 return _exactFraction(parseFloat(s));
21047 }
21048 },
21049
21050 'Fraction': function(s) { return s; },
21051
21052 'BigNumber': function(s) { return s; },
21053
21054 'number': function(s) {
21055 return _exactFraction(s);
21056 },
21057
21058 'Complex': function(s) {
21059 if (s.im !== 0) {
21060 return s;
21061 }
21062 return _exactFraction(s.re);
21063 },
21064 });
21065
21066 function unaryMinusNode(n) {
21067 return new OperatorNode('-', 'unaryMinus', [n]);
21068 }
21069
21070 function _fractionToNode(f) {
21071 var n;
21072 var vn = f.s*f.n;
21073 if (vn < 0) {
21074 n = new OperatorNode('-', 'unaryMinus', [new ConstantNode(-vn)])
21075 }
21076 else {
21077 n = new ConstantNode(vn);
21078 }
21079
21080 if (f.d === 1) {
21081 return n;
21082 }
21083 return new OperatorNode('/', 'divide', [n, new ConstantNode(f.d)]);
21084 }
21085
21086 /*
21087 * Create a binary tree from a list of Fractions and Nodes.
21088 * Tries to fold Fractions by evaluating them until the first Node in the list is hit, so
21089 * `args` should be sorted to have the Fractions at the start (if the operator is commutative).
21090 * @param args - list of Fractions and Nodes
21091 * @param fn - evaluator for the binary operation evaluator that accepts two Fractions
21092 * @param makeNode - creates a binary OperatorNode/FunctionNode from a list of child Nodes
21093 * if args.length is 1, returns args[0]
21094 * @return - Either a Node representing a binary expression or Fraction
21095 */
21096 function foldOp(fn, args, makeNode) {
21097 return args.reduce(function(a, b) {
21098 if (!type.isNode(a) && !type.isNode(b)) {
21099 try {
21100 return _eval(fn, [a,b]);
21101 }
21102 catch (ignoreandcontinue) {}
21103 a = _toNode(a);
21104 b = _toNode(b);
21105 }
21106 else if (!type.isNode(a)) {
21107 a = _toNode(a);
21108 }
21109 else if (!type.isNode(b)) {
21110 b = _toNode(b);
21111 }
21112
21113 return makeNode([a, b]);
21114 });
21115 }
21116
21117 // destroys the original node and returns a folded one
21118 function foldFraction(node) {
21119 switch(node.type) {
21120 case 'SymbolNode':
21121 return node;
21122 case 'ConstantNode':
21123 if (node.valueType === 'number') {
21124 return _toNumber(node.value);
21125 }
21126 return node;
21127 case 'FunctionNode':
21128 if (math[node.name] && math[node.name].rawArgs) {
21129 return node;
21130 }
21131
21132 // Process operators as OperatorNode
21133 var operatorFunctions = [ 'add', 'multiply' ];
21134 if (operatorFunctions.indexOf(node.name) === -1) {
21135 var args = node.args.map(foldFraction);
21136
21137 // If all args are numbers
21138 if (!args.some(type.isNode)) {
21139 try {
21140 return _eval(node.name, args);
21141 }
21142 catch (ignoreandcontine) {}
21143 }
21144
21145 // Convert all args to nodes and construct a symbolic function call
21146 args = args.map(function(arg) {
21147 return type.isNode(arg) ? arg : _toNode(arg);
21148 });
21149 return new FunctionNode(node.name, args);
21150 }
21151 else {
21152 // treat as operator
21153 }
21154 /* falls through */
21155 case 'OperatorNode':
21156 var fn = node.fn.toString();
21157 var args;
21158 var res;
21159 var makeNode = createMakeNodeFunction(node);
21160 if (node.args.length === 1) {
21161 args = [foldFraction(node.args[0])];
21162 if (!type.isNode(args[0])) {
21163 res = _eval(fn, args);
21164 }
21165 else {
21166 res = makeNode(args);
21167 }
21168 }
21169 else if (isAssociative(node)) {
21170 args = allChildren(node);
21171 args = args.map(foldFraction);
21172
21173 if (isCommutative(fn)) {
21174 // commutative binary operator
21175 var consts = [], vars = [];
21176
21177 for (var i=0; i < args.length; i++) {
21178 if (!type.isNode(args[i])) {
21179 consts.push(args[i]);
21180 }
21181 else {
21182 vars.push(args[i]);
21183 }
21184 }
21185
21186 if (consts.length > 1) {
21187 res = foldOp(fn, consts, makeNode);
21188 vars.unshift(res);
21189 res = foldOp(fn, vars, makeNode);
21190 }
21191 else {
21192 // we won't change the children order since it's not neccessary
21193 res = foldOp(fn, args, makeNode);
21194 }
21195 }
21196 else {
21197 // non-commutative binary operator
21198 res = foldOp(fn, args, makeNode);
21199 }
21200 }
21201 else {
21202 // non-associative binary operator
21203 args = node.args.map(foldFraction);
21204 res = foldOp(fn, args, makeNode);
21205 }
21206 return res;
21207 case 'ParenthesisNode':
21208 // remove the uneccessary parenthesis
21209 return foldFraction(node.content);
21210 case 'AccessorNode':
21211 /* falls through */
21212 case 'ArrayNode':
21213 /* falls through */
21214 case 'AssignmentNode':
21215 /* falls through */
21216 case 'BlockNode':
21217 /* falls through */
21218 case 'FunctionAssignmentNode':
21219 /* falls through */
21220 case 'IndexNode':
21221 /* falls through */
21222 case 'ObjectNode':
21223 /* falls through */
21224 case 'RangeNode':
21225 /* falls through */
21226 case 'UpdateNode':
21227 /* falls through */
21228 case 'ConditionalNode':
21229 /* falls through */
21230 default:
21231 throw 'Unimplemented node type in simplifyConstant: '+node.type;
21232 }
21233 }
21234
21235 return simplifyConstant;
21236}
21237
21238exports.math = true;
21239exports.name = 'simplifyConstant';
21240exports.path = 'algebra.simplify';
21241exports.factory = factory;
21242
21243
21244/***/ }),
21245/* 121 */
21246/***/ (function(module, exports, __webpack_require__) {
21247
21248"use strict";
21249
21250
21251function factory(type, config, load, typed, math) {
21252 var FunctionNode = math.expression.node.FunctionNode;
21253 var OperatorNode = math.expression.node.OperatorNode;
21254 var SymbolNode = math.expression.node.SymbolNode;
21255
21256 // TODO commutative/associative properties rely on the arguments
21257 // e.g. multiply is not commutative for matrices
21258 // The properties should be calculated from an argument to simplify, or possibly something in math.config
21259 // the other option is for typed() to specify a return type so that we can evaluate the type of arguments
21260 var commutative = {
21261 'add': true,
21262 'multiply': true
21263 }
21264 var associative = {
21265 'add': true,
21266 'multiply': true
21267 }
21268
21269
21270 function isCommutative(node, context) {
21271 if (!type.isOperatorNode(node)) {
21272 return true;
21273 }
21274 var name = node.fn.toString();
21275 if (context && context.hasOwnProperty(name) && context[name].hasOwnProperty('commutative')) {
21276 return context[name].commutative;
21277 }
21278 return commutative[name] || false;
21279 }
21280
21281 function isAssociative(node, context) {
21282 if (!type.isOperatorNode(node)) {
21283 return false;
21284 }
21285 var name = node.fn.toString();
21286 if (context && context.hasOwnProperty(name) && context[name].hasOwnProperty('associative')) {
21287 return context[name].associative;
21288 }
21289 return associative[name] || false;
21290 }
21291
21292 /**
21293 * Flatten all associative operators in an expression tree.
21294 * Assumes parentheses have already been removed.
21295 */
21296 function flatten(node) {
21297 if (!node.args || node.args.length === 0) {
21298 return node;
21299 }
21300 node.args = allChildren(node);
21301 for (var i=0; i<node.args.length; i++) {
21302 flatten(node.args[i]);
21303 }
21304 }
21305
21306 /**
21307 * Get the children of a node as if it has been flattened.
21308 * TODO implement for FunctionNodes
21309 */
21310 function allChildren(node) {
21311 var op;
21312 var children = [];
21313 var findChildren = function(node) {
21314 for (var i = 0; i < node.args.length; i++) {
21315 var child = node.args[i];
21316 if (type.isOperatorNode(child) && op === child.op) {
21317 findChildren(child);
21318 }
21319 else {
21320 children.push(child);
21321 }
21322 }
21323 };
21324
21325 if (isAssociative(node)) {
21326 op = node.op;
21327 findChildren(node);
21328 return children;
21329 }
21330 else {
21331 return node.args;
21332 }
21333 }
21334
21335 /**
21336 * Unflatten all flattened operators to a right-heavy binary tree.
21337 */
21338 function unflattenr(node) {
21339 if (!node.args || node.args.length === 0) {
21340 return;
21341 }
21342 var makeNode = createMakeNodeFunction(node);
21343 var l = node.args.length;
21344 for (var i = 0; i < l; i++) {
21345 unflattenr(node.args[i])
21346 }
21347 if (l > 2 && isAssociative(node)) {
21348 var curnode = node.args.pop();
21349 while (node.args.length > 0) {
21350 curnode = makeNode([node.args.pop(), curnode]);
21351 }
21352 node.args = curnode.args;
21353 }
21354 }
21355
21356 /**
21357 * Unflatten all flattened operators to a left-heavy binary tree.
21358 */
21359 function unflattenl(node) {
21360 if (!node.args || node.args.length === 0) {
21361 return;
21362 }
21363 var makeNode = createMakeNodeFunction(node);
21364 var l = node.args.length;
21365 for (var i = 0; i < l; i++) {
21366 unflattenl(node.args[i])
21367 }
21368 if (l > 2 && isAssociative(node)) {
21369 var curnode = node.args.shift();
21370 while (node.args.length > 0) {
21371 curnode = makeNode([curnode, node.args.shift()]);
21372 }
21373 node.args = curnode.args;
21374 }
21375 }
21376
21377 function createMakeNodeFunction(node) {
21378 if (type.isOperatorNode(node)) {
21379 return function(args){
21380 try{
21381 return new OperatorNode(node.op, node.fn, args);
21382 } catch(err){
21383 console.error(err);
21384 return [];
21385 }
21386 };
21387 }
21388 else {
21389 return function(args){
21390 return new FunctionNode(new SymbolNode(node.name), args);
21391 };
21392 }
21393 }
21394 return {
21395 createMakeNodeFunction: createMakeNodeFunction,
21396 isCommutative: isCommutative,
21397 isAssociative: isAssociative,
21398 flatten: flatten,
21399 allChildren: allChildren,
21400 unflattenr: unflattenr,
21401 unflattenl: unflattenl
21402 };
21403}
21404
21405exports.factory = factory;
21406exports.math = true;
21407
21408/***/ }),
21409/* 122 */
21410/***/ (function(module, exports, __webpack_require__) {
21411
21412"use strict";
21413
21414
21415function factory(type, config, load, typed, math) {
21416 var ConstantNode = math.expression.node.ConstantNode;
21417 var OperatorNode = math.expression.node.OperatorNode;
21418 var FunctionNode = math.expression.node.FunctionNode;
21419 var ParenthesisNode = math.expression.node.ParenthesisNode;
21420
21421 var node0 = new ConstantNode(0);
21422 var node1 = new ConstantNode(1);
21423
21424 /**
21425 * simplifyCore() performs single pass simplification suitable for
21426 * applications requiring ultimate performance. In contrast, simplify()
21427 * extends simplifyCore() with additional passes to provide deeper
21428 * simplification.
21429 *
21430 * Syntax:
21431 *
21432 * simplify.simplifyCore(expr)
21433 *
21434 * Examples:
21435 *
21436 * var f = math.parse('2 * 1 * x ^ (2 - 1)');
21437 * math.simplify.simpifyCore(f); // Node {2 * x}
21438 * math.simplify('2 * 1 * x ^ (2 - 1)', [math.simplify.simpifyCore]); // Node {2 * x};
21439 *
21440 * See also:
21441 *
21442 * derivative
21443 *
21444 * @param {Node} node
21445 * The expression to be simplified
21446 */
21447 function simplifyCore(node) {
21448 if (type.isOperatorNode(node) && node.args.length <= 2) {
21449 var a0 = simplifyCore(node.args[0]);
21450 var a1 = node.args[1] && simplifyCore(node.args[1]);
21451 if (node.op === "+") {
21452 if (node.args.length === 1) {
21453 return node.args[0];
21454 }
21455 if (type.isConstantNode(a0)) {
21456 if (a0.value === "0") {
21457 return a1;
21458 } else if (type.isConstantNode(a1) && a0.value && a0.value.length < 5 && a1.value && a1.value.length < 5) {
21459 return new ConstantNode(Number(a0.value) + Number(a1.value));
21460 }
21461 }
21462 if (type.isConstantNode(a1) && a1.value === "0") {
21463 return a0;
21464 }
21465 if (node.args.length === 2 && type.isOperatorNode(a1) && a1.op === '-' && a1.fn === 'unaryMinus') {
21466 return new OperatorNode('-', 'subtract', [a0,a1.args[0]]);
21467 }
21468 return new OperatorNode(node.op, node.fn, a1 ? [a0,a1] : [a0]);
21469 } else if (node.op === "-") {
21470 if (type.isConstantNode(a0) && a1) {
21471 if (type.isConstantNode(a1) && a0.value && a0.value.length < 5 && a1.value && a1.value.length < 5) {
21472 return new ConstantNode(Number(a0.value) - Number(a1.value));
21473 } else if (a0.value === "0") {
21474 return new OperatorNode("-", "unaryMinus", [a1]);
21475 }
21476 }
21477 if (node.fn === "subtract" && node.args.length === 2) {
21478 if (type.isConstantNode(a1) && a1.value === "0") {
21479 return a0;
21480 }
21481 if (type.isOperatorNode(a1) && a1.fn === "unaryMinus") {
21482 return simplifyCore(new OperatorNode("+", "add", [a0, a1.args[0]]));
21483 }
21484 return new OperatorNode(node.op, node.fn, [a0,a1]);
21485 } else if (node.fn === "unaryMinus") {
21486 if (type.isOperatorNode(a0)) {
21487 if (a0.fn === 'unaryMinus') {
21488 return a0.args[0];
21489 } else if (a0.fn === 'subtract') {
21490 return new OperatorNode('-', 'subtract', [a0.args[1], a0.args[0]]);
21491 }
21492 }
21493 return new OperatorNode(node.op, node.fn, [a0]);
21494 }
21495 throw new Error('never happens');
21496 } else if (node.op === "*") {
21497 if (type.isConstantNode(a0)) {
21498 if (a0.value === "0") {
21499 return node0;
21500 } else if (a0.value === "1") {
21501 return a1;
21502 } else if (type.isConstantNode(a1) && a0.value && a0.value.length < 5 && a1.value && a1.value.length < 5) {
21503 return new ConstantNode(Number(a0.value) * Number(a1.value));
21504 }
21505 }
21506 if (type.isConstantNode(a1)) {
21507 if (a1.value === "0") {
21508 return node0;
21509 } else if (a1.value === "1") {
21510 return a0;
21511 } else if (type.isOperatorNode(a0) && a0.op === node.op) {
21512 var a00 = a0.args[0];
21513 if (type.isConstantNode(a00) && a1.value && a1.value.length < 5 && a00.value && a00.value.length < 5) {
21514 var a00_a1 = new ConstantNode(Number(a0.args[0].value) * Number(a1.value));
21515 return new OperatorNode(node.op, node.fn, [a00_a1, a0.args[1]]); // constants on left
21516 }
21517 }
21518 return new OperatorNode(node.op, node.fn, [a1, a0]); // constants on left
21519 }
21520 return new OperatorNode(node.op, node.fn, [a0, a1]);
21521 } else if (node.op === "/") {
21522 if (type.isConstantNode(a0)) {
21523 if (a0.value === "0") {
21524 return node0;
21525 } else if (type.isConstantNode(a1) && a0.value && a0.value.length < 5 && (a1.value === "1" || a1.value==="2" || a1.value==="4")) {
21526 return new ConstantNode(Number(a0.value) / Number(a1.value));
21527 }
21528 }
21529 return new OperatorNode(node.op, node.fn, [a0, a1]);
21530 } else if (node.op === "^") {
21531 if (type.isConstantNode(a1)) {
21532 if (a1.value === "0") {
21533 return node1;
21534 } else if (a1.value === "1") {
21535 return a0;
21536 } else {
21537 if (type.isConstantNode(a0) &&
21538 a0.value && a0.value.length < 5 &&
21539 a1.value && a1.value.length < 2) {
21540 // fold constant
21541 return new ConstantNode(
21542 math.pow(Number(a0.value), Number(a1.value)));
21543 } else if (type.isOperatorNode(a0) && a0.op === "^") {
21544 var a01 = a0.args[1];
21545 if (type.isConstantNode(a01)) {
21546 return new OperatorNode(node.op, node.fn, [
21547 a0.args[0],
21548 new ConstantNode(a01.value * a1.value)
21549 ]);
21550 }
21551 }
21552 }
21553 }
21554 return new OperatorNode(node.op, node.fn, [a0, a1]);
21555 }
21556 } else if (type.isParenthesisNode(node)) {
21557 var c = simplifyCore(node.content);
21558 if (type.isParenthesisNode(c) || type.isSymbolNode(c) || type.isConstantNode(c)) {
21559 return c;
21560 }
21561 return new ParenthesisNode(c);
21562 } else if (type.isFunctionNode(node)) {
21563 var args = node.args.map(simplifyCore);
21564 if (args.length === 1) {
21565 if (type.isParenthesisNode(args[0])) {
21566 args[0] = args[0].content;
21567 }
21568 }
21569 return new FunctionNode(simplifyCore(node.fn), args);
21570 } else {
21571 // cannot simplify
21572 }
21573 return node;
21574 }
21575
21576 return simplifyCore;
21577}
21578
21579exports.math = true;
21580exports.name = 'simplifyCore';
21581exports.path = 'algebra.simplify';
21582exports.factory = factory;
21583
21584
21585/***/ }),
21586/* 123 */
21587/***/ (function(module, exports, __webpack_require__) {
21588
21589"use strict";
21590
21591
21592var object= __webpack_require__(5);
21593
21594function factory (type, config, load, typed) {
21595 /**
21596 * Clone an object.
21597 *
21598 * Syntax:
21599 *
21600 * math.clone(x)
21601 *
21602 * Examples:
21603 *
21604 * math.clone(3.5); // returns number 3.5
21605 * math.clone(math.complex('2-4i'); // returns Complex 2 - 4i
21606 * math.clone(math.unit(45, 'deg')); // returns Unit 45 deg
21607 * math.clone([[1, 2], [3, 4]]); // returns Array [[1, 2], [3, 4]]
21608 * math.clone("hello world"); // returns string "hello world"
21609 *
21610 * @param {*} x Object to be cloned
21611 * @return {*} A clone of object x
21612 */
21613 var clone = typed('clone', {
21614 'any': object.clone
21615 });
21616
21617 clone.toTex = undefined; // use default template
21618
21619 return clone;
21620}
21621
21622exports.name = 'clone';
21623exports.factory = factory;
21624
21625
21626/***/ }),
21627/* 124 */
21628/***/ (function(module, exports, __webpack_require__) {
21629
21630"use strict";
21631
21632
21633var nearlyEqual = __webpack_require__(3).nearlyEqual;
21634var bigNearlyEqual = __webpack_require__(37);
21635
21636function factory (type, config, load, typed) {
21637
21638 var matrix = load(__webpack_require__(0));
21639
21640 var algorithm03 = load(__webpack_require__(17));
21641 var algorithm07 = load(__webpack_require__(26));
21642 var algorithm12 = load(__webpack_require__(18));
21643 var algorithm13 = load(__webpack_require__(8));
21644 var algorithm14 = load(__webpack_require__(6));
21645
21646 var latex = __webpack_require__(4);
21647
21648 /**
21649 * Test whether two values are unequal.
21650 *
21651 * The function tests whether the relative difference between x and y is
21652 * larger than the configured epsilon. The function cannot be used to compare
21653 * values smaller than approximately 2.22e-16.
21654 *
21655 * For matrices, the function is evaluated element wise.
21656 * In case of complex numbers, x.re must unequal y.re, or x.im must unequal y.im.
21657 *
21658 * Values `null` and `undefined` are compared strictly, thus `null` is unequal
21659 * with everything except `null`, and `undefined` is unequal with everying
21660 * except. `undefined`.
21661 *
21662 * Syntax:
21663 *
21664 * math.unequal(x, y)
21665 *
21666 * Examples:
21667 *
21668 * math.unequal(2 + 2, 3); // returns true
21669 * math.unequal(2 + 2, 4); // returns false
21670 *
21671 * var a = math.unit('50 cm');
21672 * var b = math.unit('5 m');
21673 * math.unequal(a, b); // returns false
21674 *
21675 * var c = [2, 5, 1];
21676 * var d = [2, 7, 1];
21677 *
21678 * math.unequal(c, d); // returns [false, true, false]
21679 * math.deepEqual(c, d); // returns false
21680 *
21681 * math.unequal(0, null); // returns true
21682 * See also:
21683 *
21684 * equal, deepEqual, smaller, smallerEq, larger, largerEq, compare
21685 *
21686 * @param {number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined} x First value to compare
21687 * @param {number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined} y Second value to compare
21688 * @return {boolean | Array | Matrix} Returns true when the compared values are unequal, else returns false
21689 */
21690 var unequal = typed('unequal', {
21691
21692 'any, any': function (x, y) {
21693 // strict equality for null and undefined?
21694 if (x === null) { return y !== null; }
21695 if (y === null) { return x !== null; }
21696 if (x === undefined) { return y !== undefined; }
21697 if (y === undefined) { return x !== undefined; }
21698
21699 return _unequal(x, y);
21700 },
21701
21702 'Matrix, Matrix': function (x, y) {
21703 // result
21704 var c;
21705
21706 // process matrix storage
21707 switch (x.storage()) {
21708 case 'sparse':
21709 switch (y.storage()) {
21710 case 'sparse':
21711 // sparse + sparse
21712 c = algorithm07(x, y, _unequal);
21713 break;
21714 default:
21715 // sparse + dense
21716 c = algorithm03(y, x, _unequal, true);
21717 break;
21718 }
21719 break;
21720 default:
21721 switch (y.storage()) {
21722 case 'sparse':
21723 // dense + sparse
21724 c = algorithm03(x, y, _unequal, false);
21725 break;
21726 default:
21727 // dense + dense
21728 c = algorithm13(x, y, _unequal);
21729 break;
21730 }
21731 break;
21732 }
21733 return c;
21734 },
21735
21736 'Array, Array': function (x, y) {
21737 // use matrix implementation
21738 return unequal(matrix(x), matrix(y)).valueOf();
21739 },
21740
21741 'Array, Matrix': function (x, y) {
21742 // use matrix implementation
21743 return unequal(matrix(x), y);
21744 },
21745
21746 'Matrix, Array': function (x, y) {
21747 // use matrix implementation
21748 return unequal(x, matrix(y));
21749 },
21750
21751 'Matrix, any': function (x, y) {
21752 // result
21753 var c;
21754 // check storage format
21755 switch (x.storage()) {
21756 case 'sparse':
21757 c = algorithm12(x, y, _unequal, false);
21758 break;
21759 default:
21760 c = algorithm14(x, y, _unequal, false);
21761 break;
21762 }
21763 return c;
21764 },
21765
21766 'any, Matrix': function (x, y) {
21767 // result
21768 var c;
21769 // check storage format
21770 switch (y.storage()) {
21771 case 'sparse':
21772 c = algorithm12(y, x, _unequal, true);
21773 break;
21774 default:
21775 c = algorithm14(y, x, _unequal, true);
21776 break;
21777 }
21778 return c;
21779 },
21780
21781 'Array, any': function (x, y) {
21782 // use matrix implementation
21783 return algorithm14(matrix(x), y, _unequal, false).valueOf();
21784 },
21785
21786 'any, Array': function (x, y) {
21787 // use matrix implementation
21788 return algorithm14(matrix(y), x, _unequal, true).valueOf();
21789 }
21790 });
21791
21792 var _unequal = typed('_unequal', {
21793
21794 'boolean, boolean': function (x, y) {
21795 return x !== y;
21796 },
21797
21798 'number, number': function (x, y) {
21799 return !nearlyEqual(x, y, config.epsilon);
21800 },
21801
21802 'BigNumber, BigNumber': function (x, y) {
21803 return !bigNearlyEqual(x, y, config.epsilon);
21804 },
21805
21806 'Fraction, Fraction': function (x, y) {
21807 return !x.equals(y);
21808 },
21809
21810 'Complex, Complex': function (x, y) {
21811 return !x.equals(y);
21812 },
21813
21814 'Unit, Unit': function (x, y) {
21815 if (!x.equalBase(y)) {
21816 throw new Error('Cannot compare units with different base');
21817 }
21818 return unequal(x.value, y.value);
21819 },
21820
21821 'string, string': function (x, y) {
21822 return x !== y;
21823 }
21824 });
21825
21826 unequal.toTex = {
21827 2: '\\left(${args[0]}' + latex.operators['unequal'] + '${args[1]}\\right)'
21828 };
21829
21830 return unequal;
21831}
21832
21833exports.name = 'unequal';
21834exports.factory = factory;
21835
21836
21837/***/ }),
21838/* 125 */
21839/***/ (function(module, exports, __webpack_require__) {
21840
21841"use strict";
21842
21843
21844var number = __webpack_require__(3);
21845var deepMap = __webpack_require__(1);
21846
21847function factory (type, config, load, typed) {
21848 /**
21849 * Compute the sign of a value. The sign of a value x is:
21850 *
21851 * - 1 when x > 1
21852 * - -1 when x < 0
21853 * - 0 when x == 0
21854 *
21855 * For matrices, the function is evaluated element wise.
21856 *
21857 * Syntax:
21858 *
21859 * math.sign(x)
21860 *
21861 * Examples:
21862 *
21863 * math.sign(3.5); // returns 1
21864 * math.sign(-4.2); // returns -1
21865 * math.sign(0); // returns 0
21866 *
21867 * math.sign([3, 5, -2, 0, 2]); // returns [1, 1, -1, 0, 1]
21868 *
21869 * See also:
21870 *
21871 * abs
21872 *
21873 * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x
21874 * The number for which to determine the sign
21875 * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit}e
21876 * The sign of `x`
21877 */
21878 var sign = typed('sign', {
21879 'number': number.sign,
21880
21881 'Complex': function (x) {
21882 return x.sign();
21883 },
21884
21885 'BigNumber': function (x) {
21886 return new type.BigNumber(x.cmp(0));
21887 },
21888
21889 'Fraction': function (x) {
21890 return new type.Fraction(x.s, 1);
21891 },
21892
21893 'Array | Matrix': function (x) {
21894 // deep map collection, skip zeros since sign(0) = 0
21895 return deepMap(x, sign, true);
21896 },
21897
21898 'Unit': function(x) {
21899 return sign(x.value);
21900 }
21901 });
21902
21903 sign.toTex = {1: '\\mathrm{${name}}\\left(${args[0]}\\right)'};
21904
21905 return sign;
21906}
21907
21908exports.name = 'sign';
21909exports.factory = factory;
21910
21911
21912
21913/***/ }),
21914/* 126 */
21915/***/ (function(module, exports, __webpack_require__) {
21916
21917"use strict";
21918
21919
21920var deepMap = __webpack_require__(1);
21921
21922function factory (type, config, load, typed) {
21923 /**
21924 * Compute the complex conjugate of a complex value.
21925 * If `x = a+bi`, the complex conjugate of `x` is `a - bi`.
21926 *
21927 * For matrices, the function is evaluated element wise.
21928 *
21929 * Syntax:
21930 *
21931 * math.conj(x)
21932 *
21933 * Examples:
21934 *
21935 * math.conj(math.complex('2 + 3i')); // returns Complex 2 - 3i
21936 * math.conj(math.complex('2 - 3i')); // returns Complex 2 + 3i
21937 * math.conj(math.complex('-5.2i')); // returns Complex 5.2i
21938 *
21939 * See also:
21940 *
21941 * re, im, arg, abs
21942 *
21943 * @param {number | BigNumber | Complex | Array | Matrix} x
21944 * A complex number or array with complex numbers
21945 * @return {number | BigNumber | Complex | Array | Matrix}
21946 * The complex conjugate of x
21947 */
21948 var conj = typed('conj', {
21949 'number': function (x) {
21950 return x;
21951 },
21952
21953 'BigNumber': function (x) {
21954 return x;
21955 },
21956
21957 'Complex': function (x) {
21958 return x.conjugate();
21959 },
21960
21961 'Array | Matrix': function (x) {
21962 return deepMap(x, conj);
21963 }
21964 });
21965
21966 conj.toTex = {1: '\\left(${args[0]}\\right)^*'};
21967
21968 return conj;
21969}
21970
21971exports.name = 'conj';
21972exports.factory = factory;
21973
21974
21975/***/ }),
21976/* 127 */
21977/***/ (function(module, exports, __webpack_require__) {
21978
21979"use strict";
21980
21981
21982var util = __webpack_require__(25);
21983
21984var object = util.object;
21985
21986function factory (type, config, load, typed) {
21987
21988 var matrix = load(__webpack_require__(0));
21989 var abs = load(__webpack_require__(28));
21990 var addScalar = load(__webpack_require__(16));
21991 var divideScalar = load(__webpack_require__(14));
21992 var multiplyScalar = load(__webpack_require__(22));
21993 var subtract = load(__webpack_require__(21));
21994 var larger = load(__webpack_require__(34));
21995 var equalScalar = load(__webpack_require__(10));
21996 var unaryMinus = load(__webpack_require__(35));
21997
21998 var SparseMatrix = type.SparseMatrix;
21999 var DenseMatrix = type.DenseMatrix;
22000 var Spa = type.Spa;
22001
22002 /**
22003 * Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a
22004 * row permutation vector `p` where `A[p,:] = L * U`
22005 *
22006 * Syntax:
22007 *
22008 * math.lup(A);
22009 *
22010 * Example:
22011 *
22012 * var m = [[2, 1], [1, 4]];
22013 * var r = math.lup(m);
22014 * // r = {
22015 * // L: [[1, 0], [0.5, 1]],
22016 * // U: [[2, 1], [0, 3.5]],
22017 * // P: [0, 1]
22018 * // }
22019 *
22020 * See also:
22021 *
22022 * slu, lsolve, lusolve, usolve
22023 *
22024 * @param {Matrix | Array} A A two dimensional matrix or array for which to get the LUP decomposition.
22025 *
22026 * @return {{L: Array | Matrix, U: Array | Matrix, P: Array.<number>}} The lower triangular matrix, the upper triangular matrix and the permutation matrix.
22027 */
22028 var lup = typed('lup', {
22029
22030 'DenseMatrix': function (m) {
22031 return _denseLUP(m);
22032 },
22033
22034 'SparseMatrix': function (m) {
22035 return _sparseLUP(m);
22036 },
22037
22038 'Array': function (a) {
22039 // create dense matrix from array
22040 var m = matrix(a);
22041 // lup, use matrix implementation
22042 var r = _denseLUP(m);
22043 // result
22044 return {
22045 L: r.L.valueOf(),
22046 U: r.U.valueOf(),
22047 p: r.p
22048 };
22049 }
22050 });
22051
22052 var _denseLUP = function (m) {
22053 // rows & columns
22054 var rows = m._size[0];
22055 var columns = m._size[1];
22056 // minimum rows and columns
22057 var n = Math.min(rows, columns);
22058 // matrix array, clone original data
22059 var data = object.clone(m._data);
22060 // l matrix arrays
22061 var ldata = [];
22062 var lsize = [rows, n];
22063 // u matrix arrays
22064 var udata = [];
22065 var usize = [n, columns];
22066 // vars
22067 var i, j, k;
22068 // permutation vector
22069 var p = [];
22070 for (i = 0; i < rows; i++)
22071 p[i] = i;
22072 // loop columns
22073 for (j = 0; j < columns; j++) {
22074 // skip first column in upper triangular matrix
22075 if (j > 0) {
22076 // loop rows
22077 for (i = 0; i < rows; i++) {
22078 // min i,j
22079 var min = Math.min(i, j);
22080 // v[i, j]
22081 var s = 0;
22082 // loop up to min
22083 for (k = 0; k < min; k++) {
22084 // s = l[i, k] - data[k, j]
22085 s = addScalar(s, multiplyScalar(data[i][k], data[k][j]));
22086 }
22087 data[i][j] = subtract(data[i][j], s);
22088 }
22089 }
22090 // row with larger value in cvector, row >= j
22091 var pi = j;
22092 var pabsv = 0;
22093 var vjj = 0;
22094 // loop rows
22095 for (i = j; i < rows; i++) {
22096 // data @ i, j
22097 var v = data[i][j];
22098 // absolute value
22099 var absv = abs(v);
22100 // value is greater than pivote value
22101 if (larger(absv, pabsv)) {
22102 // store row
22103 pi = i;
22104 // update max value
22105 pabsv = absv;
22106 // value @ [j, j]
22107 vjj = v;
22108 }
22109 }
22110 // swap rows (j <-> pi)
22111 if (j !== pi) {
22112 // swap values j <-> pi in p
22113 p[j] = [p[pi], p[pi] = p[j]][0];
22114 // swap j <-> pi in data
22115 DenseMatrix._swapRows(j, pi, data);
22116 }
22117 // check column is in lower triangular matrix
22118 if (j < rows) {
22119 // loop rows (lower triangular matrix)
22120 for (i = j + 1; i < rows; i++) {
22121 // value @ i, j
22122 var vij = data[i][j];
22123 if (!equalScalar(vij, 0)) {
22124 // update data
22125 data[i][j] = divideScalar(data[i][j], vjj);
22126 }
22127 }
22128 }
22129 }
22130 // loop columns
22131 for (j = 0; j < columns; j++) {
22132 // loop rows
22133 for (i = 0; i < rows; i++) {
22134 // initialize row in arrays
22135 if (j === 0) {
22136 // check row exists in upper triangular matrix
22137 if (i < columns) {
22138 // U
22139 udata[i] = [];
22140 }
22141 // L
22142 ldata[i] = [];
22143 }
22144 // check we are in the upper triangular matrix
22145 if (i < j) {
22146 // check row exists in upper triangular matrix
22147 if (i < columns) {
22148 // U
22149 udata[i][j] = data[i][j];
22150 }
22151 // check column exists in lower triangular matrix
22152 if (j < rows) {
22153 // L
22154 ldata[i][j] = 0;
22155 }
22156 continue;
22157 }
22158 // diagonal value
22159 if (i === j) {
22160 // check row exists in upper triangular matrix
22161 if (i < columns) {
22162 // U
22163 udata[i][j] = data[i][j];
22164 }
22165 // check column exists in lower triangular matrix
22166 if (j < rows) {
22167 // L
22168 ldata[i][j] = 1;
22169 }
22170 continue;
22171 }
22172 // check row exists in upper triangular matrix
22173 if (i < columns) {
22174 // U
22175 udata[i][j] = 0;
22176 }
22177 // check column exists in lower triangular matrix
22178 if (j < rows) {
22179 // L
22180 ldata[i][j] = data[i][j];
22181 }
22182 }
22183 }
22184 // l matrix
22185 var l = new DenseMatrix({
22186 data: ldata,
22187 size: lsize
22188 });
22189 // u matrix
22190 var u = new DenseMatrix({
22191 data: udata,
22192 size: usize
22193 });
22194 // p vector
22195 var pv = [];
22196 for (i = 0, n = p.length; i < n; i++)
22197 pv[p[i]] = i;
22198 // return matrices
22199 return {
22200 L: l,
22201 U: u,
22202 p: pv,
22203 toString: function () {
22204 return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p;
22205 }
22206 };
22207 };
22208
22209 var _sparseLUP = function (m) {
22210 // rows & columns
22211 var rows = m._size[0];
22212 var columns = m._size[1];
22213 // minimum rows and columns
22214 var n = Math.min(rows, columns);
22215 // matrix arrays (will not be modified, thanks to permutation vector)
22216 var values = m._values;
22217 var index = m._index;
22218 var ptr = m._ptr;
22219 // l matrix arrays
22220 var lvalues = [];
22221 var lindex = [];
22222 var lptr = [];
22223 var lsize = [rows, n];
22224 // u matrix arrays
22225 var uvalues = [];
22226 var uindex = [];
22227 var uptr = [];
22228 var usize = [n, columns];
22229 // vars
22230 var i, j, k;
22231 // permutation vectors, (current index -> original index) and (original index -> current index)
22232 var pv_co = [];
22233 var pv_oc = [];
22234 for (i = 0; i < rows; i++) {
22235 pv_co[i] = i;
22236 pv_oc[i] = i;
22237 }
22238 // swap indices in permutation vectors (condition x < y)!
22239 var swapIndeces = function (x, y) {
22240 // find pv indeces getting data from x and y
22241 var kx = pv_oc[x];
22242 var ky = pv_oc[y];
22243 // update permutation vector current -> original
22244 pv_co[kx] = y;
22245 pv_co[ky] = x;
22246 // update permutation vector original -> current
22247 pv_oc[x] = ky;
22248 pv_oc[y] = kx;
22249 };
22250 // loop columns
22251 for (j = 0; j < columns; j++) {
22252 // sparse accumulator
22253 var spa = new Spa();
22254 // check lower triangular matrix has a value @ column j
22255 if (j < rows) {
22256 // update ptr
22257 lptr.push(lvalues.length);
22258 // first value in j column for lower triangular matrix
22259 lvalues.push(1);
22260 lindex.push(j);
22261 }
22262 // update ptr
22263 uptr.push(uvalues.length);
22264 // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
22265 var k0 = ptr[j];
22266 var k1 = ptr[j + 1];
22267 // copy column j into sparse accumulator
22268 for (k = k0; k < k1; k++) {
22269 // row
22270 i = index[k];
22271 // copy column values into sparse accumulator (use permutation vector)
22272 spa.set(pv_co[i], values[k]);
22273 }
22274 // skip first column in upper triangular matrix
22275 if (j > 0) {
22276 // loop rows in column j (above diagonal)
22277 spa.forEach(0, j - 1, function (k, vkj) {
22278 // loop rows in column k (L)
22279 SparseMatrix._forEachRow(k, lvalues, lindex, lptr, function (i, vik) {
22280 // check row is below k
22281 if (i > k) {
22282 // update spa value
22283 spa.accumulate(i, unaryMinus(multiplyScalar(vik, vkj)));
22284 }
22285 });
22286 });
22287 }
22288 // row with larger value in spa, row >= j
22289 var pi = j;
22290 var vjj = spa.get(j);
22291 var pabsv = abs(vjj);
22292 // loop values in spa (order by row, below diagonal)
22293 spa.forEach(j + 1, rows - 1, function (x, v) {
22294 // absolute value
22295 var absv = abs(v);
22296 // value is greater than pivote value
22297 if (larger(absv, pabsv)) {
22298 // store row
22299 pi = x;
22300 // update max value
22301 pabsv = absv;
22302 // value @ [j, j]
22303 vjj = v;
22304 }
22305 });
22306 // swap rows (j <-> pi)
22307 if (j !== pi) {
22308 // swap values j <-> pi in L
22309 SparseMatrix._swapRows(j, pi, lsize[1], lvalues, lindex, lptr);
22310 // swap values j <-> pi in U
22311 SparseMatrix._swapRows(j, pi, usize[1], uvalues, uindex, uptr);
22312 // swap values in spa
22313 spa.swap(j, pi);
22314 // update permutation vector (swap values @ j, pi)
22315 swapIndeces(j, pi);
22316 }
22317 // loop values in spa (order by row)
22318 spa.forEach(0, rows - 1, function (x, v) {
22319 // check we are above diagonal
22320 if (x <= j) {
22321 // update upper triangular matrix
22322 uvalues.push(v);
22323 uindex.push(x);
22324 }
22325 else {
22326 // update value
22327 v = divideScalar(v, vjj);
22328 // check value is non zero
22329 if (!equalScalar(v, 0)) {
22330 // update lower triangular matrix
22331 lvalues.push(v);
22332 lindex.push(x);
22333 }
22334 }
22335 });
22336 }
22337 // update ptrs
22338 uptr.push(uvalues.length);
22339 lptr.push(lvalues.length);
22340
22341 // return matrices
22342 return {
22343 L: new SparseMatrix({
22344 values: lvalues,
22345 index: lindex,
22346 ptr: lptr,
22347 size: lsize
22348 }),
22349 U: new SparseMatrix({
22350 values: uvalues,
22351 index: uindex,
22352 ptr: uptr,
22353 size: usize
22354 }),
22355 p: pv_co,
22356 toString: function () {
22357 return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p;
22358 }
22359 };
22360 };
22361
22362 return lup;
22363}
22364
22365exports.name = 'lup';
22366exports.factory = factory;
22367
22368
22369/***/ }),
22370/* 128 */
22371/***/ (function(module, exports, __webpack_require__) {
22372
22373"use strict";
22374
22375
22376var util = __webpack_require__(25);
22377
22378var number = util.number,
22379
22380 isInteger = number.isInteger;
22381
22382function factory (type, config, load, typed) {
22383
22384 var cs_sqr = load(__webpack_require__(413));
22385 var cs_lu = load(__webpack_require__(421));
22386
22387 /**
22388 * 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
22389 *
22390 * `P * A * Q = L * U`
22391 *
22392 * Syntax:
22393 *
22394 * math.slu(A, order, threshold);
22395 *
22396 * See also:
22397 *
22398 * lup, lsolve, usolve, lusolve
22399 *
22400 * @param {SparseMatrix} A A two dimensional sparse matrix for which to get the LU decomposition.
22401 * @param {Number} order The Symbolic Ordering and Analysis order:
22402 * 0 - Natural ordering, no permutation vector q is returned
22403 * 1 - Matrix must be square, symbolic ordering and analisis is performed on M = A + A'
22404 * 2 - Symbolic ordering and analisis is performed on M = A' * A. Dense columns from A' are dropped, A recreated from A'.
22405 * This is appropriatefor LU factorization of unsymmetric matrices.
22406 * 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.
22407 * A dense row is a row with more than 10*sqr(columns) entries.
22408 * @param {Number} threshold Partial pivoting threshold (1 for partial pivoting)
22409 *
22410 * @return {Object} The lower triangular matrix, the upper triangular matrix and the permutation vectors.
22411 */
22412 var slu = typed('slu', {
22413
22414 'SparseMatrix, number, number': function (a, order, threshold) {
22415 // verify order
22416 if (!isInteger(order) || order < 0 || order > 3)
22417 throw new Error('Symbolic Ordering and Analysis order must be an integer number in the interval [0, 3]');
22418 // verify threshold
22419 if (threshold < 0 || threshold > 1)
22420 throw new Error('Partial pivoting threshold must be a number from 0 to 1');
22421
22422 // perform symbolic ordering and analysis
22423 var s = cs_sqr(order, a, false);
22424
22425 // perform lu decomposition
22426 var f = cs_lu(a, s, threshold);
22427
22428 // return decomposition
22429 return {
22430 L: f.L,
22431 U: f.U,
22432 p: f.pinv,
22433 q: s.q,
22434 toString: function () {
22435 return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\np: ' + this.p.toString() + (this.q ? '\nq: ' + this.q.toString() : '') + '\n';
22436 }
22437 };
22438 }
22439 });
22440
22441 return slu;
22442}
22443
22444exports.name = 'slu';
22445exports.factory = factory;
22446
22447
22448/***/ }),
22449/* 129 */
22450/***/ (function(module, exports, __webpack_require__) {
22451
22452"use strict";
22453
22454
22455function factory () {
22456
22457 /**
22458 * Depth-first search and postorder of a tree rooted at node j
22459 *
22460 * @param {Number} j The tree node
22461 * @param {Number} k
22462 * @param {Array} w The workspace array
22463 * @param {Number} head The index offset within the workspace for the head array
22464 * @param {Number} next The index offset within the workspace for the next array
22465 * @param {Array} post The post ordering array
22466 * @param {Number} stack The index offset within the workspace for the stack array
22467 *
22468 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
22469 */
22470 var cs_tdfs = function (j, k, w, head, next, post, stack) {
22471 // variables
22472 var top = 0;
22473 // place j on the stack
22474 w[stack] = j;
22475 // while (stack is not empty)
22476 while (top >= 0) {
22477 // p = top of stack
22478 var p = w[stack + top];
22479 // i = youngest child of p
22480 var i = w[head + p];
22481 if (i == -1) {
22482 // p has no unordered children left
22483 top--;
22484 // node p is the kth postordered node
22485 post[k++] = p;
22486 }
22487 else {
22488 // remove i from children of p
22489 w[head + p] = w[next + i];
22490 // increment top
22491 ++top;
22492 // start dfs on child node i
22493 w[stack + top] = i;
22494 }
22495 }
22496 return k;
22497 };
22498
22499 return cs_tdfs;
22500}
22501
22502exports.name = 'cs_tdfs';
22503exports.path = 'sparse';
22504exports.factory = factory;
22505
22506
22507/***/ }),
22508/* 130 */
22509/***/ (function(module, exports, __webpack_require__) {
22510
22511"use strict";
22512
22513
22514var nearlyEqual = __webpack_require__(3).nearlyEqual;
22515var bigNearlyEqual = __webpack_require__(37);
22516
22517function factory (type, config, load, typed) {
22518
22519 var matrix = load(__webpack_require__(0));
22520
22521 var algorithm03 = load(__webpack_require__(17));
22522 var algorithm07 = load(__webpack_require__(26));
22523 var algorithm12 = load(__webpack_require__(18));
22524 var algorithm13 = load(__webpack_require__(8));
22525 var algorithm14 = load(__webpack_require__(6));
22526
22527 var latex = __webpack_require__(4);
22528
22529 /**
22530 * Test whether value x is larger or equal to y.
22531 *
22532 * The function returns true when x is larger than y or the relative
22533 * difference between x and y is smaller than the configured epsilon. The
22534 * function cannot be used to compare values smaller than approximately 2.22e-16.
22535 *
22536 * For matrices, the function is evaluated element wise.
22537 *
22538 * Syntax:
22539 *
22540 * math.largerEq(x, y)
22541 *
22542 * Examples:
22543 *
22544 * math.larger(2, 1 + 1); // returns false
22545 * math.largerEq(2, 1 + 1); // returns true
22546 *
22547 * See also:
22548 *
22549 * equal, unequal, smaller, smallerEq, larger, compare
22550 *
22551 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
22552 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
22553 * @return {boolean | Array | Matrix} Returns true when the x is larger or equal to y, else returns false
22554 */
22555 var largerEq = typed('largerEq', {
22556
22557 'boolean, boolean': function (x, y) {
22558 return x >= y;
22559 },
22560
22561 'number, number': function (x, y) {
22562 return x >= y || nearlyEqual(x, y, config.epsilon);
22563 },
22564
22565 'BigNumber, BigNumber': function (x, y) {
22566 return x.gte(y) || bigNearlyEqual(x, y, config.epsilon);
22567 },
22568
22569 'Fraction, Fraction': function (x, y) {
22570 return x.compare(y) !== -1;
22571 },
22572
22573 'Complex, Complex': function () {
22574 throw new TypeError('No ordering relation is defined for complex numbers');
22575 },
22576
22577 'Unit, Unit': function (x, y) {
22578 if (!x.equalBase(y)) {
22579 throw new Error('Cannot compare units with different base');
22580 }
22581 return largerEq(x.value, y.value);
22582 },
22583
22584 'string, string': function (x, y) {
22585 return x >= y;
22586 },
22587
22588 'Matrix, Matrix': function (x, y) {
22589 // result
22590 var c;
22591
22592 // process matrix storage
22593 switch (x.storage()) {
22594 case 'sparse':
22595 switch (y.storage()) {
22596 case 'sparse':
22597 // sparse + sparse
22598 c = algorithm07(x, y, largerEq);
22599 break;
22600 default:
22601 // sparse + dense
22602 c = algorithm03(y, x, largerEq, true);
22603 break;
22604 }
22605 break;
22606 default:
22607 switch (y.storage()) {
22608 case 'sparse':
22609 // dense + sparse
22610 c = algorithm03(x, y, largerEq, false);
22611 break;
22612 default:
22613 // dense + dense
22614 c = algorithm13(x, y, largerEq);
22615 break;
22616 }
22617 break;
22618 }
22619 return c;
22620 },
22621
22622 'Array, Array': function (x, y) {
22623 // use matrix implementation
22624 return largerEq(matrix(x), matrix(y)).valueOf();
22625 },
22626
22627 'Array, Matrix': function (x, y) {
22628 // use matrix implementation
22629 return largerEq(matrix(x), y);
22630 },
22631
22632 'Matrix, Array': function (x, y) {
22633 // use matrix implementation
22634 return largerEq(x, matrix(y));
22635 },
22636
22637 'Matrix, any': function (x, y) {
22638 // result
22639 var c;
22640 // check storage format
22641 switch (x.storage()) {
22642 case 'sparse':
22643 c = algorithm12(x, y, largerEq, false);
22644 break;
22645 default:
22646 c = algorithm14(x, y, largerEq, false);
22647 break;
22648 }
22649 return c;
22650 },
22651
22652 'any, Matrix': function (x, y) {
22653 // result
22654 var c;
22655 // check storage format
22656 switch (y.storage()) {
22657 case 'sparse':
22658 c = algorithm12(y, x, largerEq, true);
22659 break;
22660 default:
22661 c = algorithm14(y, x, largerEq, true);
22662 break;
22663 }
22664 return c;
22665 },
22666
22667 'Array, any': function (x, y) {
22668 // use matrix implementation
22669 return algorithm14(matrix(x), y, largerEq, false).valueOf();
22670 },
22671
22672 'any, Array': function (x, y) {
22673 // use matrix implementation
22674 return algorithm14(matrix(y), x, largerEq, true).valueOf();
22675 }
22676 });
22677
22678 largerEq.toTex = {
22679 2: '\\left(${args[0]}' + latex.operators['largerEq'] + '${args[1]}\\right)'
22680 };
22681
22682 return largerEq;
22683}
22684
22685exports.name = 'largerEq';
22686exports.factory = factory;
22687
22688
22689/***/ }),
22690/* 131 */
22691/***/ (function(module, exports, __webpack_require__) {
22692
22693"use strict";
22694
22695
22696function factory () {
22697
22698 /**
22699 * Checks if the node at w[j] is marked
22700 *
22701 * @param {Array} w The array
22702 * @param {Number} j The array index
22703 *
22704 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
22705 */
22706 var cs_marked = function (w, j) {
22707 // check node is marked
22708 return w[j] < 0;
22709 };
22710
22711 return cs_marked;
22712}
22713
22714exports.name = 'cs_marked';
22715exports.path = 'sparse';
22716exports.factory = factory;
22717
22718
22719/***/ }),
22720/* 132 */
22721/***/ (function(module, exports, __webpack_require__) {
22722
22723"use strict";
22724
22725
22726function factory (type, config, load) {
22727
22728 var cs_flip = load(__webpack_require__(84));
22729
22730 /**
22731 * Marks the node at w[j]
22732 *
22733 * @param {Array} w The array
22734 * @param {Number} j The array index
22735 *
22736 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
22737 */
22738 var cs_mark = function (w, j) {
22739 // mark w[j]
22740 w[j] = cs_flip(w [j]);
22741 };
22742
22743 return cs_mark;
22744}
22745
22746exports.name = 'cs_mark';
22747exports.path = 'sparse';
22748exports.factory = factory;
22749
22750
22751/***/ }),
22752/* 133 */
22753/***/ (function(module, exports, __webpack_require__) {
22754
22755"use strict";
22756
22757
22758function factory (type, config, load, typed) {
22759
22760 var matrix = load(__webpack_require__(0));
22761 var divideScalar = load(__webpack_require__(14));
22762 var multiplyScalar = load(__webpack_require__(22));
22763 var subtract = load(__webpack_require__(21));
22764 var equalScalar = load(__webpack_require__(10));
22765
22766 var solveValidation = load(__webpack_require__(85));
22767
22768 var DenseMatrix = type.DenseMatrix;
22769
22770 /**
22771 * Solves the linear equation system by forwards substitution. Matrix must be a lower triangular matrix.
22772 *
22773 * `L * x = b`
22774 *
22775 * Syntax:
22776 *
22777 * math.lsolve(L, b);
22778 *
22779 * Examples:
22780 *
22781 * var a = [[-2, 3], [2, 1]];
22782 * var b = [11, 9];
22783 * var x = lsolve(a, b); // [[-5.5], [20]]
22784 *
22785 * See also:
22786 *
22787 * lup, slu, usolve, lusolve
22788 *
22789 * @param {Matrix, Array} L A N x N matrix or array (L)
22790 * @param {Matrix, Array} b A column vector with the b values
22791 *
22792 * @return {DenseMatrix | Array} A column vector with the linear system solution (x)
22793 */
22794 var lsolve = typed('lsolve', {
22795
22796 'SparseMatrix, Array | Matrix': function (m, b) {
22797 // process matrix
22798 return _sparseForwardSubstitution(m, b);
22799 },
22800
22801 'DenseMatrix, Array | Matrix': function (m, b) {
22802 // process matrix
22803 return _denseForwardSubstitution(m, b);
22804 },
22805
22806 'Array, Array | Matrix': function (a, b) {
22807 // create dense matrix from array
22808 var m = matrix(a);
22809 // use matrix implementation
22810 var r = _denseForwardSubstitution(m, b);
22811 // result
22812 return r.valueOf();
22813 }
22814 });
22815
22816 var _denseForwardSubstitution = function (m, b) {
22817 // validate matrix and vector, return copy of column vector b
22818 b = solveValidation(m, b, true);
22819 // column vector data
22820 var bdata = b._data;
22821 // rows & columns
22822 var rows = m._size[0];
22823 var columns = m._size[1];
22824 // result
22825 var x = [];
22826 // data
22827 var data = m._data;
22828 // forward solve m * x = b, loop columns
22829 for (var j = 0; j < columns; j++) {
22830 // b[j]
22831 var bj = bdata[j][0] || 0;
22832 // x[j]
22833 var xj;
22834 // forward substitution (outer product) avoids inner looping when bj == 0
22835 if (!equalScalar(bj, 0)) {
22836 // value @ [j, j]
22837 var vjj = data[j][j];
22838 // check vjj
22839 if (equalScalar(vjj, 0)) {
22840 // system cannot be solved
22841 throw new Error('Linear system cannot be solved since matrix is singular');
22842 }
22843 // calculate xj
22844 xj = divideScalar(bj, vjj);
22845 // loop rows
22846 for (var i = j + 1; i < rows; i++) {
22847 // update copy of b
22848 bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, data[i][j]))];
22849 }
22850 }
22851 else {
22852 // zero @ j
22853 xj = 0;
22854 }
22855 // update x
22856 x[j] = [xj];
22857 }
22858 // return vector
22859 return new DenseMatrix({
22860 data: x,
22861 size: [rows, 1]
22862 });
22863 };
22864
22865 var _sparseForwardSubstitution = function (m, b) {
22866 // validate matrix and vector, return copy of column vector b
22867 b = solveValidation(m, b, true);
22868 // column vector data
22869 var bdata = b._data;
22870 // rows & columns
22871 var rows = m._size[0];
22872 var columns = m._size[1];
22873 // matrix arrays
22874 var values = m._values;
22875 var index = m._index;
22876 var ptr = m._ptr;
22877 // vars
22878 var i, k;
22879 // result
22880 var x = [];
22881 // forward solve m * x = b, loop columns
22882 for (var j = 0; j < columns; j++) {
22883 // b[j]
22884 var bj = bdata[j][0] || 0;
22885 // forward substitution (outer product) avoids inner looping when bj == 0
22886 if (!equalScalar(bj, 0)) {
22887 // value @ [j, j]
22888 var vjj = 0;
22889 // lower triangular matrix values & index (column j)
22890 var jvalues = [];
22891 var jindex = [];
22892 // last index in column
22893 var l = ptr[j + 1];
22894 // values in column, find value @ [j, j]
22895 for (k = ptr[j]; k < l; k++) {
22896 // row
22897 i = index[k];
22898 // check row (rows are not sorted!)
22899 if (i === j) {
22900 // update vjj
22901 vjj = values[k];
22902 }
22903 else if (i > j) {
22904 // store lower triangular
22905 jvalues.push(values[k]);
22906 jindex.push(i);
22907 }
22908 }
22909 // at this point we must have a value @ [j, j]
22910 if (equalScalar(vjj, 0)) {
22911 // system cannot be solved, there is no value @ [j, j]
22912 throw new Error('Linear system cannot be solved since matrix is singular');
22913 }
22914 // calculate xj
22915 var xj = divideScalar(bj, vjj);
22916 // loop lower triangular
22917 for (k = 0, l = jindex.length; k < l; k++) {
22918 // row
22919 i = jindex[k];
22920 // update copy of b
22921 bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, jvalues[k]))];
22922 }
22923 // update x
22924 x[j] = [xj];
22925 }
22926 else {
22927 // update x
22928 x[j] = [0];
22929 }
22930 }
22931 // return vector
22932 return new DenseMatrix({
22933 data: x,
22934 size: [rows, 1]
22935 });
22936 };
22937
22938 return lsolve;
22939}
22940
22941exports.name = 'lsolve';
22942exports.factory = factory;
22943
22944
22945/***/ }),
22946/* 134 */
22947/***/ (function(module, exports, __webpack_require__) {
22948
22949"use strict";
22950
22951
22952function factory (type, config, load, typed) {
22953
22954 var matrix = load(__webpack_require__(0));
22955 var divideScalar = load(__webpack_require__(14));
22956 var multiplyScalar = load(__webpack_require__(22));
22957 var subtract = load(__webpack_require__(21));
22958 var equalScalar = load(__webpack_require__(10));
22959
22960 var solveValidation = load(__webpack_require__(85));
22961
22962 var DenseMatrix = type.DenseMatrix;
22963
22964 /**
22965 * Solves the linear equation system by backward substitution. Matrix must be an upper triangular matrix.
22966 *
22967 * `U * x = b`
22968 *
22969 * Syntax:
22970 *
22971 * math.usolve(U, b);
22972 *
22973 * Examples:
22974 *
22975 * var a = [[-2, 3], [2, 1]];
22976 * var b = [11, 9];
22977 * var x = usolve(a, b); // [[8], [9]]
22978 *
22979 * See also:
22980 *
22981 * lup, slu, usolve, lusolve
22982 *
22983 * @param {Matrix, Array} U A N x N matrix or array (U)
22984 * @param {Matrix, Array} b A column vector with the b values
22985 *
22986 * @return {DenseMatrix | Array} A column vector with the linear system solution (x)
22987 */
22988 var usolve = typed('usolve', {
22989
22990 'SparseMatrix, Array | Matrix': function (m, b) {
22991 // process matrix
22992 return _sparseBackwardSubstitution(m, b);
22993 },
22994
22995 'DenseMatrix, Array | Matrix': function (m, b) {
22996 // process matrix
22997 return _denseBackwardSubstitution(m, b);
22998 },
22999
23000 'Array, Array | Matrix': function (a, b) {
23001 // create dense matrix from array
23002 var m = matrix(a);
23003 // use matrix implementation
23004 var r = _denseBackwardSubstitution(m, b);
23005 // result
23006 return r.valueOf();
23007 }
23008 });
23009
23010 var _denseBackwardSubstitution = function (m, b) {
23011 // validate matrix and vector, return copy of column vector b
23012 b = solveValidation(m, b, true);
23013 // column vector data
23014 var bdata = b._data;
23015 // rows & columns
23016 var rows = m._size[0];
23017 var columns = m._size[1];
23018 // result
23019 var x = [];
23020 // arrays
23021 var data = m._data;
23022 // backward solve m * x = b, loop columns (backwards)
23023 for (var j = columns - 1; j >= 0 ; j--) {
23024 // b[j]
23025 var bj = bdata[j][0] || 0;
23026 // x[j]
23027 var xj;
23028 // backward substitution (outer product) avoids inner looping when bj == 0
23029 if (!equalScalar(bj, 0)) {
23030 // value @ [j, j]
23031 var vjj = data[j][j];
23032 // check vjj
23033 if (equalScalar(vjj, 0)) {
23034 // system cannot be solved
23035 throw new Error('Linear system cannot be solved since matrix is singular');
23036 }
23037 // calculate xj
23038 xj = divideScalar(bj, vjj);
23039 // loop rows
23040 for (var i = j - 1; i >= 0; i--) {
23041 // update copy of b
23042 bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, data[i][j]))];
23043 }
23044 }
23045 else {
23046 // zero value @ j
23047 xj = 0;
23048 }
23049 // update x
23050 x[j] = [xj];
23051 }
23052 // return column vector
23053 return new DenseMatrix({
23054 data: x,
23055 size: [rows, 1]
23056 });
23057 };
23058
23059 var _sparseBackwardSubstitution = function (m, b) {
23060 // validate matrix and vector, return copy of column vector b
23061 b = solveValidation(m, b, true);
23062 // column vector data
23063 var bdata = b._data;
23064 // rows & columns
23065 var rows = m._size[0];
23066 var columns = m._size[1];
23067 // matrix arrays
23068 var values = m._values;
23069 var index = m._index;
23070 var ptr = m._ptr;
23071 // vars
23072 var i, k;
23073 // result
23074 var x = [];
23075 // backward solve m * x = b, loop columns (backwards)
23076 for (var j = columns - 1; j >= 0 ; j--) {
23077 // b[j]
23078 var bj = bdata[j][0] || 0;
23079 // backward substitution (outer product) avoids inner looping when bj == 0
23080 if (!equalScalar(bj, 0)) {
23081 // value @ [j, j]
23082 var vjj = 0;
23083 // upper triangular matrix values & index (column j)
23084 var jvalues = [];
23085 var jindex = [];
23086 // first & last indeces in column
23087 var f = ptr[j];
23088 var l = ptr[j + 1];
23089 // values in column, find value @ [j, j], loop backwards
23090 for (k = l - 1; k >= f; k--) {
23091 // row
23092 i = index[k];
23093 // check row
23094 if (i === j) {
23095 // update vjj
23096 vjj = values[k];
23097 }
23098 else if (i < j) {
23099 // store upper triangular
23100 jvalues.push(values[k]);
23101 jindex.push(i);
23102 }
23103 }
23104 // at this point we must have a value @ [j, j]
23105 if (equalScalar(vjj, 0)) {
23106 // system cannot be solved, there is no value @ [j, j]
23107 throw new Error('Linear system cannot be solved since matrix is singular');
23108 }
23109 // calculate xj
23110 var xj = divideScalar(bj, vjj);
23111 // loop upper triangular
23112 for (k = 0, l = jindex.length; k < l; k++) {
23113 // row
23114 i = jindex[k];
23115 // update copy of b
23116 bdata[i] = [subtract(bdata[i][0], multiplyScalar(xj, jvalues[k]))];
23117 }
23118 // update x
23119 x[j] = [xj];
23120 }
23121 else {
23122 // update x
23123 x[j] = [0];
23124 }
23125 }
23126 // return vector
23127 return new DenseMatrix({
23128 data: x,
23129 size: [rows, 1]
23130 });
23131 };
23132
23133 return usolve;
23134}
23135
23136exports.name = 'usolve';
23137exports.factory = factory;
23138
23139
23140/***/ }),
23141/* 135 */
23142/***/ (function(module, exports, __webpack_require__) {
23143
23144"use strict";
23145
23146
23147function factory (type, config, load, typed) {
23148
23149 var matrix = load(__webpack_require__(0));
23150 var divideScalar = load(__webpack_require__(14));
23151 var latex = __webpack_require__(4);
23152
23153 var algorithm02 = load(__webpack_require__(24));
23154 var algorithm03 = load(__webpack_require__(17));
23155 var algorithm07 = load(__webpack_require__(26));
23156 var algorithm11 = load(__webpack_require__(19));
23157 var algorithm12 = load(__webpack_require__(18));
23158 var algorithm13 = load(__webpack_require__(8));
23159 var algorithm14 = load(__webpack_require__(6));
23160
23161 /**
23162 * Divide two matrices element wise. The function accepts both matrices and
23163 * scalar values.
23164 *
23165 * Syntax:
23166 *
23167 * math.dotDivide(x, y)
23168 *
23169 * Examples:
23170 *
23171 * math.dotDivide(2, 4); // returns 0.5
23172 *
23173 * a = [[9, 5], [6, 1]];
23174 * b = [[3, 2], [5, 2]];
23175 *
23176 * math.dotDivide(a, b); // returns [[3, 2.5], [1.2, 0.5]]
23177 * math.divide(a, b); // returns [[1.75, 0.75], [-1.75, 2.25]]
23178 *
23179 * See also:
23180 *
23181 * divide, multiply, dotMultiply
23182 *
23183 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Numerator
23184 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Denominator
23185 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Quotient, `x ./ y`
23186 */
23187 var dotDivide = typed('dotDivide', {
23188
23189 'any, any': divideScalar,
23190
23191 'Matrix, Matrix': function (x, y) {
23192 // result
23193 var c;
23194
23195 // process matrix storage
23196 switch (x.storage()) {
23197 case 'sparse':
23198 switch (y.storage()) {
23199 case 'sparse':
23200 // sparse ./ sparse
23201 c = algorithm07(x, y, divideScalar, false);
23202 break;
23203 default:
23204 // sparse ./ dense
23205 c = algorithm02(y, x, divideScalar, true);
23206 break;
23207 }
23208 break;
23209 default:
23210 switch (y.storage()) {
23211 case 'sparse':
23212 // dense ./ sparse
23213 c = algorithm03(x, y, divideScalar, false);
23214 break;
23215 default:
23216 // dense ./ dense
23217 c = algorithm13(x, y, divideScalar);
23218 break;
23219 }
23220 break;
23221 }
23222 return c;
23223 },
23224
23225 'Array, Array': function (x, y) {
23226 // use matrix implementation
23227 return dotDivide(matrix(x), matrix(y)).valueOf();
23228 },
23229
23230 'Array, Matrix': function (x, y) {
23231 // use matrix implementation
23232 return dotDivide(matrix(x), y);
23233 },
23234
23235 'Matrix, Array': function (x, y) {
23236 // use matrix implementation
23237 return dotDivide(x, matrix(y));
23238 },
23239
23240 'Matrix, any': function (x, y) {
23241 // result
23242 var c;
23243 // check storage format
23244 switch (x.storage()) {
23245 case 'sparse':
23246 c = algorithm11(x, y, divideScalar, false);
23247 break;
23248 default:
23249 c = algorithm14(x, y, divideScalar, false);
23250 break;
23251 }
23252 return c;
23253 },
23254
23255 'any, Matrix': function (x, y) {
23256 // result
23257 var c;
23258 // check storage format
23259 switch (y.storage()) {
23260 case 'sparse':
23261 c = algorithm12(y, x, divideScalar, true);
23262 break;
23263 default:
23264 c = algorithm14(y, x, divideScalar, true);
23265 break;
23266 }
23267 return c;
23268 },
23269
23270 'Array, any': function (x, y) {
23271 // use matrix implementation
23272 return algorithm14(matrix(x), y, divideScalar, false).valueOf();
23273 },
23274
23275 'any, Array': function (x, y) {
23276 // use matrix implementation
23277 return algorithm14(matrix(y), x, divideScalar, true).valueOf();
23278 }
23279 });
23280
23281 dotDivide.toTex = {
23282 2: '\\left(${args[0]}' + latex.operators['dotDivide'] + '${args[1]}\\right)'
23283 };
23284
23285 return dotDivide;
23286}
23287
23288exports.name = 'dotDivide';
23289exports.factory = factory;
23290
23291
23292/***/ }),
23293/* 136 */
23294/***/ (function(module, exports, __webpack_require__) {
23295
23296"use strict";
23297
23298
23299var DimensionError = __webpack_require__(11);
23300
23301function factory (type, config, load, typed) {
23302
23303 var equalScalar = load(__webpack_require__(10));
23304
23305 var SparseMatrix = type.SparseMatrix;
23306
23307 /**
23308 * Iterates over SparseMatrix A and invokes the callback function f(Aij, Bij).
23309 * Callback function invoked NZA times, number of nonzero elements in A.
23310 *
23311 *
23312 * ┌ f(Aij, Bij) ; A(i,j) !== 0
23313 * C(i,j) = ┤
23314 * └ 0 ; otherwise
23315 *
23316 *
23317 * @param {Matrix} a The SparseMatrix instance (A)
23318 * @param {Matrix} b The SparseMatrix instance (B)
23319 * @param {Function} callback The f(Aij,Bij) operation to invoke
23320 *
23321 * @return {Matrix} SparseMatrix (C)
23322 *
23323 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
23324 */
23325 var algorithm09 = function (a, b, callback) {
23326 // sparse matrix arrays
23327 var avalues = a._values;
23328 var aindex = a._index;
23329 var aptr = a._ptr;
23330 var asize = a._size;
23331 var adt = a._datatype;
23332 // sparse matrix arrays
23333 var bvalues = b._values;
23334 var bindex = b._index;
23335 var bptr = b._ptr;
23336 var bsize = b._size;
23337 var bdt = b._datatype;
23338
23339 // validate dimensions
23340 if (asize.length !== bsize.length)
23341 throw new DimensionError(asize.length, bsize.length);
23342
23343 // check rows & columns
23344 if (asize[0] !== bsize[0] || asize[1] !== bsize[1])
23345 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
23346
23347 // rows & columns
23348 var rows = asize[0];
23349 var columns = asize[1];
23350
23351 // datatype
23352 var dt;
23353 // equal signature to use
23354 var eq = equalScalar;
23355 // zero value
23356 var zero = 0;
23357 // callback signature to use
23358 var cf = callback;
23359
23360 // process data types
23361 if (typeof adt === 'string' && adt === bdt) {
23362 // datatype
23363 dt = adt;
23364 // find signature that matches (dt, dt)
23365 eq = typed.find(equalScalar, [dt, dt]);
23366 // convert 0 to the same datatype
23367 zero = typed.convert(0, dt);
23368 // callback
23369 cf = typed.find(callback, [dt, dt]);
23370 }
23371
23372 // result arrays
23373 var cvalues = avalues && bvalues ? [] : undefined;
23374 var cindex = [];
23375 var cptr = [];
23376 // matrix
23377 var c = new SparseMatrix({
23378 values: cvalues,
23379 index: cindex,
23380 ptr: cptr,
23381 size: [rows, columns],
23382 datatype: dt
23383 });
23384
23385 // workspaces
23386 var x = cvalues ? [] : undefined;
23387 // marks indicating we have a value in x for a given column
23388 var w = [];
23389
23390 // vars
23391 var i, j, k, k0, k1;
23392
23393 // loop columns
23394 for (j = 0; j < columns; j++) {
23395 // update cptr
23396 cptr[j] = cindex.length;
23397 // column mark
23398 var mark = j + 1;
23399 // check we need to process values
23400 if (x) {
23401 // loop B(:,j)
23402 for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
23403 // row
23404 i = bindex[k];
23405 // update workspace
23406 w[i] = mark;
23407 x[i] = bvalues[k];
23408 }
23409 }
23410 // loop A(:,j)
23411 for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
23412 // row
23413 i = aindex[k];
23414 // check we need to process values
23415 if (x) {
23416 // b value @ i,j
23417 var vb = w[i] === mark ? x[i] : zero;
23418 // invoke f
23419 var vc = cf(avalues[k], vb);
23420 // check zero value
23421 if (!eq(vc, zero)) {
23422 // push index
23423 cindex.push(i);
23424 // push value
23425 cvalues.push(vc);
23426 }
23427 }
23428 else {
23429 // push index
23430 cindex.push(i);
23431 }
23432 }
23433 }
23434 // update cptr
23435 cptr[columns] = cindex.length;
23436
23437 // return sparse matrix
23438 return c;
23439 };
23440
23441 return algorithm09;
23442}
23443
23444exports.name = 'algorithm09';
23445exports.factory = factory;
23446
23447
23448/***/ }),
23449/* 137 */
23450/***/ (function(module, exports, __webpack_require__) {
23451
23452"use strict";
23453
23454
23455var deepMap = __webpack_require__(1);
23456
23457function factory (type, config, load, typed) {
23458 var divideScalar = load(__webpack_require__(14));
23459
23460 /**
23461 * Calculate the logarithm of a value.
23462 *
23463 * For matrices, the function is evaluated element wise.
23464 *
23465 * Syntax:
23466 *
23467 * math.log(x)
23468 * math.log(x, base)
23469 *
23470 * Examples:
23471 *
23472 * math.log(3.5); // returns 1.252762968495368
23473 * math.exp(math.log(2.4)); // returns 2.4
23474 *
23475 * math.pow(10, 4); // returns 10000
23476 * math.log(10000, 10); // returns 4
23477 * math.log(10000) / math.log(10); // returns 4
23478 *
23479 * math.log(1024, 2); // returns 10
23480 * math.pow(2, 10); // returns 1024
23481 *
23482 * See also:
23483 *
23484 * exp, log10
23485 *
23486 * @param {number | BigNumber | Complex | Array | Matrix} x
23487 * Value for which to calculate the logarithm.
23488 * @param {number | BigNumber | Complex} [base=e]
23489 * Optional base for the logarithm. If not provided, the natural
23490 * logarithm of `x` is calculated.
23491 * @return {number | BigNumber | Complex | Array | Matrix}
23492 * Returns the logarithm of `x`
23493 */
23494 var log = typed('log', {
23495 'number': function (x) {
23496 if (x >= 0 || config.predictable) {
23497 return Math.log(x);
23498 }
23499 else {
23500 // negative value -> complex value computation
23501 return new type.Complex(x, 0).log();
23502 }
23503 },
23504
23505 'Complex': function (x) {
23506 return x.log();
23507 },
23508
23509 'BigNumber': function (x) {
23510 if (!x.isNegative() || config.predictable) {
23511 return x.ln();
23512 }
23513 else {
23514 // downgrade to number, return Complex valued result
23515 return new type.Complex(x.toNumber(), 0).log();
23516 }
23517 },
23518
23519 'Array | Matrix': function (x) {
23520 return deepMap(x, log);
23521 },
23522
23523 'any, any': function (x, base) {
23524 // calculate logarithm for a specified base, log(x, base)
23525 return divideScalar(log(x), log(base));
23526 }
23527 });
23528
23529 log.toTex = {
23530 1: '\\ln\\left(${args[0]}\\right)',
23531 2: '\\log_{${args[1]}}\\left(${args[0]}\\right)'
23532 };
23533
23534 return log;
23535}
23536
23537exports.name = 'log';
23538exports.factory = factory;
23539
23540
23541/***/ }),
23542/* 138 */
23543/***/ (function(module, exports, __webpack_require__) {
23544
23545"use strict";
23546
23547
23548var clone = __webpack_require__(5).clone;
23549var format = __webpack_require__(9).format;
23550
23551function factory (type, config, load, typed) {
23552
23553 var matrix = load(__webpack_require__(0));
23554 var add = load(__webpack_require__(20));
23555
23556 /**
23557 * Calculate the trace of a matrix: the sum of the elements on the main
23558 * diagonal of a square matrix.
23559 *
23560 * Syntax:
23561 *
23562 * math.trace(x)
23563 *
23564 * Examples:
23565 *
23566 * math.trace([[1, 2], [3, 4]]); // returns 5
23567 *
23568 * var A = [
23569 * [1, 2, 3],
23570 * [-1, 2, 3],
23571 * [2, 0, 3]
23572 * ]
23573 * math.trace(A); // returns 6
23574 *
23575 * See also:
23576 *
23577 * diag
23578 *
23579 * @param {Array | Matrix} x A matrix
23580 *
23581 * @return {number} The trace of `x`
23582 */
23583 var trace = typed('trace', {
23584
23585 'Array': function (x) {
23586 // use dense matrix implementation
23587 return trace(matrix(x));
23588 },
23589
23590 'Matrix': function (x) {
23591 // result
23592 var c;
23593 // process storage format
23594 switch (x.storage()) {
23595 case 'dense':
23596 c = _denseTrace(x);
23597 break;
23598 case 'sparse':
23599 c = _sparseTrace(x);
23600 break;
23601 }
23602 return c;
23603 },
23604
23605 'any': clone
23606 });
23607
23608 var _denseTrace = function (m) {
23609 // matrix size & data
23610 var size = m._size;
23611 var data = m._data;
23612
23613 // process dimensions
23614 switch (size.length) {
23615 case 1:
23616 // vector
23617 if (size[0] == 1) {
23618 // return data[0]
23619 return clone(data[0]);
23620 }
23621 throw new RangeError('Matrix must be square (size: ' + format(size) + ')');
23622 case 2:
23623 // two dimensional
23624 var rows = size[0];
23625 var cols = size[1];
23626 if (rows === cols) {
23627 // calulate sum
23628 var sum = 0;
23629 // loop diagonal
23630 for (var i = 0; i < rows; i++)
23631 sum = add(sum, data[i][i]);
23632 // return trace
23633 return sum;
23634 }
23635 throw new RangeError('Matrix must be square (size: ' + format(size) + ')');
23636 default:
23637 // multi dimensional
23638 throw new RangeError('Matrix must be two dimensional (size: ' + format(size) + ')');
23639 }
23640 };
23641
23642 var _sparseTrace = function (m) {
23643 // matrix arrays
23644 var values = m._values;
23645 var index = m._index;
23646 var ptr = m._ptr;
23647 var size = m._size;
23648 // check dimensions
23649 var rows = size[0];
23650 var columns = size[1];
23651 // matrix must be square
23652 if (rows === columns) {
23653 // calulate sum
23654 var sum = 0;
23655 // check we have data (avoid looping columns)
23656 if (values.length > 0) {
23657 // loop columns
23658 for (var j = 0; j < columns; j++) {
23659 // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
23660 var k0 = ptr[j];
23661 var k1 = ptr[j + 1];
23662 // loop k within [k0, k1[
23663 for (var k = k0; k < k1; k++) {
23664 // row index
23665 var i = index[k];
23666 // check row
23667 if (i === j) {
23668 // accumulate value
23669 sum = add(sum, values[k]);
23670 // exit loop
23671 break;
23672 }
23673 if (i > j) {
23674 // exit loop, no value on the diagonal for column j
23675 break;
23676 }
23677 }
23678 }
23679 }
23680 // return trace
23681 return sum;
23682 }
23683 throw new RangeError('Matrix must be square (size: ' + format(size) + ')');
23684 };
23685
23686 trace.toTex = {1: '\\mathrm{tr}\\left(${args[0]}\\right)'};
23687
23688 return trace;
23689}
23690
23691exports.name = 'trace';
23692exports.factory = factory;
23693
23694
23695/***/ }),
23696/* 139 */
23697/***/ (function(module, exports, __webpack_require__) {
23698
23699"use strict";
23700
23701
23702function factory (type, config, load, typed) {
23703 var add = load(__webpack_require__(20));
23704 var subtract = load(__webpack_require__(21));
23705 var multiply = load(__webpack_require__(12));
23706 var divide = load(__webpack_require__(49));
23707 var pow = load(__webpack_require__(46));
23708 var factorial = load(__webpack_require__(69));
23709 var combinations = load(__webpack_require__(70));
23710 var isNegative = load(__webpack_require__(58));
23711 var isInteger = load(__webpack_require__(51));
23712 var larger = load(__webpack_require__(34));
23713
23714 /**
23715 * The Stirling numbers of the second kind, counts the number of ways to partition
23716 * a set of n labelled objects into k nonempty unlabelled subsets.
23717 * stirlingS2 only takes integer arguments.
23718 * The following condition must be enforced: k <= n.
23719 *
23720 * If n = k or k = 1, then s(n,k) = 1
23721 *
23722 * Syntax:
23723 *
23724 * math.stirlingS2(n, k)
23725 *
23726 * Examples:
23727 *
23728 * math.stirlingS2(5, 3); //returns 25
23729 *
23730 * See also:
23731 *
23732 * Bell numbers
23733 *
23734 * @param {Number | BigNumber} n Total number of objects in the set
23735 * @param {Number | BigNumber} k Number of objects in the subset
23736 * @return {Number | BigNumber} S(n,k)
23737 */
23738 var stirlingS2 = typed('stirlingS2', {
23739 'number | BigNumber, number | BigNumber': function (n, k) {
23740 if (!isInteger(n) || isNegative(n) || !isInteger(k) || isNegative(k)) {
23741 throw new TypeError('Non-negative integer value expected in function stirlingS2');
23742 }
23743 else if (larger(k, n)) {
23744 throw new TypeError('k must be less than or equal to n in function stirlingS2');
23745 }
23746
23747 // 1/k! Sum(i=0 -> k) [(-1)^(k-i)*C(k,j)* i^n]
23748 var kFactorial = factorial(k);
23749 var result = 0;
23750 for(var i = 0; i <= k; i++) {
23751 var negativeOne = pow(-1, subtract(k,i));
23752 var kChooseI = combinations(k,i);
23753 var iPower = pow(i,n);
23754
23755 result = add(result, multiply(multiply(kChooseI, iPower), negativeOne));
23756 }
23757
23758 return divide(result, kFactorial);
23759 }
23760 });
23761
23762 stirlingS2.toTex = {2: '\\mathrm{S}\\left(${args}\\right)'};
23763
23764 return stirlingS2;
23765}
23766
23767exports.name = 'stirlingS2';
23768exports.factory = factory;
23769
23770
23771/***/ }),
23772/* 140 */
23773/***/ (function(module, exports, __webpack_require__) {
23774
23775"use strict";
23776
23777
23778var deepMap = __webpack_require__(1);
23779var isInteger = __webpack_require__(3).isInteger;
23780
23781function factory (type, config, load, typed) {
23782 var multiply = load(__webpack_require__(12));
23783 var pow = load(__webpack_require__(46));
23784
23785 /**
23786 * Compute the gamma function of a value using Lanczos approximation for
23787 * small values, and an extended Stirling approximation for large values.
23788 *
23789 * For matrices, the function is evaluated element wise.
23790 *
23791 * Syntax:
23792 *
23793 * math.gamma(n)
23794 *
23795 * Examples:
23796 *
23797 * math.gamma(5); // returns 24
23798 * math.gamma(-0.5); // returns -3.5449077018110335
23799 * math.gamma(math.i); // returns -0.15494982830180973 - 0.49801566811835596i
23800 *
23801 * See also:
23802 *
23803 * combinations, factorial, permutations
23804 *
23805 * @param {number | Array | Matrix} n A real or complex number
23806 * @return {number | Array | Matrix} The gamma of `n`
23807 */
23808 var gamma = typed('gamma', {
23809 'number': function (n) {
23810 var t, x;
23811
23812 if (isInteger(n)) {
23813 if (n <= 0) {
23814 return isFinite(n) ? Infinity : NaN;
23815 }
23816
23817 if (n > 171) {
23818 return Infinity; // Will overflow
23819 }
23820
23821 var value = n - 2;
23822 var res = n - 1;
23823 while (value > 1) {
23824 res *= value;
23825 value--;
23826 }
23827
23828 if (res == 0) {
23829 res = 1; // 0! is per definition 1
23830 }
23831
23832 return res;
23833 }
23834
23835 if (n < 0.5) {
23836 return Math.PI / (Math.sin(Math.PI * n) * gamma(1-n));
23837 }
23838
23839 if (n >= 171.35) {
23840 return Infinity; // will overflow
23841 }
23842
23843 if (n > 85.0) { // Extended Stirling Approx
23844 var twoN = n*n;
23845 var threeN = twoN*n;
23846 var fourN = threeN*n;
23847 var fiveN = fourN*n;
23848 return Math.sqrt(2*Math.PI/n) * Math.pow((n/Math.E), n) *
23849 (1 + 1/(12*n) + 1/(288*twoN) - 139/(51840*threeN) -
23850 571/(2488320*fourN) + 163879/(209018880*fiveN) +
23851 5246819/(75246796800*fiveN*n));
23852 }
23853
23854 --n;
23855 x = p[0];
23856 for (var i = 1; i < p.length; ++i) {
23857 x += p[i] / (n+i);
23858 }
23859
23860 t = n + g + 0.5;
23861 return Math.sqrt(2*Math.PI) * Math.pow(t, n+0.5) * Math.exp(-t) * x;
23862 },
23863
23864 'Complex': function (n) {
23865 var t, x;
23866
23867 if (n.im == 0) {
23868 return gamma(n.re);
23869 }
23870
23871 n = new type.Complex(n.re - 1, n.im);
23872 x = new type.Complex(p[0], 0);
23873 for (var i = 1; i < p.length; ++i) {
23874 var real = n.re + i; // x += p[i]/(n+i)
23875 var den = real*real + n.im*n.im;
23876 if (den != 0) {
23877 x.re += p[i] * real / den;
23878 x.im += -(p[i] * n.im) / den;
23879 } else {
23880 x.re = p[i] < 0
23881 ? -Infinity
23882 : Infinity;
23883 }
23884 }
23885
23886 t = new type.Complex(n.re + g + 0.5, n.im);
23887 var twoPiSqrt = Math.sqrt(2*Math.PI);
23888
23889 n.re += 0.5;
23890 var result = pow(t, n);
23891 if (result.im == 0) { // sqrt(2*PI)*result
23892 result.re *= twoPiSqrt;
23893 } else if (result.re == 0) {
23894 result.im *= twoPiSqrt;
23895 } else {
23896 result.re *= twoPiSqrt;
23897 result.im *= twoPiSqrt;
23898 }
23899
23900 var r = Math.exp(-t.re); // exp(-t)
23901 t.re = r * Math.cos(-t.im);
23902 t.im = r * Math.sin(-t.im);
23903
23904 return multiply(multiply(result, t), x);
23905 },
23906
23907 'BigNumber': function (n) {
23908 if (n.isInteger()) {
23909 return (n.isNegative() || n.isZero())
23910 ? new type.BigNumber(Infinity)
23911 : bigFactorial(n.minus(1));
23912 }
23913
23914 if (!n.isFinite()) {
23915 return new type.BigNumber(n.isNegative() ? NaN : Infinity);
23916 }
23917
23918 throw new Error('Integer BigNumber expected');
23919 },
23920
23921 'Array | Matrix': function (n) {
23922 return deepMap(n, gamma);
23923 }
23924 });
23925
23926 /**
23927 * Calculate factorial for a BigNumber
23928 * @param {BigNumber} n
23929 * @returns {BigNumber} Returns the factorial of n
23930 */
23931 function bigFactorial(n) {
23932 if (n.isZero()) {
23933 return new type.BigNumber(1); // 0! is per definition 1
23934 }
23935
23936 var precision = config.precision + (Math.log(n.toNumber()) | 0);
23937 var Big = type.BigNumber.clone({precision: precision});
23938
23939 var res = new Big(n);
23940 var value = n.toNumber() - 1; // number
23941 while (value > 1) {
23942 res = res.times(value);
23943 value--;
23944 }
23945
23946 return new type.BigNumber(res.toPrecision(type.BigNumber.precision));
23947 }
23948
23949 gamma.toTex = {1: '\\Gamma\\left(${args[0]}\\right)'};
23950
23951 return gamma;
23952}
23953
23954// TODO: comment on the variables g and p
23955
23956var g = 4.7421875;
23957
23958var p = [
23959 0.99999999999999709182,
23960 57.156235665862923517,
23961 -59.597960355475491248,
23962 14.136097974741747174,
23963 -0.49191381609762019978,
23964 0.33994649984811888699e-4,
23965 0.46523628927048575665e-4,
23966 -0.98374475304879564677e-4,
23967 0.15808870322491248884e-3,
23968 -0.21026444172410488319e-3,
23969 0.21743961811521264320e-3,
23970 -0.16431810653676389022e-3,
23971 0.84418223983852743293e-4,
23972 -0.26190838401581408670e-4,
23973 0.36899182659531622704e-5
23974];
23975
23976exports.name = 'gamma';
23977exports.factory = factory;
23978
23979
23980/***/ }),
23981/* 141 */
23982/***/ (function(module, exports, __webpack_require__) {
23983
23984"use strict";
23985
23986
23987var deepMap = __webpack_require__(1);
23988
23989function factory (type, config, load, typed) {
23990 var latex = __webpack_require__(4);
23991
23992 /**
23993 * Logical `not`. Flips boolean value of a given parameter.
23994 * For matrices, the function is evaluated element wise.
23995 *
23996 * Syntax:
23997 *
23998 * math.not(x)
23999 *
24000 * Examples:
24001 *
24002 * math.not(2); // returns false
24003 * math.not(0); // returns true
24004 * math.not(true); // returns false
24005 *
24006 * a = [2, -7, 0];
24007 * math.not(a); // returns [false, false, true]
24008 *
24009 * See also:
24010 *
24011 * and, or, xor
24012 *
24013 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check
24014 * @return {boolean | Array | Matrix}
24015 * Returns true when input is a zero or empty value.
24016 */
24017 var not = typed('not', {
24018 'number': function (x) {
24019 return !x;
24020 },
24021
24022 'Complex': function (x) {
24023 return x.re === 0 && x.im === 0;
24024 },
24025
24026 'BigNumber': function (x) {
24027 return x.isZero() || x.isNaN();
24028 },
24029
24030 'Unit': function (x) {
24031 return not(x.value);
24032 },
24033
24034 'Array | Matrix': function (x) {
24035 return deepMap(x, not);
24036 }
24037 });
24038
24039 not.toTex = {
24040 1: latex.operators['not'] + '\\left(${args[0]}\\right)'
24041 };
24042
24043 return not;
24044}
24045
24046exports.name = 'not';
24047exports.factory = factory;
24048
24049
24050/***/ }),
24051/* 142 */
24052/***/ (function(module, exports, __webpack_require__) {
24053
24054"use strict";
24055
24056
24057var maxArgumentCount = __webpack_require__(32).maxArgumentCount;
24058
24059function factory (type, config, load, typed) {
24060 /**
24061 * Create a new matrix or array with the results of the callback function executed on
24062 * each entry of the matrix/array.
24063 *
24064 * Syntax:
24065 *
24066 * math.map(x, callback)
24067 *
24068 * Examples:
24069 *
24070 * math.map([1, 2, 3], function(value) {
24071 * return value * value;
24072 * }); // returns [1, 4, 9]
24073 *
24074 * See also:
24075 *
24076 * filter, forEach, sort
24077 *
24078 * @param {Matrix | Array} x The matrix to iterate on.
24079 * @param {Function} callback The callback method is invoked with three
24080 * parameters: the value of the element, the index
24081 * of the element, and the matrix being traversed.
24082 * @return {Matrix | array} Transformed map of x
24083 */
24084 var map = typed('map', {
24085 'Array, function': _map,
24086
24087 'Matrix, function': function (x, callback) {
24088 return x.map(callback);
24089 }
24090 });
24091
24092 map.toTex = undefined; // use default template
24093
24094 return map;
24095}
24096
24097/**
24098 * Map for a multi dimensional array
24099 * @param {Array} array
24100 * @param {Function} callback
24101 * @return {Array}
24102 * @private
24103 */
24104function _map (array, callback) {
24105 // figure out what number of arguments the callback function expects
24106 var args = maxArgumentCount(callback);
24107
24108 var recurse = function (value, index) {
24109 if (Array.isArray(value)) {
24110 return value.map(function (child, i) {
24111 // we create a copy of the index array and append the new index value
24112 return recurse(child, index.concat(i));
24113 });
24114 }
24115 else {
24116 // invoke the callback function with the right number of arguments
24117 if (args === 1) {
24118 return callback(value);
24119 }
24120 else if (args === 2) {
24121 return callback(value, index);
24122 }
24123 else { // 3 or -1
24124 return callback(value, index, array);
24125 }
24126 }
24127 };
24128
24129 return recurse(array, []);
24130}
24131
24132exports.name = 'map';
24133exports.factory = factory;
24134
24135
24136/***/ }),
24137/* 143 */
24138/***/ (function(module, exports, __webpack_require__) {
24139
24140"use strict";
24141
24142
24143var size = __webpack_require__(2).size;
24144
24145function factory (type, config, load, typed) {
24146 var matrix = load(__webpack_require__(0));
24147 var compareAsc = load(__webpack_require__(52));
24148 var compareDesc = function (a, b) {
24149 return -compareAsc(a, b);
24150 };
24151 var compareNatural = load(__webpack_require__(31));
24152
24153 /**
24154 * Sort the items in a matrix.
24155 *
24156 * Syntax:
24157 *
24158 * math.sort(x)
24159 * math.sort(x, compare)
24160 *
24161 * Examples:
24162 *
24163 * math.sort([5, 10, 1]); // returns [1, 5, 10]
24164 * math.sort(['C', 'B', 'A', 'D']); // returns ['A', 'B', 'C', 'D']
24165 *
24166 * function sortByLength (a, b) {
24167 * return a.length - b.length;
24168 * }
24169 * math.sort(['Langdon', 'Tom', 'Sara'], sortByLength); // returns ['Tom', 'Sara', 'Langdon']
24170 *
24171 * See also:
24172 *
24173 * filter, forEach, map, compare, compareNatural
24174 *
24175 * @param {Matrix | Array} x A one dimensional matrix or array to sort
24176 * @param {Function | 'asc' | 'desc' | 'natural'} [compare='asc']
24177 * An optional _comparator function or name. The function is called as
24178 * `compare(a, b)`, and must return 1 when a > b, -1 when a < b,
24179 * and 0 when a == b.
24180 * @return {Matrix | Array} Returns the sorted matrix.
24181 */
24182 var sort = typed('sort', {
24183 'Array': function (x) {
24184 _arrayIsVector(x);
24185 return x.sort(compareAsc);
24186 },
24187
24188 'Matrix': function (x) {
24189 _matrixIsVector(x);
24190 return matrix(x.toArray().sort(compareAsc), x.storage());
24191 },
24192
24193 'Array, function': function (x, _comparator) {
24194 _arrayIsVector(x);
24195 return x.sort(_comparator);
24196 },
24197
24198 'Matrix, function': function (x, _comparator) {
24199 _matrixIsVector(x);
24200 return matrix(x.toArray().sort(_comparator), x.storage());
24201 },
24202
24203 'Array, string': function (x, order) {
24204 _arrayIsVector(x);
24205 return x.sort(_comparator(order));
24206 },
24207
24208 'Matrix, string': function (x, order) {
24209 _matrixIsVector(x);
24210 return matrix(x.toArray().sort(_comparator(order)), x.storage());
24211 }
24212 });
24213
24214 sort.toTex = undefined; // use default template
24215
24216 /**
24217 * Get the comparator for given order ('asc', 'desc', 'natural')
24218 * @param {'asc' | 'desc' | 'natural'} order
24219 * @return {Function} Returns a _comparator function
24220 */
24221 function _comparator (order) {
24222 if (order === 'asc') {
24223 return compareAsc;
24224 }
24225 else if (order === 'desc') {
24226 return compareDesc;
24227 }
24228 else if (order === 'natural') {
24229 return compareNatural;
24230 }
24231 else {
24232 throw new Error('String "asc", "desc", or "natural" expected');
24233 }
24234 }
24235
24236 /**
24237 * Validate whether an array is one dimensional
24238 * Throws an error when this is not the case
24239 * @param {Array} array
24240 * @private
24241 */
24242 function _arrayIsVector (array) {
24243 if (size(array).length !== 1) {
24244 throw new Error('One dimensional array expected');
24245 }
24246 }
24247
24248 /**
24249 * Validate whether a matrix is one dimensional
24250 * Throws an error when this is not the case
24251 * @param {Matrix} matrix
24252 * @private
24253 */
24254 function _matrixIsVector (matrix) {
24255 if (matrix.size().length !== 1) {
24256 throw new Error('One dimensional matrix expected');
24257 }
24258 }
24259
24260 return sort;
24261}
24262
24263exports.name = 'sort';
24264exports.factory = factory;
24265
24266
24267/***/ }),
24268/* 144 */
24269/***/ (function(module, exports, __webpack_require__) {
24270
24271"use strict";
24272
24273
24274var deepForEach = __webpack_require__(43);
24275
24276function factory (type, config, load, typed) {
24277 var add = load(__webpack_require__(16));
24278
24279 /**
24280 * Compute the sum of a matrix or a list with values.
24281 * In case of a (multi dimensional) array or matrix, the sum of all
24282 * elements will be calculated.
24283 *
24284 * Syntax:
24285 *
24286 * math.sum(a, b, c, ...)
24287 * math.sum(A)
24288 *
24289 * Examples:
24290 *
24291 * math.sum(2, 1, 4, 3); // returns 10
24292 * math.sum([2, 1, 4, 3]); // returns 10
24293 * math.sum([[2, 5], [4, 3], [1, 7]]); // returns 22
24294 *
24295 * See also:
24296 *
24297 * mean, median, min, max, prod, std, var
24298 *
24299 * @param {... *} args A single matrix or or multiple scalar values
24300 * @return {*} The sum of all values
24301 */
24302 var sum = typed('sum', {
24303 'Array | Matrix': function (args) {
24304 // sum([a, b, c, d, ...])
24305 return _sum(args);
24306 },
24307
24308 'Array | Matrix, number | BigNumber': function () {
24309 // sum([a, b, c, d, ...], dim)
24310 // TODO: implement sum(A, dim)
24311 throw new Error('sum(A, dim) is not yet supported');
24312 },
24313
24314 '...': function (args) {
24315 // sum(a, b, c, d, ...)
24316 return _sum(args);
24317 }
24318 });
24319
24320 sum.toTex = undefined; // use default template
24321
24322 return sum;
24323
24324 /**
24325 * Recursively calculate the sum of an n-dimensional array
24326 * @param {Array} array
24327 * @return {number} sum
24328 * @private
24329 */
24330 function _sum(array) {
24331 var sum = undefined;
24332
24333 deepForEach(array, function (value) {
24334 sum = (sum === undefined) ? value : add(sum, value);
24335 });
24336
24337 if (sum === undefined) {
24338 switch (config.number) {
24339 case 'number':
24340 return 0;
24341 case 'BigNumber':
24342 return new type.BigNumber(0);
24343 case 'Fraction':
24344 return new type.Fraction(0);
24345 default:
24346 return 0;
24347 }
24348 }
24349
24350 return sum;
24351 }
24352}
24353
24354exports.name = 'sum';
24355exports.factory = factory;
24356
24357
24358/***/ }),
24359/* 145 */
24360/***/ (function(module, exports, __webpack_require__) {
24361
24362"use strict";
24363
24364
24365var flatten = __webpack_require__(2).flatten;
24366var identify = __webpack_require__(2).identify;
24367var generalize = __webpack_require__(2).generalize;
24368
24369function factory (type, config, load, typed) {
24370 var equal = load(__webpack_require__(30));
24371 var index = load(__webpack_require__(27));
24372 var matrix = load(__webpack_require__(45));
24373 var size = load(__webpack_require__(29));
24374 var subset = load(__webpack_require__(23));
24375 var compareNatural = load(__webpack_require__(31));
24376
24377 /**
24378 * Create the difference of two (multi)sets: every element of set1, that is not the element of set2.
24379 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
24380 *
24381 * Syntax:
24382 *
24383 * math.setDifference(set1, set2)
24384 *
24385 * Examples:
24386 *
24387 * math.setDifference([1, 2, 3, 4], [3, 4, 5, 6]); // returns [1, 2]
24388 * math.setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]]); // returns [1, 2]
24389 *
24390 * See also:
24391 *
24392 * setUnion, setIntersect, setSymDifference
24393 *
24394 * @param {Array | Matrix} a1 A (multi)set
24395 * @param {Array | Matrix} a2 A (multi)set
24396 * @return {Array | Matrix} The difference of two (multi)sets
24397 */
24398 var setDifference = typed('setDifference', {
24399 'Array | Matrix, Array | Matrix': function (a1, a2) {
24400 if (subset(size(a1), new index(0)) === 0) { // empty-anything=empty
24401 var result = [];
24402 }
24403 else if (subset(size(a2), new index(0)) === 0) { // anything-empty=anything
24404 return flatten(a1.toArray());
24405 }
24406 else {
24407 var b1 = identify(flatten(Array.isArray(a1) ? a1: a1.toArray()).sort(compareNatural));
24408 var b2 = identify(flatten(Array.isArray(a2) ? a2: a2.toArray()).sort(compareNatural));
24409 var result = [];
24410 var inb2;
24411 for (var i=0; i<b1.length; i++) {
24412 inb2 = false;
24413 for (var j=0; j<b2.length; j++) {
24414 if (equal(b1[i].value, b2[j].value) && b1[i].identifier === b2[j].identifier) { // the identifier is always a decimal int
24415 inb2 = true;
24416 break;
24417 }
24418 }
24419 if (!inb2) {
24420 result.push(b1[i]);
24421 }
24422 }
24423 }
24424 // return an array, if both inputs were arrays
24425 if (Array.isArray(a1) && Array.isArray(a2)) {
24426 return generalize(result);
24427 }
24428 // return a matrix otherwise
24429 return new matrix(generalize(result));
24430 }
24431 });
24432
24433 return setDifference;
24434}
24435
24436exports.name = 'setDifference';
24437exports.factory = factory;
24438
24439
24440/***/ }),
24441/* 146 */
24442/***/ (function(module, exports, __webpack_require__) {
24443
24444"use strict";
24445
24446
24447var flatten = __webpack_require__(2).flatten;
24448var identify = __webpack_require__(2).identify;
24449var generalize = __webpack_require__(2).generalize;
24450
24451function factory (type, config, load, typed) {
24452 var equal = load(__webpack_require__(30));
24453 var index = load(__webpack_require__(27));
24454 var matrix = load(__webpack_require__(45));
24455 var size = load(__webpack_require__(29));
24456 var subset = load(__webpack_require__(23));
24457 var compareNatural = load(__webpack_require__(31));
24458
24459 /**
24460 * Create the intersection of two (multi)sets.
24461 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
24462 *
24463 * Syntax:
24464 *
24465 * math.setIntersect(set1, set2)
24466 *
24467 * Examples:
24468 *
24469 * math.setIntersect([1, 2, 3, 4], [3, 4, 5, 6]); // returns [3, 4]
24470 * math.setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]]); // returns [3, 4]
24471 *
24472 * See also:
24473 *
24474 * setUnion, setDifference
24475 *
24476 * @param {Array | Matrix} a1 A (multi)set
24477 * @param {Array | Matrix} a2 A (multi)set
24478 * @return {Array | Matrix} The intersection of two (multi)sets
24479 */
24480 var setIntersect = typed('setIntersect', {
24481 'Array | Matrix, Array | Matrix': function (a1, a2) {
24482 if (subset(size(a1), new index(0)) === 0 || subset(size(a2), new index(0)) === 0) { // of any of them is empty, return empty
24483 var result = [];
24484 }
24485 else {
24486 var b1 = identify(flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural));
24487 var b2 = identify(flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural));
24488 var result = [];
24489 for (var i=0; i<b1.length; i++) {
24490 for (var j=0; j<b2.length; j++) {
24491 if (equal(b1[i].value, b2[j].value) && b1[i].identifier === b2[j].identifier) { // the identifier is always a decimal int
24492 result.push(b1[i]);
24493 break;
24494 }
24495 }
24496 }
24497 }
24498 // return an array, if both inputs were arrays
24499 if (Array.isArray(a1) && Array.isArray(a2)) {
24500 return generalize(result);
24501 }
24502 // return a matrix otherwise
24503 return new matrix(generalize(result));
24504 }
24505 });
24506
24507 return setIntersect;
24508}
24509
24510exports.name = 'setIntersect';
24511exports.factory = factory;
24512
24513
24514/***/ }),
24515/* 147 */
24516/***/ (function(module, exports, __webpack_require__) {
24517
24518"use strict";
24519
24520
24521var flatten = __webpack_require__(2).flatten;
24522
24523function factory (type, config, load, typed) {
24524 var index = load(__webpack_require__(27));
24525 var concat = load(__webpack_require__(64));
24526 var size = load(__webpack_require__(29));
24527 var sort = load(__webpack_require__(143));
24528 var subset = load(__webpack_require__(23));
24529 var setDifference = load(__webpack_require__(145));
24530
24531 /**
24532 * Create the symmetric difference of two (multi)sets.
24533 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
24534 *
24535 * Syntax:
24536 *
24537 * math.setSymDifference(set1, set2)
24538 *
24539 * Examples:
24540 *
24541 * math.setSymDifference([1, 2, 3, 4], [3, 4, 5, 6]); // returns [1, 2, 5, 6]
24542 * math.setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]]); // returns [1, 2, 5, 6]
24543 *
24544 * See also:
24545 *
24546 * setUnion, setIntersect, setDifference
24547 *
24548 * @param {Array | Matrix} a1 A (multi)set
24549 * @param {Array | Matrix} a2 A (multi)set
24550 * @return {Array | Matrix} The symmetric difference of two (multi)sets
24551 */
24552 var setSymDifference = typed('setSymDifference', {
24553 'Array | Matrix, Array | Matrix': function (a1, a2) {
24554 if (subset(size(a1), new index(0)) === 0) { // if any of them is empty, return the other one
24555 return flatten(a2);
24556 }
24557 else if (subset(size(a2), new index(0)) === 0) {
24558 return flatten(a1);
24559 }
24560 var b1 = flatten(a1);
24561 var b2 = flatten(a2);
24562 return concat(setDifference(b1, b2), setDifference(b2, b1));
24563 }
24564 });
24565
24566 return setSymDifference;
24567}
24568
24569exports.name = 'setSymDifference';
24570exports.factory = factory;
24571
24572
24573/***/ }),
24574/* 148 */
24575/***/ (function(module, exports, __webpack_require__) {
24576
24577"use strict";
24578
24579
24580var flatten = __webpack_require__(2).flatten;
24581var reduce = __webpack_require__(65);
24582var containsCollections = __webpack_require__(66);
24583
24584function factory (type, config, load, typed) {
24585 var add = load(__webpack_require__(16));
24586 var divide = load(__webpack_require__(14));
24587 var compare = load(__webpack_require__(52));
24588 var partitionSelect = load(__webpack_require__(89));
24589
24590 /**
24591 * Compute the median of a matrix or a list with values. The values are
24592 * sorted and the middle value is returned. In case of an even number of
24593 * values, the average of the two middle values is returned.
24594 * Supported types of values are: Number, BigNumber, Unit
24595 *
24596 * In case of a (multi dimensional) array or matrix, the median of all
24597 * elements will be calculated.
24598 *
24599 * Syntax:
24600 *
24601 * math.median(a, b, c, ...)
24602 * math.median(A)
24603 *
24604 * Examples:
24605 *
24606 * math.median(5, 2, 7); // returns 5
24607 * math.median([3, -1, 5, 7]); // returns 4
24608 *
24609 * See also:
24610 *
24611 * mean, min, max, sum, prod, std, var, quantileSeq
24612 *
24613 * @param {... *} args A single matrix or or multiple scalar values
24614 * @return {*} The median
24615 */
24616 var median = typed('median', {
24617 // median([a, b, c, d, ...])
24618 'Array | Matrix': _median,
24619
24620 // median([a, b, c, d, ...], dim)
24621 'Array | Matrix, number | BigNumber': function (array, dim) {
24622 // TODO: implement median(A, dim)
24623 throw new Error('median(A, dim) is not yet supported');
24624 //return reduce(arguments[0], arguments[1], ...);
24625 },
24626
24627 // median(a, b, c, d, ...)
24628 '...': function (args) {
24629 if (containsCollections(args)) {
24630 throw new TypeError('Scalar values expected in function median');
24631 }
24632
24633 return _median(args);
24634 }
24635 });
24636
24637
24638 /**
24639 * Recursively calculate the median of an n-dimensional array
24640 * @param {Array} array
24641 * @return {Number} median
24642 * @private
24643 */
24644 function _median(array) {
24645 array = flatten(array.valueOf());
24646
24647 var num = array.length;
24648 if (num == 0) {
24649 throw new Error('Cannot calculate median of an empty array');
24650 }
24651
24652 if (num % 2 == 0) {
24653 // even: return the average of the two middle values
24654 var mid = num / 2 - 1;
24655 var right = partitionSelect(array, mid + 1);
24656
24657 // array now partitioned at mid + 1, take max of left part
24658 var left = array[mid];
24659 for (var i = 0; i < mid; ++i) {
24660 if (compare(array[i], left) > 0) {
24661 left = array[i];
24662 }
24663 }
24664
24665 return middle2(left, right);
24666 }
24667 else {
24668 // odd: return the middle value
24669 var m = partitionSelect(array, (num - 1) / 2);
24670
24671 return middle(m);
24672 }
24673 }
24674
24675 // helper function to type check the middle value of the array
24676 var middle = typed({
24677 'number | BigNumber | Complex | Unit': function (value) {
24678 return value;
24679 }
24680 });
24681
24682 // helper function to type check the two middle value of the array
24683 var middle2 = typed({
24684 'number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit': function (left, right) {
24685 return divide(add(left, right), 2);
24686 }
24687 });
24688
24689 median.toTex = undefined; // use default template
24690
24691 return median;
24692}
24693
24694exports.name = 'median';
24695exports.factory = factory;
24696
24697
24698/***/ }),
24699/* 149 */
24700/***/ (function(module, exports, __webpack_require__) {
24701
24702"use strict";
24703
24704
24705var DEFAULT_NORMALIZATION = 'unbiased';
24706
24707var deepForEach = __webpack_require__(43);
24708
24709function factory (type, config, load, typed) {
24710 var add = load(__webpack_require__(16));
24711 var subtract = load(__webpack_require__(21));
24712 var multiply = load(__webpack_require__(22));
24713 var divide = load(__webpack_require__(14));
24714
24715 /**
24716 * Compute the variance of a matrix or a list with values.
24717 * In case of a (multi dimensional) array or matrix, the variance over all
24718 * elements will be calculated.
24719 *
24720 * Optionally, the type of normalization can be specified as second
24721 * parameter. The parameter `normalization` can be one of the following values:
24722 *
24723 * - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
24724 * - 'uncorrected' The sum of squared errors is divided by n
24725 * - 'biased' The sum of squared errors is divided by (n + 1)
24726 *
24727 * Note that older browser may not like the variable name `var`. In that
24728 * case, the function can be called as `math['var'](...)` instead of
24729 * `math.var(...)`.
24730 *
24731 * Syntax:
24732 *
24733 * math.var(a, b, c, ...)
24734 * math.var(A)
24735 * math.var(A, normalization)
24736 *
24737 * Examples:
24738 *
24739 * math.var(2, 4, 6); // returns 4
24740 * math.var([2, 4, 6, 8]); // returns 6.666666666666667
24741 * math.var([2, 4, 6, 8], 'uncorrected'); // returns 5
24742 * math.var([2, 4, 6, 8], 'biased'); // returns 4
24743 *
24744 * math.var([[1, 2, 3], [4, 5, 6]]); // returns 3.5
24745 *
24746 * See also:
24747 *
24748 * mean, median, max, min, prod, std, sum
24749 *
24750 * @param {Array | Matrix} array
24751 * A single matrix or or multiple scalar values
24752 * @param {string} [normalization='unbiased']
24753 * Determines how to normalize the variance.
24754 * Choose 'unbiased' (default), 'uncorrected', or 'biased'.
24755 * @return {*} The variance
24756 */
24757 var variance = typed('variance', {
24758 // var([a, b, c, d, ...])
24759 'Array | Matrix': function (array) {
24760 return _var(array, DEFAULT_NORMALIZATION);
24761 },
24762
24763 // var([a, b, c, d, ...], normalization)
24764 'Array | Matrix, string': _var,
24765
24766 // var(a, b, c, d, ...)
24767 '...': function (args) {
24768 return _var(args, DEFAULT_NORMALIZATION);
24769 }
24770 });
24771
24772 variance.toTex = '\\mathrm{Var}\\left(${args}\\right)';
24773
24774 return variance;
24775
24776 /**
24777 * Recursively calculate the variance of an n-dimensional array
24778 * @param {Array} array
24779 * @param {string} normalization
24780 * Determines how to normalize the variance:
24781 * - 'unbiased' The sum of squared errors is divided by (n - 1)
24782 * - 'uncorrected' The sum of squared errors is divided by n
24783 * - 'biased' The sum of squared errors is divided by (n + 1)
24784 * @return {number | BigNumber} variance
24785 * @private
24786 */
24787 function _var(array, normalization) {
24788 var sum = 0;
24789 var num = 0;
24790
24791 if (array.length == 0) {
24792 throw new SyntaxError('Function var requires one or more parameters (0 provided)');
24793 }
24794
24795 // calculate the mean and number of elements
24796 deepForEach(array, function (value) {
24797 sum = add(sum, value);
24798 num++;
24799 });
24800 if (num === 0) throw new Error('Cannot calculate var of an empty array');
24801
24802 var mean = divide(sum, num);
24803
24804 // calculate the variance
24805 sum = 0;
24806 deepForEach(array, function (value) {
24807 var diff = subtract(value, mean);
24808 sum = add(sum, multiply(diff, diff));
24809 });
24810
24811 switch (normalization) {
24812 case 'uncorrected':
24813 return divide(sum, num);
24814
24815 case 'biased':
24816 return divide(sum, num + 1);
24817
24818 case 'unbiased':
24819 var zero = type.isBigNumber(sum) ? new type.BigNumber(0) : 0;
24820 return (num == 1) ? zero : divide(sum, num - 1);
24821
24822 default:
24823 throw new Error('Unknown normalization "' + normalization + '". ' +
24824 'Choose "unbiased" (default), "uncorrected", or "biased".');
24825 }
24826 }
24827}
24828
24829exports.name = 'var';
24830exports.factory = factory;
24831
24832
24833/***/ }),
24834/* 150 */
24835/***/ (function(module, exports, __webpack_require__) {
24836
24837"use strict";
24838
24839
24840var deepMap = __webpack_require__(1);
24841
24842function factory (type, config, load, typed) {
24843
24844 /**
24845 * Calculate the hyperbolic arccos of a value,
24846 * defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.
24847 *
24848 * For matrices, the function is evaluated element wise.
24849 *
24850 * Syntax:
24851 *
24852 * math.acosh(x)
24853 *
24854 * Examples:
24855 *
24856 * math.acosh(1.5); // returns 0.9624236501192069
24857 *
24858 * See also:
24859 *
24860 * cosh, asinh, atanh
24861 *
24862 * @param {number | Complex | Unit | Array | Matrix} x Function input
24863 * @return {number | Complex | Array | Matrix} Hyperbolic arccosine of x
24864 */
24865 var acosh = typed('acosh', {
24866 'number': function (x) {
24867 if (x >= 1 || config.predictable) {
24868 return _acosh(x);
24869 }
24870 if (x <= -1) {
24871 return new type.Complex(Math.log(Math.sqrt(x*x - 1) - x), Math.PI);
24872 }
24873 return new type.Complex(x, 0).acosh();
24874 },
24875
24876 'Complex': function (x) {
24877 return x.acosh();
24878 },
24879
24880 'BigNumber': function (x) {
24881 return x.acosh();
24882 },
24883
24884 'Array | Matrix': function (x) {
24885 return deepMap(x, acosh);
24886 }
24887 });
24888
24889 acosh.toTex = {1: '\\cosh^{-1}\\left(${args[0]}\\right)'};
24890
24891 return acosh;
24892}
24893
24894/**
24895 * Calculate the hyperbolic arccos of a number
24896 * @param {number} x
24897 * @return {number}
24898 * @private
24899 */
24900var _acosh = Math.acosh || function (x) {
24901 return Math.log(Math.sqrt(x*x - 1) + x)
24902};
24903
24904exports.name = 'acosh';
24905exports.factory = factory;
24906
24907
24908/***/ }),
24909/* 151 */
24910/***/ (function(module, exports, __webpack_require__) {
24911
24912var core = __webpack_require__(152);
24913
24914/**
24915 * math.js factory function. Creates a new instance of math.js
24916 *
24917 * @param {Object} [config] Available configuration options:
24918 * {number} epsilon
24919 * Minimum relative difference between two
24920 * compared values, used by all comparison functions.
24921 * {string} matrix
24922 * A string 'matrix' (default) or 'array'.
24923 * {string} number
24924 * A string 'number' (default), 'bignumber', or
24925 * 'fraction'
24926 * {number} precision
24927 * The number of significant digits for BigNumbers.
24928 * Not applicable for Numbers.
24929 * {boolean} predictable
24930 * Predictable output type of functions. When true,
24931 * output type depends only on the input types. When
24932 * false (default), output type can vary depending
24933 * on input values. For example `math.sqrt(-4)`
24934 * returns `complex('2i')` when predictable is false, and
24935 * returns `NaN` when true.
24936 */
24937function create (config) {
24938 // create a new math.js instance
24939 var math = core.create(config);
24940 math.create = create;
24941
24942 // import data types, functions, constants, expression parser, etc.
24943 math['import'](__webpack_require__(159));
24944
24945 return math;
24946}
24947
24948// return a new instance of math.js
24949module.exports = create();
24950
24951
24952/***/ }),
24953/* 152 */
24954/***/ (function(module, exports, __webpack_require__) {
24955
24956module.exports = __webpack_require__(153);
24957
24958/***/ }),
24959/* 153 */
24960/***/ (function(module, exports, __webpack_require__) {
24961
24962var isFactory = __webpack_require__(5).isFactory;
24963var typedFactory = __webpack_require__(154);
24964var emitter = __webpack_require__(91);
24965
24966var importFactory = __webpack_require__(157);
24967var configFactory = __webpack_require__(158);
24968
24969/**
24970 * Math.js core. Creates a new, empty math.js instance
24971 * @param {Object} [options] Available options:
24972 * {number} epsilon
24973 * Minimum relative difference between two
24974 * compared values, used by all comparison functions.
24975 * {string} matrix
24976 * A string 'Matrix' (default) or 'Array'.
24977 * {string} number
24978 * A string 'number' (default), 'BigNumber', or 'Fraction'
24979 * {number} precision
24980 * The number of significant digits for BigNumbers.
24981 * Not applicable for Numbers.
24982 * {boolean} predictable
24983 * Predictable output type of functions. When true,
24984 * output type depends only on the input types. When
24985 * false (default), output type can vary depending
24986 * on input values. For example `math.sqrt(-4)`
24987 * returns `complex('2i')` when predictable is false, and
24988 * returns `NaN` when true.
24989 * {string} randomSeed
24990 * Random seed for seeded pseudo random number generator.
24991 * Set to null to randomly seed.
24992 * @returns {Object} Returns a bare-bone math.js instance containing
24993 * functions:
24994 * - `import` to add new functions
24995 * - `config` to change configuration
24996 * - `on`, `off`, `once`, `emit` for events
24997 */
24998exports.create = function create (options) {
24999 // simple test for ES5 support
25000 if (typeof Object.create !== 'function') {
25001 throw new Error('ES5 not supported by this JavaScript engine. ' +
25002 'Please load the es5-shim and es5-sham library for compatibility.');
25003 }
25004
25005 // cached factories and instances
25006 var factories = [];
25007 var instances = [];
25008
25009 // create a namespace for the mathjs instance, and attach emitter functions
25010 var math = emitter.mixin({});
25011 math.type = {};
25012 math.expression = {
25013 transform: {},
25014 mathWithTransform: {}
25015 };
25016
25017 // create a new typed instance
25018 math.typed = typedFactory.create(math.type);
25019
25020 // create configuration options. These are private
25021 var _config = {
25022 // minimum relative difference between two compared values,
25023 // used by all comparison functions
25024 epsilon: 1e-12,
25025
25026 // type of default matrix output. Choose 'matrix' (default) or 'array'
25027 matrix: 'Matrix',
25028
25029 // type of default number output. Choose 'number' (default) 'BigNumber', or 'Fraction
25030 number: 'number',
25031
25032 // number of significant digits in BigNumbers
25033 precision: 64,
25034
25035 // predictable output type of functions. When true, output type depends only
25036 // on the input types. When false (default), output type can vary depending
25037 // on input values. For example `math.sqrt(-4)` returns `complex('2i')` when
25038 // predictable is false, and returns `NaN` when true.
25039 predictable: false,
25040
25041 // random seed for seeded pseudo random number generation
25042 // null = randomly seed
25043 randomSeed: null
25044 };
25045
25046 /**
25047 * Load a function or data type from a factory.
25048 * If the function or data type already exists, the existing instance is
25049 * returned.
25050 * @param {{type: string, name: string, factory: Function}} factory
25051 * @returns {*}
25052 */
25053 function load (factory) {
25054 if (!isFactory(factory)) {
25055 throw new Error('Factory object with properties `type`, `name`, and `factory` expected');
25056 }
25057
25058 var index = factories.indexOf(factory);
25059 var instance;
25060 if (index === -1) {
25061 // doesn't yet exist
25062 if (factory.math === true) {
25063 // pass with math namespace
25064 instance = factory.factory(math.type, _config, load, math.typed, math);
25065 }
25066 else {
25067 instance = factory.factory(math.type, _config, load, math.typed);
25068 }
25069
25070 // append to the cache
25071 factories.push(factory);
25072 instances.push(instance);
25073 }
25074 else {
25075 // already existing function, return the cached instance
25076 instance = instances[index];
25077 }
25078
25079 return instance;
25080 }
25081
25082 // load the import and config functions
25083 math['import'] = load(importFactory);
25084 math['config'] = load(configFactory);
25085 math.expression.mathWithTransform['config'] = math['config']
25086
25087 // apply options
25088 if (options) {
25089 math.config(options);
25090 }
25091
25092 return math;
25093};
25094
25095
25096/***/ }),
25097/* 154 */
25098/***/ (function(module, exports, __webpack_require__) {
25099
25100var typedFunction = __webpack_require__(155);
25101var digits = __webpack_require__(3).digits;
25102var isBigNumber = __webpack_require__(71);
25103var isMatrix = __webpack_require__(59);
25104
25105// returns a new instance of typed-function
25106var createTyped = function () {
25107 // initially, return the original instance of typed-function
25108 // consecutively, return a new instance from typed.create.
25109 createTyped = typedFunction.create;
25110 return typedFunction;
25111};
25112
25113/**
25114 * Factory function for creating a new typed instance
25115 * @param {Object} type Object with data types like Complex and BigNumber
25116 * @returns {Function}
25117 */
25118exports.create = function create(type) {
25119 // TODO: typed-function must be able to silently ignore signatures with unknown data types
25120
25121 // type checks for all known types
25122 //
25123 // note that:
25124 //
25125 // - check by duck-typing on a property like `isUnit`, instead of checking instanceof.
25126 // instanceof cannot be used because that would not allow to pass data from
25127 // one instance of math.js to another since each has it's own instance of Unit.
25128 // - check the `isUnit` property via the constructor, so there will be no
25129 // matches for "fake" instances like plain objects with a property `isUnit`.
25130 // That is important for security reasons.
25131 // - It must not be possible to override the type checks used internally,
25132 // for security reasons, so these functions are not exposed in the expression
25133 // parser.
25134 type.isNumber = function (x) { return typeof x === 'number' };
25135 type.isComplex = function (x) { return type.Complex && x instanceof type.Complex || false };
25136 type.isBigNumber = isBigNumber;
25137 type.isFraction = function (x) { return type.Fraction && x instanceof type.Fraction || false };
25138 type.isUnit = function (x) { return x && x.constructor.prototype.isUnit || false };
25139 type.isString = function (x) { return typeof x === 'string' };
25140 type.isArray = Array.isArray;
25141 type.isMatrix = isMatrix;
25142 type.isDenseMatrix = function (x) { return x && x.isDenseMatrix && x.constructor.prototype.isMatrix || false };
25143 type.isSparseMatrix = function (x) { return x && x.isSparseMatrix && x.constructor.prototype.isMatrix || false };
25144 type.isRange = function (x) { return x && x.constructor.prototype.isRange || false };
25145 type.isIndex = function (x) { return x && x.constructor.prototype.isIndex || false };
25146 type.isBoolean = function (x) { return typeof x === 'boolean' };
25147 type.isResultSet = function (x) { return x && x.constructor.prototype.isResultSet || false };
25148 type.isHelp = function (x) { return x && x.constructor.prototype.isHelp || false };
25149 type.isFunction = function (x) { return typeof x === 'function'};
25150 type.isDate = function (x) { return x instanceof Date };
25151 type.isRegExp = function (x) { return x instanceof RegExp };
25152 type.isObject = function (x) { return typeof x === 'object' };
25153 type.isNull = function (x) { return x === null };
25154 type.isUndefined = function (x) { return x === undefined };
25155
25156 type.isAccessorNode = function (x) { return x && x.isAccessorNode && x.constructor.prototype.isNode || false };
25157 type.isArrayNode = function (x) { return x && x.isArrayNode && x.constructor.prototype.isNode || false };
25158 type.isAssignmentNode = function (x) { return x && x.isAssignmentNode && x.constructor.prototype.isNode || false };
25159 type.isBlockNode = function (x) { return x && x.isBlockNode && x.constructor.prototype.isNode || false };
25160 type.isConditionalNode = function (x) { return x && x.isConditionalNode && x.constructor.prototype.isNode || false };
25161 type.isConstantNode = function (x) { return x && x.isConstantNode && x.constructor.prototype.isNode || false };
25162 type.isFunctionAssignmentNode = function (x) { return x && x.isFunctionAssignmentNode && x.constructor.prototype.isNode || false };
25163 type.isFunctionNode = function (x) { return x && x.isFunctionNode && x.constructor.prototype.isNode || false };
25164 type.isIndexNode = function (x) { return x && x.isIndexNode && x.constructor.prototype.isNode || false };
25165 type.isNode = function (x) { return x && x.isNode && x.constructor.prototype.isNode || false };
25166 type.isObjectNode = function (x) { return x && x.isObjectNode && x.constructor.prototype.isNode || false };
25167 type.isOperatorNode = function (x) { return x && x.isOperatorNode && x.constructor.prototype.isNode || false };
25168 type.isParenthesisNode = function (x) { return x && x.isParenthesisNode && x.constructor.prototype.isNode || false };
25169 type.isRangeNode = function (x) { return x && x.isRangeNode && x.constructor.prototype.isNode || false };
25170 type.isSymbolNode = function (x) { return x && x.isSymbolNode && x.constructor.prototype.isNode || false };
25171
25172 type.isChain = function (x) { return x && x.constructor.prototype.isChain || false };
25173
25174 // get a new instance of typed-function
25175 var typed = createTyped();
25176
25177 // define all types. The order of the types determines in which order function
25178 // arguments are type-checked (so for performance it's important to put the
25179 // most used types first).
25180 typed.types = [
25181 { name: 'number', test: type.isNumber },
25182 { name: 'Complex', test: type.isComplex },
25183 { name: 'BigNumber', test: type.isBigNumber },
25184 { name: 'Fraction', test: type.isFraction },
25185 { name: 'Unit', test: type.isUnit },
25186 { name: 'string', test: type.isString },
25187 { name: 'Array', test: type.isArray },
25188 { name: 'Matrix', test: type.isMatrix },
25189 { name: 'DenseMatrix', test: type.isDenseMatrix },
25190 { name: 'SparseMatrix', test: type.isSparseMatrix },
25191 { name: 'Range', test: type.isRange },
25192 { name: 'Index', test: type.isIndex },
25193 { name: 'boolean', test: type.isBoolean },
25194 { name: 'ResultSet', test: type.isResultSet },
25195 { name: 'Help', test: type.isHelp },
25196 { name: 'function', test: type.isFunction },
25197 { name: 'Date', test: type.isDate },
25198 { name: 'RegExp', test: type.isRegExp },
25199 { name: 'Object', test: type.isObject },
25200 { name: 'null', test: type.isNull },
25201 { name: 'undefined', test: type.isUndefined },
25202
25203 { name: 'OperatorNode', test: type.isOperatorNode },
25204 { name: 'ConstantNode', test: type.isConstantNode },
25205 { name: 'SymbolNode', test: type.isSymbolNode },
25206 { name: 'ParenthesisNode', test: type.isParenthesisNode },
25207 { name: 'FunctionNode', test: type.isFunctionNode },
25208 { name: 'FunctionAssignmentNode', test: type.isFunctionAssignmentNode },
25209 { name: 'ArrayNode', test: type.isArrayNode },
25210 { name: 'AssignmentNode', test: type.isAssignmentNode },
25211 { name: 'BlockNode', test: type.isBlockNode },
25212 { name: 'ConditionalNode', test: type.isConditionalNode },
25213 { name: 'IndexNode', test: type.isIndexNode },
25214 { name: 'RangeNode', test: type.isRangeNode },
25215 { name: 'Node', test: type.isNode }
25216 ];
25217
25218 // TODO: add conversion from BigNumber to number?
25219 typed.conversions = [
25220 {
25221 from: 'number',
25222 to: 'BigNumber',
25223 convert: function (x) {
25224 // note: conversion from number to BigNumber can fail if x has >15 digits
25225 if (digits(x) > 15) {
25226 throw new TypeError('Cannot implicitly convert a number with >15 significant digits to BigNumber ' +
25227 '(value: ' + x + '). ' +
25228 'Use function bignumber(x) to convert to BigNumber.');
25229 }
25230 return new type.BigNumber(x);
25231 }
25232 }, {
25233 from: 'number',
25234 to: 'Complex',
25235 convert: function (x) {
25236 return new type.Complex(x, 0);
25237 }
25238 }, {
25239 from: 'number',
25240 to: 'string',
25241 convert: function (x) {
25242 return x + '';
25243 }
25244 }, {
25245 from: 'BigNumber',
25246 to: 'Complex',
25247 convert: function (x) {
25248 return new type.Complex(x.toNumber(), 0);
25249 }
25250 }, {
25251 from: 'Fraction',
25252 to: 'BigNumber',
25253 convert: function (x) {
25254 throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
25255 'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
25256 }
25257 }, {
25258 from: 'Fraction',
25259 to: 'Complex',
25260 convert: function (x) {
25261 return new type.Complex(x.valueOf(), 0);
25262 }
25263 }, {
25264 from: 'number',
25265 to: 'Fraction',
25266 convert: function (x) {
25267 var f = new type.Fraction(x);
25268 if (f.valueOf() !== x) {
25269 throw new TypeError('Cannot implicitly convert a number to a Fraction when there will be a loss of precision ' +
25270 '(value: ' + x + '). ' +
25271 'Use function fraction(x) to convert to Fraction.');
25272 }
25273 return new type.Fraction(x);
25274 }
25275 }, {
25276 // FIXME: add conversion from Fraction to number, for example for `sqrt(fraction(1,3))`
25277 // from: 'Fraction',
25278 // to: 'number',
25279 // convert: function (x) {
25280 // return x.valueOf();
25281 // }
25282 //}, {
25283 from: 'string',
25284 to: 'number',
25285 convert: function (x) {
25286 var n = Number(x);
25287 if (isNaN(n)) {
25288 throw new Error('Cannot convert "' + x + '" to a number');
25289 }
25290 return n;
25291 }
25292 }, {
25293 from: 'string',
25294 to: 'BigNumber',
25295 convert: function (x) {
25296 try {
25297 return new type.BigNumber(x);
25298 }
25299 catch (err) {
25300 throw new Error('Cannot convert "' + x + '" to BigNumber');
25301 }
25302 }
25303 }, {
25304 from: 'string',
25305 to: 'Fraction',
25306 convert: function (x) {
25307 try {
25308 return new type.Fraction(x);
25309 }
25310 catch (err) {
25311 throw new Error('Cannot convert "' + x + '" to Fraction');
25312 }
25313 }
25314 }, {
25315 from: 'string',
25316 to: 'Complex',
25317 convert: function (x) {
25318 try {
25319 return new type.Complex(x);
25320 }
25321 catch (err) {
25322 throw new Error('Cannot convert "' + x + '" to Complex');
25323 }
25324 }
25325 }, {
25326 from: 'boolean',
25327 to: 'number',
25328 convert: function (x) {
25329 return +x;
25330 }
25331 }, {
25332 from: 'boolean',
25333 to: 'BigNumber',
25334 convert: function (x) {
25335 return new type.BigNumber(+x);
25336 }
25337 }, {
25338 from: 'boolean',
25339 to: 'Fraction',
25340 convert: function (x) {
25341 return new type.Fraction(+x);
25342 }
25343 }, {
25344 from: 'boolean',
25345 to: 'string',
25346 convert: function (x) {
25347 return +x;
25348 }
25349 }, {
25350 from: 'null',
25351 to: 'number',
25352 convert: function () {
25353 return 0;
25354 }
25355 }, {
25356 from: 'null',
25357 to: 'string',
25358 convert: function () {
25359 return 'null';
25360 }
25361 }, {
25362 from: 'null',
25363 to: 'BigNumber',
25364 convert: function () {
25365 return new type.BigNumber(0);
25366 }
25367 }, {
25368 from: 'null',
25369 to: 'Fraction',
25370 convert: function () {
25371 return new type.Fraction(0);
25372 }
25373 }, {
25374 from: 'Array',
25375 to: 'Matrix',
25376 convert: function (array) {
25377 // TODO: how to decide on the right type of matrix to create?
25378 return new type.DenseMatrix(array);
25379 }
25380 }, {
25381 from: 'Matrix',
25382 to: 'Array',
25383 convert: function (matrix) {
25384 return matrix.valueOf();
25385 }
25386 }
25387 ];
25388
25389 return typed;
25390};
25391
25392
25393/***/ }),
25394/* 155 */
25395/***/ (function(module, exports, __webpack_require__) {
25396
25397"use strict";
25398var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
25399 * typed-function
25400 *
25401 * Type checking for JavaScript functions
25402 *
25403 * https://github.com/josdejong/typed-function
25404 */
25405
25406
25407(function (root, factory) {
25408 if (true) {
25409 // AMD. Register as an anonymous module.
25410 !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
25411 __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
25412 (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
25413 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
25414 } else if (typeof exports === 'object') {
25415 // OldNode. Does not work with strict CommonJS, but
25416 // only CommonJS-like environments that support module.exports,
25417 // like OldNode.
25418 module.exports = factory();
25419 } else {
25420 // Browser globals (root is window)
25421 root.typed = factory();
25422 }
25423}(this, function () {
25424 // factory function to create a new instance of typed-function
25425 // TODO: allow passing configuration, types, tests via the factory function
25426 function create() {
25427 /**
25428 * Get a type test function for a specific data type
25429 * @param {string} name Name of a data type like 'number' or 'string'
25430 * @returns {Function(obj: *) : boolean} Returns a type testing function.
25431 * Throws an error for an unknown type.
25432 */
25433 function getTypeTest(name) {
25434 var test;
25435 for (var i = 0; i < typed.types.length; i++) {
25436 var entry = typed.types[i];
25437 if (entry.name === name) {
25438 test = entry.test;
25439 break;
25440 }
25441 }
25442
25443 if (!test) {
25444 var hint;
25445 for (i = 0; i < typed.types.length; i++) {
25446 entry = typed.types[i];
25447 if (entry.name.toLowerCase() == name.toLowerCase()) {
25448 hint = entry.name;
25449 break;
25450 }
25451 }
25452
25453 throw new Error('Unknown type "' + name + '"' +
25454 (hint ? ('. Did you mean "' + hint + '"?') : ''));
25455 }
25456 return test;
25457 }
25458
25459 /**
25460 * Retrieve the function name from a set of functions, and check
25461 * whether the name of all functions match (if given)
25462 * @param {Array.<function>} fns
25463 */
25464 function getName (fns) {
25465 var name = '';
25466
25467 for (var i = 0; i < fns.length; i++) {
25468 var fn = fns[i];
25469
25470 // merge function name when this is a typed function
25471 if (fn.signatures && fn.name != '') {
25472 if (name == '') {
25473 name = fn.name;
25474 }
25475 else if (name != fn.name) {
25476 var err = new Error('Function names do not match (expected: ' + name + ', actual: ' + fn.name + ')');
25477 err.data = {
25478 actual: fn.name,
25479 expected: name
25480 };
25481 throw err;
25482 }
25483 }
25484 }
25485
25486 return name;
25487 }
25488
25489 /**
25490 * Create an ArgumentsError. Creates messages like:
25491 *
25492 * Unexpected type of argument (expected: ..., actual: ..., index: ...)
25493 * Too few arguments (expected: ..., index: ...)
25494 * Too many arguments (expected: ..., actual: ...)
25495 *
25496 * @param {String} fn Function name
25497 * @param {number} argCount Number of arguments
25498 * @param {Number} index Current argument index
25499 * @param {*} actual Current argument
25500 * @param {string} [expected] An optional, comma separated string with
25501 * expected types on given index
25502 * @extends Error
25503 */
25504 function createError(fn, argCount, index, actual, expected) {
25505 var actualType = getTypeOf(actual);
25506 var _expected = expected ? expected.split(',') : null;
25507 var _fn = (fn || 'unnamed');
25508 var anyType = _expected && contains(_expected, 'any');
25509 var message;
25510 var data = {
25511 fn: fn,
25512 index: index,
25513 actual: actualType,
25514 expected: _expected
25515 };
25516
25517 if (_expected) {
25518 if (argCount > index && !anyType) {
25519 // unexpected type
25520 message = 'Unexpected type of argument in function ' + _fn +
25521 ' (expected: ' + _expected.join(' or ') + ', actual: ' + actualType + ', index: ' + index + ')';
25522 }
25523 else {
25524 // too few arguments
25525 message = 'Too few arguments in function ' + _fn +
25526 ' (expected: ' + _expected.join(' or ') + ', index: ' + index + ')';
25527 }
25528 }
25529 else {
25530 // too many arguments
25531 message = 'Too many arguments in function ' + _fn +
25532 ' (expected: ' + index + ', actual: ' + argCount + ')'
25533 }
25534
25535 var err = new TypeError(message);
25536 err.data = data;
25537 return err;
25538 }
25539
25540 /**
25541 * Collection with function references (local shortcuts to functions)
25542 * @constructor
25543 * @param {string} [name='refs'] Optional name for the refs, used to generate
25544 * JavaScript code
25545 */
25546 function Refs(name) {
25547 this.name = name || 'refs';
25548 this.categories = {};
25549 }
25550
25551 /**
25552 * Add a function reference.
25553 * @param {Function} fn
25554 * @param {string} [category='fn'] A function category, like 'fn' or 'signature'
25555 * @returns {string} Returns the function name, for example 'fn0' or 'signature2'
25556 */
25557 Refs.prototype.add = function (fn, category) {
25558 var cat = category || 'fn';
25559 if (!this.categories[cat]) this.categories[cat] = [];
25560
25561 var index = this.categories[cat].indexOf(fn);
25562 if (index == -1) {
25563 index = this.categories[cat].length;
25564 this.categories[cat].push(fn);
25565 }
25566
25567 return cat + index;
25568 };
25569
25570 /**
25571 * Create code lines for all function references
25572 * @returns {string} Returns the code containing all function references
25573 */
25574 Refs.prototype.toCode = function () {
25575 var code = [];
25576 var path = this.name + '.categories';
25577 var categories = this.categories;
25578
25579 for (var cat in categories) {
25580 if (categories.hasOwnProperty(cat)) {
25581 var category = categories[cat];
25582
25583 for (var i = 0; i < category.length; i++) {
25584 code.push('var ' + cat + i + ' = ' + path + '[\'' + cat + '\'][' + i + '];');
25585 }
25586 }
25587 }
25588
25589 return code.join('\n');
25590 };
25591
25592 /**
25593 * A function parameter
25594 * @param {string | string[] | Param} types A parameter type like 'string',
25595 * 'number | boolean'
25596 * @param {boolean} [varArgs=false] Variable arguments if true
25597 * @constructor
25598 */
25599 function Param(types, varArgs) {
25600 // parse the types, can be a string with types separated by pipe characters |
25601 if (typeof types === 'string') {
25602 // parse variable arguments operator (ellipses '...number')
25603 var _types = types.trim();
25604 var _varArgs = _types.substr(0, 3) === '...';
25605 if (_varArgs) {
25606 _types = _types.substr(3);
25607 }
25608 if (_types === '') {
25609 this.types = ['any'];
25610 }
25611 else {
25612 this.types = _types.split('|');
25613 for (var i = 0; i < this.types.length; i++) {
25614 this.types[i] = this.types[i].trim();
25615 }
25616 }
25617 }
25618 else if (Array.isArray(types)) {
25619 this.types = types;
25620 }
25621 else if (types instanceof Param) {
25622 return types.clone();
25623 }
25624 else {
25625 throw new Error('String or Array expected');
25626 }
25627
25628 // can hold a type to which to convert when handling this parameter
25629 this.conversions = [];
25630 // TODO: implement better API for conversions, be able to add conversions via constructor (support a new type Object?)
25631
25632 // variable arguments
25633 this.varArgs = _varArgs || varArgs || false;
25634
25635 // check for any type arguments
25636 this.anyType = this.types.indexOf('any') !== -1;
25637 }
25638
25639 /**
25640 * Order Params
25641 * any type ('any') will be ordered last, and object as second last (as other
25642 * types may be an object as well, like Array).
25643 *
25644 * @param {Param} a
25645 * @param {Param} b
25646 * @returns {number} Returns 1 if a > b, -1 if a < b, and else 0.
25647 */
25648 Param.compare = function (a, b) {
25649 // TODO: simplify parameter comparison, it's a mess
25650 if (a.anyType) return 1;
25651 if (b.anyType) return -1;
25652
25653 if (contains(a.types, 'Object')) return 1;
25654 if (contains(b.types, 'Object')) return -1;
25655
25656 if (a.hasConversions()) {
25657 if (b.hasConversions()) {
25658 var i, ac, bc;
25659
25660 for (i = 0; i < a.conversions.length; i++) {
25661 if (a.conversions[i] !== undefined) {
25662 ac = a.conversions[i];
25663 break;
25664 }
25665 }
25666
25667 for (i = 0; i < b.conversions.length; i++) {
25668 if (b.conversions[i] !== undefined) {
25669 bc = b.conversions[i];
25670 break;
25671 }
25672 }
25673
25674 return typed.conversions.indexOf(ac) - typed.conversions.indexOf(bc);
25675 }
25676 else {
25677 return 1;
25678 }
25679 }
25680 else {
25681 if (b.hasConversions()) {
25682 return -1;
25683 }
25684 else {
25685 // both params have no conversions
25686 var ai, bi;
25687
25688 for (i = 0; i < typed.types.length; i++) {
25689 if (typed.types[i].name === a.types[0]) {
25690 ai = i;
25691 break;
25692 }
25693 }
25694
25695 for (i = 0; i < typed.types.length; i++) {
25696 if (typed.types[i].name === b.types[0]) {
25697 bi = i;
25698 break;
25699 }
25700 }
25701
25702 return ai - bi;
25703 }
25704 }
25705 };
25706
25707 /**
25708 * Test whether this parameters types overlap an other parameters types.
25709 * Will not match ['any'] with ['number']
25710 * @param {Param} other
25711 * @return {boolean} Returns true when there are overlapping types
25712 */
25713 Param.prototype.overlapping = function (other) {
25714 for (var i = 0; i < this.types.length; i++) {
25715 if (contains(other.types, this.types[i])) {
25716 return true;
25717 }
25718 }
25719 return false;
25720 };
25721
25722 /**
25723 * Test whether this parameters types matches an other parameters types.
25724 * When any of the two parameters contains `any`, true is returned
25725 * @param {Param} other
25726 * @return {boolean} Returns true when there are matching types
25727 */
25728 Param.prototype.matches = function (other) {
25729 return this.anyType || other.anyType || this.overlapping(other);
25730 };
25731
25732 /**
25733 * Create a clone of this param
25734 * @returns {Param} Returns a cloned version of this param
25735 */
25736 Param.prototype.clone = function () {
25737 var param = new Param(this.types.slice(), this.varArgs);
25738 param.conversions = this.conversions.slice();
25739 return param;
25740 };
25741
25742 /**
25743 * Test whether this parameter contains conversions
25744 * @returns {boolean} Returns true if the parameter contains one or
25745 * multiple conversions.
25746 */
25747 Param.prototype.hasConversions = function () {
25748 return this.conversions.length > 0;
25749 };
25750
25751 /**
25752 * Tests whether this parameters contains any of the provided types
25753 * @param {Object} types A Map with types, like {'number': true}
25754 * @returns {boolean} Returns true when the parameter contains any
25755 * of the provided types
25756 */
25757 Param.prototype.contains = function (types) {
25758 for (var i = 0; i < this.types.length; i++) {
25759 if (types[this.types[i]]) {
25760 return true;
25761 }
25762 }
25763 return false;
25764 };
25765
25766 /**
25767 * Return a string representation of this params types, like 'string' or
25768 * 'number | boolean' or '...number'
25769 * @param {boolean} [toConversion] If true, the returned types string
25770 * contains the types where the parameter
25771 * will convert to. If false (default)
25772 * the "from" types are returned
25773 * @returns {string}
25774 */
25775 Param.prototype.toString = function (toConversion) {
25776 var types = [];
25777 var keys = {};
25778
25779 for (var i = 0; i < this.types.length; i++) {
25780 var conversion = this.conversions[i];
25781 var type = toConversion && conversion ? conversion.to : this.types[i];
25782 if (!(type in keys)) {
25783 keys[type] = true;
25784 types.push(type);
25785 }
25786 }
25787
25788 return (this.varArgs ? '...' : '') + types.join('|');
25789 };
25790
25791 /**
25792 * A function signature
25793 * @param {string | string[] | Param[]} params
25794 * Array with the type(s) of each parameter,
25795 * or a comma separated string with types
25796 * @param {Function} fn The actual function
25797 * @constructor
25798 */
25799 function Signature(params, fn) {
25800 var _params;
25801 if (typeof params === 'string') {
25802 _params = (params !== '') ? params.split(',') : [];
25803 }
25804 else if (Array.isArray(params)) {
25805 _params = params;
25806 }
25807 else {
25808 throw new Error('string or Array expected');
25809 }
25810
25811 this.params = new Array(_params.length);
25812 this.anyType = false;
25813 this.varArgs = false;
25814 for (var i = 0; i < _params.length; i++) {
25815 var param = new Param(_params[i]);
25816 this.params[i] = param;
25817 if (param.anyType) {
25818 this.anyType = true;
25819 }
25820 if (i === _params.length - 1) {
25821 // the last argument
25822 this.varArgs = param.varArgs;
25823 }
25824 else {
25825 // non-last argument
25826 if (param.varArgs) {
25827 throw new SyntaxError('Unexpected variable arguments operator "..."');
25828 }
25829 }
25830 }
25831
25832 this.fn = fn;
25833 }
25834
25835 /**
25836 * Create a clone of this signature
25837 * @returns {Signature} Returns a cloned version of this signature
25838 */
25839 Signature.prototype.clone = function () {
25840 return new Signature(this.params.slice(), this.fn);
25841 };
25842
25843 /**
25844 * Expand a signature: split params with union types in separate signatures
25845 * For example split a Signature "string | number" into two signatures.
25846 * @return {Signature[]} Returns an array with signatures (at least one)
25847 */
25848 Signature.prototype.expand = function () {
25849 var signatures = [];
25850
25851 function recurse(signature, path) {
25852 if (path.length < signature.params.length) {
25853 var i, newParam, conversion;
25854
25855 var param = signature.params[path.length];
25856 if (param.varArgs) {
25857 // a variable argument. do not split the types in the parameter
25858 newParam = param.clone();
25859
25860 // add conversions to the parameter
25861 // recurse for all conversions
25862 for (i = 0; i < typed.conversions.length; i++) {
25863 conversion = typed.conversions[i];
25864 if (!contains(param.types, conversion.from) && contains(param.types, conversion.to)) {
25865 var j = newParam.types.length;
25866 newParam.types[j] = conversion.from;
25867 newParam.conversions[j] = conversion;
25868 }
25869 }
25870
25871 recurse(signature, path.concat(newParam));
25872 }
25873 else {
25874 // split each type in the parameter
25875 for (i = 0; i < param.types.length; i++) {
25876 recurse(signature, path.concat(new Param(param.types[i])));
25877 }
25878
25879 // recurse for all conversions
25880 for (i = 0; i < typed.conversions.length; i++) {
25881 conversion = typed.conversions[i];
25882 if (!contains(param.types, conversion.from) && contains(param.types, conversion.to)) {
25883 newParam = new Param(conversion.from);
25884 newParam.conversions[0] = conversion;
25885 recurse(signature, path.concat(newParam));
25886 }
25887 }
25888 }
25889 }
25890 else {
25891 signatures.push(new Signature(path, signature.fn));
25892 }
25893 }
25894
25895 recurse(this, []);
25896
25897 return signatures;
25898 };
25899
25900 /**
25901 * Compare two signatures.
25902 *
25903 * When two params are equal and contain conversions, they will be sorted
25904 * by lowest index of the first conversions.
25905 *
25906 * @param {Signature} a
25907 * @param {Signature} b
25908 * @returns {number} Returns 1 if a > b, -1 if a < b, and else 0.
25909 */
25910 Signature.compare = function (a, b) {
25911 if (a.params.length > b.params.length) return 1;
25912 if (a.params.length < b.params.length) return -1;
25913
25914 // count the number of conversions
25915 var i;
25916 var len = a.params.length; // a and b have equal amount of params
25917 var ac = 0;
25918 var bc = 0;
25919 for (i = 0; i < len; i++) {
25920 if (a.params[i].hasConversions()) ac++;
25921 if (b.params[i].hasConversions()) bc++;
25922 }
25923
25924 if (ac > bc) return 1;
25925 if (ac < bc) return -1;
25926
25927 // compare the order per parameter
25928 for (i = 0; i < a.params.length; i++) {
25929 var cmp = Param.compare(a.params[i], b.params[i]);
25930 if (cmp !== 0) {
25931 return cmp;
25932 }
25933 }
25934
25935 return 0;
25936 };
25937
25938 /**
25939 * Test whether any of the signatures parameters has conversions
25940 * @return {boolean} Returns true when any of the parameters contains
25941 * conversions.
25942 */
25943 Signature.prototype.hasConversions = function () {
25944 for (var i = 0; i < this.params.length; i++) {
25945 if (this.params[i].hasConversions()) {
25946 return true;
25947 }
25948 }
25949 return false;
25950 };
25951
25952 /**
25953 * Test whether this signature should be ignored.
25954 * Checks whether any of the parameters contains a type listed in
25955 * typed.ignore
25956 * @return {boolean} Returns true when the signature should be ignored
25957 */
25958 Signature.prototype.ignore = function () {
25959 // create a map with ignored types
25960 var types = {};
25961 for (var i = 0; i < typed.ignore.length; i++) {
25962 types[typed.ignore[i]] = true;
25963 }
25964
25965 // test whether any of the parameters contains this type
25966 for (i = 0; i < this.params.length; i++) {
25967 if (this.params[i].contains(types)) {
25968 return true;
25969 }
25970 }
25971
25972 return false;
25973 };
25974
25975 /**
25976 * Test whether the path of this signature matches a given path.
25977 * @param {Param[]} params
25978 */
25979 Signature.prototype.paramsStartWith = function (params) {
25980 if (params.length === 0) {
25981 return true;
25982 }
25983
25984 var aLast = last(this.params);
25985 var bLast = last(params);
25986
25987 for (var i = 0; i < params.length; i++) {
25988 var a = this.params[i] || (aLast.varArgs ? aLast: null);
25989 var b = params[i] || (bLast.varArgs ? bLast: null);
25990
25991 if (!a || !b || !a.matches(b)) {
25992 return false;
25993 }
25994 }
25995
25996 return true;
25997 };
25998
25999 /**
26000 * Generate the code to invoke this signature
26001 * @param {Refs} refs
26002 * @param {string} prefix
26003 * @returns {string} Returns code
26004 */
26005 Signature.prototype.toCode = function (refs, prefix) {
26006 var code = [];
26007
26008 var args = new Array(this.params.length);
26009 for (var i = 0; i < this.params.length; i++) {
26010 var param = this.params[i];
26011 var conversion = param.conversions[0];
26012 if (param.varArgs) {
26013 args[i] = 'varArgs';
26014 }
26015 else if (conversion) {
26016 args[i] = refs.add(conversion.convert, 'convert') + '(arg' + i + ')';
26017 }
26018 else {
26019 args[i] = 'arg' + i;
26020 }
26021 }
26022
26023 var ref = this.fn ? refs.add(this.fn, 'signature') : undefined;
26024 if (ref) {
26025 return prefix + 'return ' + ref + '(' + args.join(', ') + '); // signature: ' + this.params.join(', ');
26026 }
26027
26028 return code.join('\n');
26029 };
26030
26031 /**
26032 * Return a string representation of the signature
26033 * @returns {string}
26034 */
26035 Signature.prototype.toString = function () {
26036 return this.params.join(', ');
26037 };
26038
26039 /**
26040 * A group of signatures with the same parameter on given index
26041 * @param {Param[]} path
26042 * @param {Signature} [signature]
26043 * @param {Node[]} childs
26044 * @param {boolean} [fallThrough=false]
26045 * @constructor
26046 */
26047 function Node(path, signature, childs, fallThrough) {
26048 this.path = path || [];
26049 this.param = path[path.length - 1] || null;
26050 this.signature = signature || null;
26051 this.childs = childs || [];
26052 this.fallThrough = fallThrough || false;
26053 }
26054
26055 /**
26056 * Generate code for this group of signatures
26057 * @param {Refs} refs
26058 * @param {string} prefix
26059 * @returns {string} Returns the code as string
26060 */
26061 Node.prototype.toCode = function (refs, prefix) {
26062 // TODO: split this function in multiple functions, it's too large
26063 var code = [];
26064
26065 if (this.param) {
26066 var index = this.path.length - 1;
26067 var conversion = this.param.conversions[0];
26068 var comment = '// type: ' + (conversion ?
26069 (conversion.from + ' (convert to ' + conversion.to + ')') :
26070 this.param);
26071
26072 // non-root node (path is non-empty)
26073 if (this.param.varArgs) {
26074 if (this.param.anyType) {
26075 // variable arguments with any type
26076 code.push(prefix + 'if (arguments.length > ' + index + ') {');
26077 code.push(prefix + ' var varArgs = [];');
26078 code.push(prefix + ' for (var i = ' + index + '; i < arguments.length; i++) {');
26079 code.push(prefix + ' varArgs.push(arguments[i]);');
26080 code.push(prefix + ' }');
26081 code.push(this.signature.toCode(refs, prefix + ' '));
26082 code.push(prefix + '}');
26083 }
26084 else {
26085 // variable arguments with a fixed type
26086 var getTests = function (types, arg) {
26087 var tests = [];
26088 for (var i = 0; i < types.length; i++) {
26089 tests[i] = refs.add(getTypeTest(types[i]), 'test') + '(' + arg + ')';
26090 }
26091 return tests.join(' || ');
26092 }.bind(this);
26093
26094 var allTypes = this.param.types;
26095 var exactTypes = [];
26096 for (var i = 0; i < allTypes.length; i++) {
26097 if (this.param.conversions[i] === undefined) {
26098 exactTypes.push(allTypes[i]);
26099 }
26100 }
26101
26102 code.push(prefix + 'if (' + getTests(allTypes, 'arg' + index) + ') { ' + comment);
26103 code.push(prefix + ' var varArgs = [arg' + index + '];');
26104 code.push(prefix + ' for (var i = ' + (index + 1) + '; i < arguments.length; i++) {');
26105 code.push(prefix + ' if (' + getTests(exactTypes, 'arguments[i]') + ') {');
26106 code.push(prefix + ' varArgs.push(arguments[i]);');
26107
26108 for (var i = 0; i < allTypes.length; i++) {
26109 var conversion_i = this.param.conversions[i];
26110 if (conversion_i) {
26111 var test = refs.add(getTypeTest(allTypes[i]), 'test');
26112 var convert = refs.add(conversion_i.convert, 'convert');
26113 code.push(prefix + ' }');
26114 code.push(prefix + ' else if (' + test + '(arguments[i])) {');
26115 code.push(prefix + ' varArgs.push(' + convert + '(arguments[i]));');
26116 }
26117 }
26118 code.push(prefix + ' } else {');
26119 code.push(prefix + ' throw createError(name, arguments.length, i, arguments[i], \'' + exactTypes.join(',') + '\');');
26120 code.push(prefix + ' }');
26121 code.push(prefix + ' }');
26122 code.push(this.signature.toCode(refs, prefix + ' '));
26123 code.push(prefix + '}');
26124 }
26125 }
26126 else {
26127 if (this.param.anyType) {
26128 // any type
26129 code.push(prefix + '// type: any');
26130 code.push(this._innerCode(refs, prefix));
26131 }
26132 else {
26133 // regular type
26134 var type = this.param.types[0];
26135 var test = type !== 'any' ? refs.add(getTypeTest(type), 'test') : null;
26136
26137 code.push(prefix + 'if (' + test + '(arg' + index + ')) { ' + comment);
26138 code.push(this._innerCode(refs, prefix + ' '));
26139 code.push(prefix + '}');
26140 }
26141 }
26142 }
26143 else {
26144 // root node (path is empty)
26145 code.push(this._innerCode(refs, prefix));
26146 }
26147
26148 return code.join('\n');
26149 };
26150
26151 /**
26152 * Generate inner code for this group of signatures.
26153 * This is a helper function of Node.prototype.toCode
26154 * @param {Refs} refs
26155 * @param {string} prefix
26156 * @returns {string} Returns the inner code as string
26157 * @private
26158 */
26159 Node.prototype._innerCode = function (refs, prefix) {
26160 var code = [];
26161 var i;
26162
26163 if (this.signature) {
26164 code.push(prefix + 'if (arguments.length === ' + this.path.length + ') {');
26165 code.push(this.signature.toCode(refs, prefix + ' '));
26166 code.push(prefix + '}');
26167 }
26168
26169 for (i = 0; i < this.childs.length; i++) {
26170 code.push(this.childs[i].toCode(refs, prefix));
26171 }
26172
26173 // TODO: shouldn't the this.param.anyType check be redundant
26174 if (!this.fallThrough || (this.param && this.param.anyType)) {
26175 var exceptions = this._exceptions(refs, prefix);
26176 if (exceptions) {
26177 code.push(exceptions);
26178 }
26179 }
26180
26181 return code.join('\n');
26182 };
26183
26184
26185 /**
26186 * Generate code to throw exceptions
26187 * @param {Refs} refs
26188 * @param {string} prefix
26189 * @returns {string} Returns the inner code as string
26190 * @private
26191 */
26192 Node.prototype._exceptions = function (refs, prefix) {
26193 var index = this.path.length;
26194
26195 if (this.childs.length === 0) {
26196 // TODO: can this condition be simplified? (we have a fall-through here)
26197 return [
26198 prefix + 'if (arguments.length > ' + index + ') {',
26199 prefix + ' throw createError(name, arguments.length, ' + index + ', arguments[' + index + ']);',
26200 prefix + '}'
26201 ].join('\n');
26202 }
26203 else {
26204 var keys = {};
26205 var types = [];
26206
26207 for (var i = 0; i < this.childs.length; i++) {
26208 var node = this.childs[i];
26209 if (node.param) {
26210 for (var j = 0; j < node.param.types.length; j++) {
26211 var type = node.param.types[j];
26212 if (!(type in keys) && !node.param.conversions[j]) {
26213 keys[type] = true;
26214 types.push(type);
26215 }
26216 }
26217 }
26218 }
26219
26220 return prefix + 'throw createError(name, arguments.length, ' + index + ', arguments[' + index + '], \'' + types.join(',') + '\');';
26221 }
26222 };
26223
26224 /**
26225 * Split all raw signatures into an array with expanded Signatures
26226 * @param {Object.<string, Function>} rawSignatures
26227 * @return {Signature[]} Returns an array with expanded signatures
26228 */
26229 function parseSignatures(rawSignatures) {
26230 // FIXME: need to have deterministic ordering of signatures, do not create via object
26231 var signature;
26232 var keys = {};
26233 var signatures = [];
26234 var i;
26235
26236 for (var types in rawSignatures) {
26237 if (rawSignatures.hasOwnProperty(types)) {
26238 var fn = rawSignatures[types];
26239 signature = new Signature(types, fn);
26240
26241 if (signature.ignore()) {
26242 continue;
26243 }
26244
26245 var expanded = signature.expand();
26246
26247 for (i = 0; i < expanded.length; i++) {
26248 var signature_i = expanded[i];
26249 var key = signature_i.toString();
26250 var existing = keys[key];
26251 if (!existing) {
26252 keys[key] = signature_i;
26253 }
26254 else {
26255 var cmp = Signature.compare(signature_i, existing);
26256 if (cmp < 0) {
26257 // override if sorted first
26258 keys[key] = signature_i;
26259 }
26260 else if (cmp === 0) {
26261 throw new Error('Signature "' + key + '" is defined twice');
26262 }
26263 // else: just ignore
26264 }
26265 }
26266 }
26267 }
26268
26269 // convert from map to array
26270 for (key in keys) {
26271 if (keys.hasOwnProperty(key)) {
26272 signatures.push(keys[key]);
26273 }
26274 }
26275
26276 // order the signatures
26277 signatures.sort(function (a, b) {
26278 return Signature.compare(a, b);
26279 });
26280
26281 // filter redundant conversions from signatures with varArgs
26282 // TODO: simplify this loop or move it to a separate function
26283 for (i = 0; i < signatures.length; i++) {
26284 signature = signatures[i];
26285
26286 if (signature.varArgs) {
26287 var index = signature.params.length - 1;
26288 var param = signature.params[index];
26289
26290 var t = 0;
26291 while (t < param.types.length) {
26292 if (param.conversions[t]) {
26293 var type = param.types[t];
26294
26295 for (var j = 0; j < signatures.length; j++) {
26296 var other = signatures[j];
26297 var p = other.params[index];
26298
26299 if (other !== signature &&
26300 p &&
26301 contains(p.types, type) && !p.conversions[index]) {
26302 // this (conversion) type already exists, remove it
26303 param.types.splice(t, 1);
26304 param.conversions.splice(t, 1);
26305 t--;
26306 break;
26307 }
26308 }
26309 }
26310 t++;
26311 }
26312 }
26313 }
26314
26315 return signatures;
26316 }
26317
26318 /**
26319 * Filter all any type signatures
26320 * @param {Signature[]} signatures
26321 * @return {Signature[]} Returns only any type signatures
26322 */
26323 function filterAnyTypeSignatures (signatures) {
26324 var filtered = [];
26325
26326 for (var i = 0; i < signatures.length; i++) {
26327 if (signatures[i].anyType) {
26328 filtered.push(signatures[i]);
26329 }
26330 }
26331
26332 return filtered;
26333 }
26334
26335 /**
26336 * create a map with normalized signatures as key and the function as value
26337 * @param {Signature[]} signatures An array with split signatures
26338 * @return {Object.<string, Function>} Returns a map with normalized
26339 * signatures as key, and the function
26340 * as value.
26341 */
26342 function mapSignatures(signatures) {
26343 var normalized = {};
26344
26345 for (var i = 0; i < signatures.length; i++) {
26346 var signature = signatures[i];
26347 if (signature.fn && !signature.hasConversions()) {
26348 var params = signature.params.join(',');
26349 normalized[params] = signature.fn;
26350 }
26351 }
26352
26353 return normalized;
26354 }
26355
26356 /**
26357 * Parse signatures recursively in a node tree.
26358 * @param {Signature[]} signatures Array with expanded signatures
26359 * @param {Param[]} path Traversed path of parameter types
26360 * @param {Signature[]} anys
26361 * @return {Node} Returns a node tree
26362 */
26363 function parseTree(signatures, path, anys) {
26364 var i, signature;
26365 var index = path.length;
26366 var nodeSignature;
26367
26368 var filtered = [];
26369 for (i = 0; i < signatures.length; i++) {
26370 signature = signatures[i];
26371
26372 // filter the first signature with the correct number of params
26373 if (signature.params.length === index && !nodeSignature) {
26374 nodeSignature = signature;
26375 }
26376
26377 if (signature.params[index] != undefined) {
26378 filtered.push(signature);
26379 }
26380 }
26381
26382 // sort the filtered signatures by param
26383 filtered.sort(function (a, b) {
26384 return Param.compare(a.params[index], b.params[index]);
26385 });
26386
26387 // recurse over the signatures
26388 var entries = [];
26389 for (i = 0; i < filtered.length; i++) {
26390 signature = filtered[i];
26391 // group signatures with the same param at current index
26392 var param = signature.params[index];
26393
26394 // TODO: replace the next filter loop
26395 var existing = entries.filter(function (entry) {
26396 return entry.param.overlapping(param);
26397 })[0];
26398
26399 //var existing;
26400 //for (var j = 0; j < entries.length; j++) {
26401 // if (entries[j].param.overlapping(param)) {
26402 // existing = entries[j];
26403 // break;
26404 // }
26405 //}
26406
26407 if (existing) {
26408 if (existing.param.varArgs) {
26409 throw new Error('Conflicting types "' + existing.param + '" and "' + param + '"');
26410 }
26411 existing.signatures.push(signature);
26412 }
26413 else {
26414 entries.push({
26415 param: param,
26416 signatures: [signature]
26417 });
26418 }
26419 }
26420
26421 // find all any type signature that can still match our current path
26422 var matchingAnys = [];
26423 for (i = 0; i < anys.length; i++) {
26424 if (anys[i].paramsStartWith(path)) {
26425 matchingAnys.push(anys[i]);
26426 }
26427 }
26428
26429 // see if there are any type signatures that don't match any of the
26430 // signatures that we have in our tree, i.e. we have alternative
26431 // matching signature(s) outside of our current tree and we should
26432 // fall through to them instead of throwing an exception
26433 var fallThrough = false;
26434 for (i = 0; i < matchingAnys.length; i++) {
26435 if (!contains(signatures, matchingAnys[i])) {
26436 fallThrough = true;
26437 break;
26438 }
26439 }
26440
26441 // parse the childs
26442 var childs = new Array(entries.length);
26443 for (i = 0; i < entries.length; i++) {
26444 var entry = entries[i];
26445 childs[i] = parseTree(entry.signatures, path.concat(entry.param), matchingAnys)
26446 }
26447
26448 return new Node(path, nodeSignature, childs, fallThrough);
26449 }
26450
26451 /**
26452 * Generate an array like ['arg0', 'arg1', 'arg2']
26453 * @param {number} count Number of arguments to generate
26454 * @returns {Array} Returns an array with argument names
26455 */
26456 function getArgs(count) {
26457 // create an array with all argument names
26458 var args = [];
26459 for (var i = 0; i < count; i++) {
26460 args[i] = 'arg' + i;
26461 }
26462
26463 return args;
26464 }
26465
26466 /**
26467 * Compose a function from sub-functions each handling a single type signature.
26468 * Signatures:
26469 * typed(signature: string, fn: function)
26470 * typed(name: string, signature: string, fn: function)
26471 * typed(signatures: Object.<string, function>)
26472 * typed(name: string, signatures: Object.<string, function>)
26473 *
26474 * @param {string | null} name
26475 * @param {Object.<string, Function>} signatures
26476 * @return {Function} Returns the typed function
26477 * @private
26478 */
26479 function _typed(name, signatures) {
26480 var refs = new Refs();
26481
26482 // parse signatures, expand them
26483 var _signatures = parseSignatures(signatures);
26484 if (_signatures.length == 0) {
26485 throw new Error('No signatures provided');
26486 }
26487
26488 // filter all any type signatures
26489 var anys = filterAnyTypeSignatures(_signatures);
26490
26491 // parse signatures into a node tree
26492 var node = parseTree(_signatures, [], anys);
26493
26494 //var util = require('util');
26495 //console.log('ROOT');
26496 //console.log(util.inspect(node, { depth: null }));
26497
26498 // generate code for the typed function
26499 // safeName is a conservative replacement of characters
26500 // to prevend being able to inject JS code at the place of the function name
26501 // the name is useful for stack trackes therefore we want have it there
26502 var code = [];
26503 var safeName = (name || '').replace(/[^a-zA-Z0-9_$]/g, '_')
26504 var args = getArgs(maxParams(_signatures));
26505 code.push('function ' + safeName + '(' + args.join(', ') + ') {');
26506 code.push(' "use strict";');
26507 code.push(' var name = ' + JSON.stringify(name || '') + ';');
26508 code.push(node.toCode(refs, ' ', false));
26509 code.push('}');
26510
26511 // generate body for the factory function
26512 var body = [
26513 refs.toCode(),
26514 'return ' + code.join('\n')
26515 ].join('\n');
26516
26517 // evaluate the JavaScript code and attach function references
26518 var factory = (new Function(refs.name, 'createError', body));
26519 var fn = factory(refs, createError);
26520
26521 //console.log('FN\n' + fn.toString()); // TODO: cleanup
26522
26523 // attach the signatures with sub-functions to the constructed function
26524 fn.signatures = mapSignatures(_signatures);
26525
26526 return fn;
26527 }
26528
26529 /**
26530 * Calculate the maximum number of parameters in givens signatures
26531 * @param {Signature[]} signatures
26532 * @returns {number} The maximum number of parameters
26533 */
26534 function maxParams(signatures) {
26535 var max = 0;
26536
26537 for (var i = 0; i < signatures.length; i++) {
26538 var len = signatures[i].params.length;
26539 if (len > max) {
26540 max = len;
26541 }
26542 }
26543
26544 return max;
26545 }
26546
26547 /**
26548 * Get the type of a value
26549 * @param {*} x
26550 * @returns {string} Returns a string with the type of value
26551 */
26552 function getTypeOf(x) {
26553 var obj;
26554
26555 for (var i = 0; i < typed.types.length; i++) {
26556 var entry = typed.types[i];
26557
26558 if (entry.name === 'Object') {
26559 // Array and Date are also Object, so test for Object afterwards
26560 obj = entry;
26561 }
26562 else {
26563 if (entry.test(x)) return entry.name;
26564 }
26565 }
26566
26567 // at last, test whether an object
26568 if (obj && obj.test(x)) return obj.name;
26569
26570 return 'unknown';
26571 }
26572
26573 /**
26574 * Test whether an array contains some item
26575 * @param {Array} array
26576 * @param {*} item
26577 * @return {boolean} Returns true if array contains item, false if not.
26578 */
26579 function contains(array, item) {
26580 return array.indexOf(item) !== -1;
26581 }
26582
26583 /**
26584 * Returns the last item in the array
26585 * @param {Array} array
26586 * @return {*} item
26587 */
26588 function last (array) {
26589 return array[array.length - 1];
26590 }
26591
26592 // data type tests
26593 var types = [
26594 { name: 'number', test: function (x) { return typeof x === 'number' } },
26595 { name: 'string', test: function (x) { return typeof x === 'string' } },
26596 { name: 'boolean', test: function (x) { return typeof x === 'boolean' } },
26597 { name: 'Function', test: function (x) { return typeof x === 'function'} },
26598 { name: 'Array', test: Array.isArray },
26599 { name: 'Date', test: function (x) { return x instanceof Date } },
26600 { name: 'RegExp', test: function (x) { return x instanceof RegExp } },
26601 { name: 'Object', test: function (x) { return typeof x === 'object' } },
26602 { name: 'null', test: function (x) { return x === null } },
26603 { name: 'undefined', test: function (x) { return x === undefined } }
26604 ];
26605
26606 // configuration
26607 var config = {};
26608
26609 // type conversions. Order is important
26610 var conversions = [];
26611
26612 // types to be ignored
26613 var ignore = [];
26614
26615 // temporary object for holding types and conversions, for constructing
26616 // the `typed` function itself
26617 // TODO: find a more elegant solution for this
26618 var typed = {
26619 config: config,
26620 types: types,
26621 conversions: conversions,
26622 ignore: ignore
26623 };
26624
26625 /**
26626 * Construct the typed function itself with various signatures
26627 *
26628 * Signatures:
26629 *
26630 * typed(signatures: Object.<string, function>)
26631 * typed(name: string, signatures: Object.<string, function>)
26632 */
26633 typed = _typed('typed', {
26634 'Object': function (signatures) {
26635 var fns = [];
26636 for (var signature in signatures) {
26637 if (signatures.hasOwnProperty(signature)) {
26638 fns.push(signatures[signature]);
26639 }
26640 }
26641 var name = getName(fns);
26642
26643 return _typed(name, signatures);
26644 },
26645 'string, Object': _typed,
26646 // TODO: add a signature 'Array.<function>'
26647 '...Function': function (fns) {
26648 var err;
26649 var name = getName(fns);
26650 var signatures = {};
26651
26652 for (var i = 0; i < fns.length; i++) {
26653 var fn = fns[i];
26654
26655 // test whether this is a typed-function
26656 if (!(typeof fn.signatures === 'object')) {
26657 err = new TypeError('Function is no typed-function (index: ' + i + ')');
26658 err.data = {index: i};
26659 throw err;
26660 }
26661
26662 // merge the signatures
26663 for (var signature in fn.signatures) {
26664 if (fn.signatures.hasOwnProperty(signature)) {
26665 if (signatures.hasOwnProperty(signature)) {
26666 if (fn.signatures[signature] !== signatures[signature]) {
26667 err = new Error('Signature "' + signature + '" is defined twice');
26668 err.data = {signature: signature};
26669 throw err;
26670 }
26671 // else: both signatures point to the same function, that's fine
26672 }
26673 else {
26674 signatures[signature] = fn.signatures[signature];
26675 }
26676 }
26677 }
26678 }
26679
26680 return _typed(name, signatures);
26681 }
26682 });
26683
26684 /**
26685 * Find a specific signature from a (composed) typed function, for
26686 * example:
26687 *
26688 * typed.find(fn, ['number', 'string'])
26689 * typed.find(fn, 'number, string')
26690 *
26691 * Function find only only works for exact matches.
26692 *
26693 * @param {Function} fn A typed-function
26694 * @param {string | string[]} signature Signature to be found, can be
26695 * an array or a comma separated string.
26696 * @return {Function} Returns the matching signature, or
26697 * throws an errror when no signature
26698 * is found.
26699 */
26700 function find (fn, signature) {
26701 if (!fn.signatures) {
26702 throw new TypeError('Function is no typed-function');
26703 }
26704
26705 // normalize input
26706 var arr;
26707 if (typeof signature === 'string') {
26708 arr = signature.split(',');
26709 for (var i = 0; i < arr.length; i++) {
26710 arr[i] = arr[i].trim();
26711 }
26712 }
26713 else if (Array.isArray(signature)) {
26714 arr = signature;
26715 }
26716 else {
26717 throw new TypeError('String array or a comma separated string expected');
26718 }
26719
26720 var str = arr.join(',');
26721
26722 // find an exact match
26723 var match = fn.signatures[str];
26724 if (match) {
26725 return match;
26726 }
26727
26728 // TODO: extend find to match non-exact signatures
26729
26730 throw new TypeError('Signature not found (signature: ' + (fn.name || 'unnamed') + '(' + arr.join(', ') + '))');
26731 }
26732
26733 /**
26734 * Convert a given value to another data type.
26735 * @param {*} value
26736 * @param {string} type
26737 */
26738 function convert (value, type) {
26739 var from = getTypeOf(value);
26740
26741 // check conversion is needed
26742 if (type === from) {
26743 return value;
26744 }
26745
26746 for (var i = 0; i < typed.conversions.length; i++) {
26747 var conversion = typed.conversions[i];
26748 if (conversion.from === from && conversion.to === type) {
26749 return conversion.convert(value);
26750 }
26751 }
26752
26753 throw new Error('Cannot convert from ' + from + ' to ' + type);
26754 }
26755
26756 // attach types and conversions to the final `typed` function
26757 typed.config = config;
26758 typed.types = types;
26759 typed.conversions = conversions;
26760 typed.ignore = ignore;
26761 typed.create = create;
26762 typed.find = find;
26763 typed.convert = convert;
26764
26765 // add a type
26766 typed.addType = function (type) {
26767 if (!type || typeof type.name !== 'string' || typeof type.test !== 'function') {
26768 throw new TypeError('Object with properties {name: string, test: function} expected');
26769 }
26770
26771 typed.types.push(type);
26772 };
26773
26774 // add a conversion
26775 typed.addConversion = function (conversion) {
26776 if (!conversion
26777 || typeof conversion.from !== 'string'
26778 || typeof conversion.to !== 'string'
26779 || typeof conversion.convert !== 'function') {
26780 throw new TypeError('Object with properties {from: string, to: string, convert: function} expected');
26781 }
26782
26783 typed.conversions.push(conversion);
26784 };
26785
26786 return typed;
26787 }
26788
26789 return create();
26790}));
26791
26792
26793/***/ }),
26794/* 156 */
26795/***/ (function(module, exports) {
26796
26797function E () {
26798 // Keep this empty so it's easier to inherit from
26799 // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)
26800}
26801
26802E.prototype = {
26803 on: function (name, callback, ctx) {
26804 var e = this.e || (this.e = {});
26805
26806 (e[name] || (e[name] = [])).push({
26807 fn: callback,
26808 ctx: ctx
26809 });
26810
26811 return this;
26812 },
26813
26814 once: function (name, callback, ctx) {
26815 var self = this;
26816 function listener () {
26817 self.off(name, listener);
26818 callback.apply(ctx, arguments);
26819 };
26820
26821 listener._ = callback
26822 return this.on(name, listener, ctx);
26823 },
26824
26825 emit: function (name) {
26826 var data = [].slice.call(arguments, 1);
26827 var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
26828 var i = 0;
26829 var len = evtArr.length;
26830
26831 for (i; i < len; i++) {
26832 evtArr[i].fn.apply(evtArr[i].ctx, data);
26833 }
26834
26835 return this;
26836 },
26837
26838 off: function (name, callback) {
26839 var e = this.e || (this.e = {});
26840 var evts = e[name];
26841 var liveEvents = [];
26842
26843 if (evts && callback) {
26844 for (var i = 0, len = evts.length; i < len; i++) {
26845 if (evts[i].fn !== callback && evts[i].fn._ !== callback)
26846 liveEvents.push(evts[i]);
26847 }
26848 }
26849
26850 // Remove event from queue to prevent memory leak
26851 // Suggested by https://github.com/lazd
26852 // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910
26853
26854 (liveEvents.length)
26855 ? e[name] = liveEvents
26856 : delete e[name];
26857
26858 return this;
26859 }
26860};
26861
26862module.exports = E;
26863
26864
26865/***/ }),
26866/* 157 */
26867/***/ (function(module, exports, __webpack_require__) {
26868
26869"use strict";
26870
26871
26872var lazy = __webpack_require__(5).lazy;
26873var isFactory = __webpack_require__(5).isFactory;
26874var traverse = __webpack_require__(5).traverse;
26875var ArgumentsError = __webpack_require__(44);
26876
26877function factory (type, config, load, typed, math) {
26878 /**
26879 * Import functions from an object or a module
26880 *
26881 * Syntax:
26882 *
26883 * math.import(object)
26884 * math.import(object, options)
26885 *
26886 * Where:
26887 *
26888 * - `object: Object`
26889 * An object with functions to be imported.
26890 * - `options: Object` An object with import options. Available options:
26891 * - `override: boolean`
26892 * If true, existing functions will be overwritten. False by default.
26893 * - `silent: boolean`
26894 * If true, the function will not throw errors on duplicates or invalid
26895 * types. False by default.
26896 * - `wrap: boolean`
26897 * If true, the functions will be wrapped in a wrapper function
26898 * which converts data types like Matrix to primitive data types like Array.
26899 * The wrapper is needed when extending math.js with libraries which do not
26900 * support these data type. False by default.
26901 *
26902 * Examples:
26903 *
26904 * // define new functions and variables
26905 * math.import({
26906 * myvalue: 42,
26907 * hello: function (name) {
26908 * return 'hello, ' + name + '!';
26909 * }
26910 * });
26911 *
26912 * // use the imported function and variable
26913 * math.myvalue * 2; // 84
26914 * math.hello('user'); // 'hello, user!'
26915 *
26916 * // import the npm module 'numbers'
26917 * // (must be installed first with `npm install numbers`)
26918 * math.import(require('numbers'), {wrap: true});
26919 *
26920 * math.fibonacci(7); // returns 13
26921 *
26922 * @param {Object | Array} object Object with functions to be imported.
26923 * @param {Object} [options] Import options.
26924 */
26925 function math_import(object, options) {
26926 var num = arguments.length;
26927 if (num !== 1 && num !== 2) {
26928 throw new ArgumentsError('import', num, 1, 2);
26929 }
26930
26931 if (!options) {
26932 options = {};
26933 }
26934
26935 if (isFactory(object)) {
26936 _importFactory(object, options);
26937 }
26938 // TODO: allow a typed-function with name too
26939 else if (Array.isArray(object)) {
26940 object.forEach(function (entry) {
26941 math_import(entry, options);
26942 });
26943 }
26944 else if (typeof object === 'object') {
26945 // a map with functions
26946 for (var name in object) {
26947 if (object.hasOwnProperty(name)) {
26948 var value = object[name];
26949 if (isSupportedType(value)) {
26950 _import(name, value, options);
26951 }
26952 else if (isFactory(object)) {
26953 _importFactory(object, options);
26954 }
26955 else {
26956 math_import(value, options);
26957 }
26958 }
26959 }
26960 }
26961 else {
26962 if (!options.silent) {
26963 throw new TypeError('Factory, Object, or Array expected');
26964 }
26965 }
26966 }
26967
26968 /**
26969 * Add a property to the math namespace and create a chain proxy for it.
26970 * @param {string} name
26971 * @param {*} value
26972 * @param {Object} options See import for a description of the options
26973 * @private
26974 */
26975 function _import(name, value, options) {
26976 // TODO: refactor this function, it's to complicated and contains duplicate code
26977 if (options.wrap && typeof value === 'function') {
26978 // create a wrapper around the function
26979 value = _wrap(value);
26980 }
26981
26982 if (isTypedFunction(math[name]) && isTypedFunction(value)) {
26983 if (options.override) {
26984 // give the typed function the right name
26985 value = typed(name, value.signatures);
26986 }
26987 else {
26988 // merge the existing and typed function
26989 value = typed(math[name], value);
26990 }
26991
26992 math[name] = value;
26993 _importTransform(name, value);
26994 math.emit('import', name, function resolver() {
26995 return value;
26996 });
26997 return;
26998 }
26999
27000 if (math[name] === undefined || options.override) {
27001 math[name] = value;
27002 _importTransform(name, value);
27003 math.emit('import', name, function resolver() {
27004 return value;
27005 });
27006 return;
27007 }
27008
27009 if (!options.silent) {
27010 throw new Error('Cannot import "' + name + '": already exists');
27011 }
27012 }
27013
27014 function _importTransform (name, value) {
27015 if (value && typeof value.transform === 'function') {
27016 math.expression.transform[name] = value.transform;
27017 if (allowedInExpressions(name)) {
27018 math.expression.mathWithTransform[name] = value.transform
27019 }
27020 }
27021 else {
27022 // remove existing transform
27023 delete math.expression.transform[name]
27024 if (allowedInExpressions(name)) {
27025 math.expression.mathWithTransform[name] = value
27026 }
27027 }
27028 }
27029
27030 /**
27031 * Create a wrapper a round an function which converts the arguments
27032 * to their primitive values (like convert a Matrix to Array)
27033 * @param {Function} fn
27034 * @return {Function} Returns the wrapped function
27035 * @private
27036 */
27037 function _wrap (fn) {
27038 var wrapper = function wrapper () {
27039 var args = [];
27040 for (var i = 0, len = arguments.length; i < len; i++) {
27041 var arg = arguments[i];
27042 args[i] = arg && arg.valueOf();
27043 }
27044 return fn.apply(math, args);
27045 };
27046
27047 if (fn.transform) {
27048 wrapper.transform = fn.transform;
27049 }
27050
27051 return wrapper;
27052 }
27053
27054 /**
27055 * Import an instance of a factory into math.js
27056 * @param {{factory: Function, name: string, path: string, math: boolean}} factory
27057 * @param {Object} options See import for a description of the options
27058 * @private
27059 */
27060 function _importFactory(factory, options) {
27061 if (typeof factory.name === 'string') {
27062 var name = factory.name;
27063 var existingTransform = name in math.expression.transform
27064 var namespace = factory.path ? traverse(math, factory.path) : math;
27065 var existing = namespace.hasOwnProperty(name) ? namespace[name] : undefined;
27066
27067 var resolver = function () {
27068 var instance = load(factory);
27069 if (instance && typeof instance.transform === 'function') {
27070 throw new Error('Transforms cannot be attached to factory functions. ' +
27071 'Please create a separate function for it with exports.path="expression.transform"');
27072 }
27073
27074 if (isTypedFunction(existing) && isTypedFunction(instance)) {
27075 if (options.override) {
27076 // replace the existing typed function (nothing to do)
27077 }
27078 else {
27079 // merge the existing and new typed function
27080 instance = typed(existing, instance);
27081 }
27082
27083 return instance;
27084 }
27085
27086 if (existing === undefined || options.override) {
27087 return instance;
27088 }
27089
27090 if (!options.silent) {
27091 throw new Error('Cannot import "' + name + '": already exists');
27092 }
27093 };
27094
27095 if (factory.lazy !== false) {
27096 lazy(namespace, name, resolver);
27097
27098 if (!existingTransform) {
27099 if (factory.path === 'expression.transform' || factoryAllowedInExpressions(factory)) {
27100 lazy(math.expression.mathWithTransform, name, resolver);
27101 }
27102 }
27103 }
27104 else {
27105 namespace[name] = resolver();
27106
27107 if (!existingTransform) {
27108 if (factory.path === 'expression.transform' || factoryAllowedInExpressions(factory)) {
27109 math.expression.mathWithTransform[name] = resolver();
27110 }
27111 }
27112 }
27113
27114 math.emit('import', name, resolver, factory.path);
27115 }
27116 else {
27117 // unnamed factory.
27118 // no lazy loading
27119 load(factory);
27120 }
27121 }
27122
27123 /**
27124 * Check whether given object is a type which can be imported
27125 * @param {Function | number | string | boolean | null | Unit | Complex} object
27126 * @return {boolean}
27127 * @private
27128 */
27129 function isSupportedType(object) {
27130 return typeof object === 'function'
27131 || typeof object === 'number'
27132 || typeof object === 'string'
27133 || typeof object === 'boolean'
27134 || object === null
27135 || (object && type.isUnit(object))
27136 || (object && type.isComplex(object))
27137 || (object && type.isBigNumber(object))
27138 || (object && type.isFraction(object))
27139 || (object && type.isMatrix(object))
27140 || (object && Array.isArray(object))
27141 }
27142
27143 /**
27144 * Test whether a given thing is a typed-function
27145 * @param {*} fn
27146 * @return {boolean} Returns true when `fn` is a typed-function
27147 */
27148 function isTypedFunction (fn) {
27149 return typeof fn === 'function' && typeof fn.signatures === 'object';
27150 }
27151
27152 function allowedInExpressions (name) {
27153 return !unsafe.hasOwnProperty(name);
27154 }
27155
27156 function factoryAllowedInExpressions (factory) {
27157 return factory.path === undefined && !unsafe.hasOwnProperty(factory.name);
27158 }
27159
27160 // namespaces and functions not available in the parser for safety reasons
27161 var unsafe = {
27162 'expression': true,
27163 'type': true,
27164 'docs': true,
27165 'error': true,
27166 'json': true,
27167 'chain': true // chain method not supported. Note that there is a unit chain too.
27168 };
27169
27170 return math_import;
27171}
27172
27173exports.math = true; // request access to the math namespace as 5th argument of the factory function
27174exports.name = 'import';
27175exports.factory = factory;
27176exports.lazy = true;
27177
27178
27179/***/ }),
27180/* 158 */
27181/***/ (function(module, exports, __webpack_require__) {
27182
27183"use strict";
27184
27185
27186var object = __webpack_require__(5);
27187
27188function factory (type, config, load, typed, math) {
27189 var MATRIX = ['Matrix', 'Array']; // valid values for option matrix
27190 var NUMBER = ['number', 'BigNumber', 'Fraction']; // valid values for option number
27191
27192 /**
27193 * Set configuration options for math.js, and get current options.
27194 * Will emit a 'config' event, with arguments (curr, prev, changes).
27195 *
27196 * Syntax:
27197 *
27198 * math.config(config: Object): Object
27199 *
27200 * Examples:
27201 *
27202 * math.config().number; // outputs 'number'
27203 * math.eval('0.4'); // outputs number 0.4
27204 * math.config({number: 'Fraction'});
27205 * math.eval('0.4'); // outputs Fraction 2/5
27206 *
27207 * @param {Object} [options] Available options:
27208 * {number} epsilon
27209 * Minimum relative difference between two
27210 * compared values, used by all comparison functions.
27211 * {string} matrix
27212 * A string 'Matrix' (default) or 'Array'.
27213 * {string} number
27214 * A string 'number' (default), 'BigNumber', or 'Fraction'
27215 * {number} precision
27216 * The number of significant digits for BigNumbers.
27217 * Not applicable for Numbers.
27218 * {string} parenthesis
27219 * How to display parentheses in LaTeX and string
27220 * output.
27221 * {string} randomSeed
27222 * Random seed for seeded pseudo random number generator.
27223 * Set to null to randomly seed.
27224 * @return {Object} Returns the current configuration
27225 */
27226 function _config(options) {
27227 if (options) {
27228 var prev = object.map(config, object.clone);
27229
27230 // validate some of the options
27231 validateOption(options, 'matrix', MATRIX);
27232 validateOption(options, 'number', NUMBER);
27233
27234 // merge options
27235 object.deepExtend(config, options);
27236
27237 var curr = object.map(config, object.clone);
27238
27239 var changes = object.map(options, object.clone);
27240
27241 // emit 'config' event
27242 math.emit('config', curr, prev, changes);
27243
27244 return curr;
27245 }
27246 else {
27247 return object.map(config, object.clone);
27248 }
27249 }
27250
27251 // attach the valid options to the function so they can be extended
27252 _config.MATRIX = MATRIX;
27253 _config.NUMBER = NUMBER;
27254
27255 return _config;
27256}
27257
27258/**
27259 * Test whether an Array contains a specific item.
27260 * @param {Array.<string>} array
27261 * @param {string} item
27262 * @return {boolean}
27263 */
27264function contains (array, item) {
27265 return array.indexOf(item) !== -1;
27266}
27267
27268/**
27269 * Find a string in an array. Case insensitive search
27270 * @param {Array.<string>} array
27271 * @param {string} item
27272 * @return {number} Returns the index when found. Returns -1 when not found
27273 */
27274function findIndex (array, item) {
27275 return array
27276 .map(function (i) {
27277 return i.toLowerCase();
27278 })
27279 .indexOf(item.toLowerCase());
27280}
27281
27282/**
27283 * Validate an option
27284 * @param {Object} options Object with options
27285 * @param {string} name Name of the option to validate
27286 * @param {Array.<string>} values Array with valid values for this option
27287 */
27288function validateOption(options, name, values) {
27289 if (options[name] !== undefined && !contains(values, options[name])) {
27290 var index = findIndex(values, options[name]);
27291 if (index !== -1) {
27292 // right value, wrong casing
27293 // TODO: lower case values are deprecated since v3, remove this warning some day.
27294 console.warn('Warning: Wrong casing for configuration option "' + name + '", should be "' + values[index] + '" instead of "' + options[name] + '".');
27295
27296 options[name] = values[index]; // change the option to the right casing
27297 }
27298 else {
27299 // unknown value
27300 console.warn('Warning: Unknown value "' + options[name] + '" for configuration option "' + name + '". Available options: ' + values.map(JSON.stringify).join(', ') + '.');
27301 }
27302 }
27303}
27304
27305exports.name = 'config';
27306exports.math = true; // request the math namespace as fifth argument
27307exports.factory = factory;
27308
27309
27310/***/ }),
27311/* 159 */
27312/***/ (function(module, exports, __webpack_require__) {
27313
27314module.exports = [
27315 __webpack_require__(160), // data types (Matrix, Complex, Unit, ...)
27316 __webpack_require__(193), // constants
27317 __webpack_require__(195), // expression parsing
27318 __webpack_require__(407), // functions
27319 __webpack_require__(549), // serialization utility (math.json.reviver)
27320 __webpack_require__(551) // errors
27321];
27322
27323
27324/***/ }),
27325/* 160 */
27326/***/ (function(module, exports, __webpack_require__) {
27327
27328module.exports = [
27329 __webpack_require__(161),
27330 __webpack_require__(165),
27331 __webpack_require__(166),
27332 __webpack_require__(170),
27333 __webpack_require__(174),
27334 __webpack_require__(177),
27335 __webpack_require__(74),
27336 __webpack_require__(185),
27337 __webpack_require__(186),
27338 __webpack_require__(187)
27339];
27340
27341
27342/***/ }),
27343/* 161 */
27344/***/ (function(module, exports, __webpack_require__) {
27345
27346module.exports = [
27347 // type
27348 __webpack_require__(162),
27349
27350 // construction function
27351 __webpack_require__(164)
27352];
27353
27354
27355/***/ }),
27356/* 162 */
27357/***/ (function(module, exports, __webpack_require__) {
27358
27359var Decimal = __webpack_require__(163); // make sure to pick the es5 version
27360
27361function factory (type, config, load, typed, math) {
27362 var BigNumber = Decimal.clone({precision: config.precision});
27363
27364 /**
27365 * Attach type information
27366 */
27367 BigNumber.prototype.type = 'BigNumber';
27368 BigNumber.prototype.isBigNumber = true;
27369
27370 /**
27371 * Get a JSON representation of a BigNumber containing
27372 * type information
27373 * @returns {Object} Returns a JSON object structured as:
27374 * `{"mathjs": "BigNumber", "value": "0.2"}`
27375 */
27376 BigNumber.prototype.toJSON = function () {
27377 return {
27378 mathjs: 'BigNumber',
27379 value: this.toString()
27380 };
27381 };
27382
27383 /**
27384 * Instantiate a BigNumber from a JSON object
27385 * @param {Object} json a JSON object structured as:
27386 * `{"mathjs": "BigNumber", "value": "0.2"}`
27387 * @return {BigNumber}
27388 */
27389 BigNumber.fromJSON = function (json) {
27390 return new BigNumber(json.value);
27391 };
27392
27393 // listen for changed in the configuration, automatically apply changed precision
27394 math.on('config', function (curr, prev) {
27395 if (curr.precision !== prev.precision) {
27396 BigNumber.config({ precision: curr.precision });
27397 }
27398 });
27399
27400 return BigNumber;
27401}
27402
27403exports.name = 'BigNumber';
27404exports.path = 'type';
27405exports.factory = factory;
27406exports.math = true; // request access to the math namespace
27407
27408/***/ }),
27409/* 163 */
27410/***/ (function(module, exports, __webpack_require__) {
27411
27412var __WEBPACK_AMD_DEFINE_RESULT__;/*! decimal.js v9.0.1 https://github.com/MikeMcl/decimal.js/LICENCE */
27413;(function (globalScope) {
27414 'use strict';
27415
27416
27417 /*
27418 * decimal.js v9.0.1
27419 * An arbitrary-precision Decimal type for JavaScript.
27420 * https://github.com/MikeMcl/decimal.js
27421 * Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com>
27422 * MIT Licence
27423 */
27424
27425
27426 // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //
27427
27428
27429 // The maximum exponent magnitude.
27430 // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.
27431 var EXP_LIMIT = 9e15, // 0 to 9e15
27432
27433 // The limit on the value of `precision`, and on the value of the first argument to
27434 // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
27435 MAX_DIGITS = 1e9, // 0 to 1e9
27436
27437 // Base conversion alphabet.
27438 NUMERALS = '0123456789abcdef',
27439
27440 // The natural logarithm of 10 (1025 digits).
27441 LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',
27442
27443 // Pi (1025 digits).
27444 PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',
27445
27446
27447 // The initial configuration properties of the Decimal constructor.
27448 DEFAULTS = {
27449
27450 // These values must be integers within the stated ranges (inclusive).
27451 // Most of these values can be changed at run-time using the `Decimal.config` method.
27452
27453 // The maximum number of significant digits of the result of a calculation or base conversion.
27454 // E.g. `Decimal.config({ precision: 20 });`
27455 precision: 20, // 1 to MAX_DIGITS
27456
27457 // The rounding mode used when rounding to `precision`.
27458 //
27459 // ROUND_UP 0 Away from zero.
27460 // ROUND_DOWN 1 Towards zero.
27461 // ROUND_CEIL 2 Towards +Infinity.
27462 // ROUND_FLOOR 3 Towards -Infinity.
27463 // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.
27464 // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
27465 // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
27466 // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
27467 // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
27468 //
27469 // E.g.
27470 // `Decimal.rounding = 4;`
27471 // `Decimal.rounding = Decimal.ROUND_HALF_UP;`
27472 rounding: 4, // 0 to 8
27473
27474 // The modulo mode used when calculating the modulus: a mod n.
27475 // The quotient (q = a / n) is calculated according to the corresponding rounding mode.
27476 // The remainder (r) is calculated as: r = a - n * q.
27477 //
27478 // UP 0 The remainder is positive if the dividend is negative, else is negative.
27479 // DOWN 1 The remainder has the same sign as the dividend (JavaScript %).
27480 // FLOOR 3 The remainder has the same sign as the divisor (Python %).
27481 // HALF_EVEN 6 The IEEE 754 remainder function.
27482 // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.
27483 //
27484 // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian
27485 // division (9) are commonly used for the modulus operation. The other rounding modes can also
27486 // be used, but they may not give useful results.
27487 modulo: 1, // 0 to 9
27488
27489 // The exponent value at and beneath which `toString` returns exponential notation.
27490 // JavaScript numbers: -7
27491 toExpNeg: -7, // 0 to -EXP_LIMIT
27492
27493 // The exponent value at and above which `toString` returns exponential notation.
27494 // JavaScript numbers: 21
27495 toExpPos: 21, // 0 to EXP_LIMIT
27496
27497 // The minimum exponent value, beneath which underflow to zero occurs.
27498 // JavaScript numbers: -324 (5e-324)
27499 minE: -EXP_LIMIT, // -1 to -EXP_LIMIT
27500
27501 // The maximum exponent value, above which overflow to Infinity occurs.
27502 // JavaScript numbers: 308 (1.7976931348623157e+308)
27503 maxE: EXP_LIMIT, // 1 to EXP_LIMIT
27504
27505 // Whether to use cryptographically-secure random number generation, if available.
27506 crypto: false // true/false
27507 },
27508
27509
27510 // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //
27511
27512
27513 Decimal, inexact, noConflict, quadrant,
27514 external = true,
27515
27516 decimalError = '[DecimalError] ',
27517 invalidArgument = decimalError + 'Invalid argument: ',
27518 precisionLimitExceeded = decimalError + 'Precision limit exceeded',
27519 cryptoUnavailable = decimalError + 'crypto unavailable',
27520
27521 mathfloor = Math.floor,
27522 mathpow = Math.pow,
27523
27524 isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,
27525 isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,
27526 isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,
27527 isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
27528
27529 BASE = 1e7,
27530 LOG_BASE = 7,
27531 MAX_SAFE_INTEGER = 9007199254740991,
27532
27533 LN10_PRECISION = LN10.length - 1,
27534 PI_PRECISION = PI.length - 1,
27535
27536 // Decimal.prototype object
27537 P = { name: '[object Decimal]' };
27538
27539
27540 // Decimal prototype methods
27541
27542
27543 /*
27544 * absoluteValue abs
27545 * ceil
27546 * comparedTo cmp
27547 * cosine cos
27548 * cubeRoot cbrt
27549 * decimalPlaces dp
27550 * dividedBy div
27551 * dividedToIntegerBy divToInt
27552 * equals eq
27553 * floor
27554 * greaterThan gt
27555 * greaterThanOrEqualTo gte
27556 * hyperbolicCosine cosh
27557 * hyperbolicSine sinh
27558 * hyperbolicTangent tanh
27559 * inverseCosine acos
27560 * inverseHyperbolicCosine acosh
27561 * inverseHyperbolicSine asinh
27562 * inverseHyperbolicTangent atanh
27563 * inverseSine asin
27564 * inverseTangent atan
27565 * isFinite
27566 * isInteger isInt
27567 * isNaN
27568 * isNegative isNeg
27569 * isPositive isPos
27570 * isZero
27571 * lessThan lt
27572 * lessThanOrEqualTo lte
27573 * logarithm log
27574 * [maximum] [max]
27575 * [minimum] [min]
27576 * minus sub
27577 * modulo mod
27578 * naturalExponential exp
27579 * naturalLogarithm ln
27580 * negated neg
27581 * plus add
27582 * precision sd
27583 * round
27584 * sine sin
27585 * squareRoot sqrt
27586 * tangent tan
27587 * times mul
27588 * toBinary
27589 * toDecimalPlaces toDP
27590 * toExponential
27591 * toFixed
27592 * toFraction
27593 * toHexadecimal toHex
27594 * toNearest
27595 * toNumber
27596 * toOctal
27597 * toPower pow
27598 * toPrecision
27599 * toSignificantDigits toSD
27600 * toString
27601 * truncated trunc
27602 * valueOf toJSON
27603 */
27604
27605
27606 /*
27607 * Return a new Decimal whose value is the absolute value of this Decimal.
27608 *
27609 */
27610 P.absoluteValue = P.abs = function () {
27611 var x = new this.constructor(this);
27612 if (x.s < 0) x.s = 1;
27613 return finalise(x);
27614 };
27615
27616
27617 /*
27618 * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
27619 * direction of positive Infinity.
27620 *
27621 */
27622 P.ceil = function () {
27623 return finalise(new this.constructor(this), this.e + 1, 2);
27624 };
27625
27626
27627 /*
27628 * Return
27629 * 1 if the value of this Decimal is greater than the value of `y`,
27630 * -1 if the value of this Decimal is less than the value of `y`,
27631 * 0 if they have the same value,
27632 * NaN if the value of either Decimal is NaN.
27633 *
27634 */
27635 P.comparedTo = P.cmp = function (y) {
27636 var i, j, xdL, ydL,
27637 x = this,
27638 xd = x.d,
27639 yd = (y = new x.constructor(y)).d,
27640 xs = x.s,
27641 ys = y.s;
27642
27643 // Either NaN or ±Infinity?
27644 if (!xd || !yd) {
27645 return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;
27646 }
27647
27648 // Either zero?
27649 if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;
27650
27651 // Signs differ?
27652 if (xs !== ys) return xs;
27653
27654 // Compare exponents.
27655 if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;
27656
27657 xdL = xd.length;
27658 ydL = yd.length;
27659
27660 // Compare digit by digit.
27661 for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
27662 if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;
27663 }
27664
27665 // Compare lengths.
27666 return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;
27667 };
27668
27669
27670 /*
27671 * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.
27672 *
27673 * Domain: [-Infinity, Infinity]
27674 * Range: [-1, 1]
27675 *
27676 * cos(0) = 1
27677 * cos(-0) = 1
27678 * cos(Infinity) = NaN
27679 * cos(-Infinity) = NaN
27680 * cos(NaN) = NaN
27681 *
27682 */
27683 P.cosine = P.cos = function () {
27684 var pr, rm,
27685 x = this,
27686 Ctor = x.constructor;
27687
27688 if (!x.d) return new Ctor(NaN);
27689
27690 // cos(0) = cos(-0) = 1
27691 if (!x.d[0]) return new Ctor(1);
27692
27693 pr = Ctor.precision;
27694 rm = Ctor.rounding;
27695 Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
27696 Ctor.rounding = 1;
27697
27698 x = cosine(Ctor, toLessThanHalfPi(Ctor, x));
27699
27700 Ctor.precision = pr;
27701 Ctor.rounding = rm;
27702
27703 return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);
27704 };
27705
27706
27707 /*
27708 *
27709 * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to
27710 * `precision` significant digits using rounding mode `rounding`.
27711 *
27712 * cbrt(0) = 0
27713 * cbrt(-0) = -0
27714 * cbrt(1) = 1
27715 * cbrt(-1) = -1
27716 * cbrt(N) = N
27717 * cbrt(-I) = -I
27718 * cbrt(I) = I
27719 *
27720 * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))
27721 *
27722 */
27723 P.cubeRoot = P.cbrt = function () {
27724 var e, m, n, r, rep, s, sd, t, t3, t3plusx,
27725 x = this,
27726 Ctor = x.constructor;
27727
27728 if (!x.isFinite() || x.isZero()) return new Ctor(x);
27729 external = false;
27730
27731 // Initial estimate.
27732 s = x.s * Math.pow(x.s * x, 1 / 3);
27733
27734 // Math.cbrt underflow/overflow?
27735 // Pass x to Math.pow as integer, then adjust the exponent of the result.
27736 if (!s || Math.abs(s) == 1 / 0) {
27737 n = digitsToString(x.d);
27738 e = x.e;
27739
27740 // Adjust n exponent so it is a multiple of 3 away from x exponent.
27741 if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');
27742 s = Math.pow(n, 1 / 3);
27743
27744 // Rarely, e may be one less than the result exponent value.
27745 e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));
27746
27747 if (s == 1 / 0) {
27748 n = '5e' + e;
27749 } else {
27750 n = s.toExponential();
27751 n = n.slice(0, n.indexOf('e') + 1) + e;
27752 }
27753
27754 r = new Ctor(n);
27755 r.s = x.s;
27756 } else {
27757 r = new Ctor(s.toString());
27758 }
27759
27760 sd = (e = Ctor.precision) + 3;
27761
27762 // Halley's method.
27763 // TODO? Compare Newton's method.
27764 for (;;) {
27765 t = r;
27766 t3 = t.times(t).times(t);
27767 t3plusx = t3.plus(x);
27768 r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);
27769
27770 // TODO? Replace with for-loop and checkRoundingDigits.
27771 if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
27772 n = n.slice(sd - 3, sd + 1);
27773
27774 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999
27775 // , i.e. approaching a rounding boundary, continue the iteration.
27776 if (n == '9999' || !rep && n == '4999') {
27777
27778 // On the first iteration only, check to see if rounding up gives the exact result as the
27779 // nines may infinitely repeat.
27780 if (!rep) {
27781 finalise(t, e + 1, 0);
27782
27783 if (t.times(t).times(t).eq(x)) {
27784 r = t;
27785 break;
27786 }
27787 }
27788
27789 sd += 4;
27790 rep = 1;
27791 } else {
27792
27793 // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
27794 // If not, then there are further digits and m will be truthy.
27795 if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
27796
27797 // Truncate to the first rounding digit.
27798 finalise(r, e + 1, 1);
27799 m = !r.times(r).times(r).eq(x);
27800 }
27801
27802 break;
27803 }
27804 }
27805 }
27806
27807 external = true;
27808
27809 return finalise(r, e, Ctor.rounding, m);
27810 };
27811
27812
27813 /*
27814 * Return the number of decimal places of the value of this Decimal.
27815 *
27816 */
27817 P.decimalPlaces = P.dp = function () {
27818 var w,
27819 d = this.d,
27820 n = NaN;
27821
27822 if (d) {
27823 w = d.length - 1;
27824 n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;
27825
27826 // Subtract the number of trailing zeros of the last word.
27827 w = d[w];
27828 if (w) for (; w % 10 == 0; w /= 10) n--;
27829 if (n < 0) n = 0;
27830 }
27831
27832 return n;
27833 };
27834
27835
27836 /*
27837 * n / 0 = I
27838 * n / N = N
27839 * n / I = 0
27840 * 0 / n = 0
27841 * 0 / 0 = N
27842 * 0 / N = N
27843 * 0 / I = 0
27844 * N / n = N
27845 * N / 0 = N
27846 * N / N = N
27847 * N / I = N
27848 * I / n = I
27849 * I / 0 = I
27850 * I / N = N
27851 * I / I = N
27852 *
27853 * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to
27854 * `precision` significant digits using rounding mode `rounding`.
27855 *
27856 */
27857 P.dividedBy = P.div = function (y) {
27858 return divide(this, new this.constructor(y));
27859 };
27860
27861
27862 /*
27863 * Return a new Decimal whose value is the integer part of dividing the value of this Decimal
27864 * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.
27865 *
27866 */
27867 P.dividedToIntegerBy = P.divToInt = function (y) {
27868 var x = this,
27869 Ctor = x.constructor;
27870 return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);
27871 };
27872
27873
27874 /*
27875 * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
27876 *
27877 */
27878 P.equals = P.eq = function (y) {
27879 return this.cmp(y) === 0;
27880 };
27881
27882
27883 /*
27884 * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
27885 * direction of negative Infinity.
27886 *
27887 */
27888 P.floor = function () {
27889 return finalise(new this.constructor(this), this.e + 1, 3);
27890 };
27891
27892
27893 /*
27894 * Return true if the value of this Decimal is greater than the value of `y`, otherwise return
27895 * false.
27896 *
27897 */
27898 P.greaterThan = P.gt = function (y) {
27899 return this.cmp(y) > 0;
27900 };
27901
27902
27903 /*
27904 * Return true if the value of this Decimal is greater than or equal to the value of `y`,
27905 * otherwise return false.
27906 *
27907 */
27908 P.greaterThanOrEqualTo = P.gte = function (y) {
27909 var k = this.cmp(y);
27910 return k == 1 || k === 0;
27911 };
27912
27913
27914 /*
27915 * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this
27916 * Decimal.
27917 *
27918 * Domain: [-Infinity, Infinity]
27919 * Range: [1, Infinity]
27920 *
27921 * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...
27922 *
27923 * cosh(0) = 1
27924 * cosh(-0) = 1
27925 * cosh(Infinity) = Infinity
27926 * cosh(-Infinity) = Infinity
27927 * cosh(NaN) = NaN
27928 *
27929 * x time taken (ms) result
27930 * 1000 9 9.8503555700852349694e+433
27931 * 10000 25 4.4034091128314607936e+4342
27932 * 100000 171 1.4033316802130615897e+43429
27933 * 1000000 3817 1.5166076984010437725e+434294
27934 * 10000000 abandoned after 2 minute wait
27935 *
27936 * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))
27937 *
27938 */
27939 P.hyperbolicCosine = P.cosh = function () {
27940 var k, n, pr, rm, len,
27941 x = this,
27942 Ctor = x.constructor,
27943 one = new Ctor(1);
27944
27945 if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);
27946 if (x.isZero()) return one;
27947
27948 pr = Ctor.precision;
27949 rm = Ctor.rounding;
27950 Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
27951 Ctor.rounding = 1;
27952 len = x.d.length;
27953
27954 // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1
27955 // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))
27956
27957 // Estimate the optimum number of times to use the argument reduction.
27958 // TODO? Estimation reused from cosine() and may not be optimal here.
27959 if (len < 32) {
27960 k = Math.ceil(len / 3);
27961 n = Math.pow(4, -k).toString();
27962 } else {
27963 k = 16;
27964 n = '2.3283064365386962890625e-10';
27965 }
27966
27967 x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);
27968
27969 // Reverse argument reduction
27970 var cosh2_x,
27971 i = k,
27972 d8 = new Ctor(8);
27973 for (; i--;) {
27974 cosh2_x = x.times(x);
27975 x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));
27976 }
27977
27978 return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);
27979 };
27980
27981
27982 /*
27983 * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this
27984 * Decimal.
27985 *
27986 * Domain: [-Infinity, Infinity]
27987 * Range: [-Infinity, Infinity]
27988 *
27989 * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...
27990 *
27991 * sinh(0) = 0
27992 * sinh(-0) = -0
27993 * sinh(Infinity) = Infinity
27994 * sinh(-Infinity) = -Infinity
27995 * sinh(NaN) = NaN
27996 *
27997 * x time taken (ms)
27998 * 10 2 ms
27999 * 100 5 ms
28000 * 1000 14 ms
28001 * 10000 82 ms
28002 * 100000 886 ms 1.4033316802130615897e+43429
28003 * 200000 2613 ms
28004 * 300000 5407 ms
28005 * 400000 8824 ms
28006 * 500000 13026 ms 8.7080643612718084129e+217146
28007 * 1000000 48543 ms
28008 *
28009 * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))
28010 *
28011 */
28012 P.hyperbolicSine = P.sinh = function () {
28013 var k, pr, rm, len,
28014 x = this,
28015 Ctor = x.constructor;
28016
28017 if (!x.isFinite() || x.isZero()) return new Ctor(x);
28018
28019 pr = Ctor.precision;
28020 rm = Ctor.rounding;
28021 Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
28022 Ctor.rounding = 1;
28023 len = x.d.length;
28024
28025 if (len < 3) {
28026 x = taylorSeries(Ctor, 2, x, x, true);
28027 } else {
28028
28029 // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))
28030 // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))
28031 // 3 multiplications and 1 addition
28032
28033 // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))
28034 // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))
28035 // 4 multiplications and 2 additions
28036
28037 // Estimate the optimum number of times to use the argument reduction.
28038 k = 1.4 * Math.sqrt(len);
28039 k = k > 16 ? 16 : k | 0;
28040
28041 x = x.times(Math.pow(5, -k));
28042
28043 x = taylorSeries(Ctor, 2, x, x, true);
28044
28045 // Reverse argument reduction
28046 var sinh2_x,
28047 d5 = new Ctor(5),
28048 d16 = new Ctor(16),
28049 d20 = new Ctor(20);
28050 for (; k--;) {
28051 sinh2_x = x.times(x);
28052 x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));
28053 }
28054 }
28055
28056 Ctor.precision = pr;
28057 Ctor.rounding = rm;
28058
28059 return finalise(x, pr, rm, true);
28060 };
28061
28062
28063 /*
28064 * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this
28065 * Decimal.
28066 *
28067 * Domain: [-Infinity, Infinity]
28068 * Range: [-1, 1]
28069 *
28070 * tanh(x) = sinh(x) / cosh(x)
28071 *
28072 * tanh(0) = 0
28073 * tanh(-0) = -0
28074 * tanh(Infinity) = 1
28075 * tanh(-Infinity) = -1
28076 * tanh(NaN) = NaN
28077 *
28078 */
28079 P.hyperbolicTangent = P.tanh = function () {
28080 var pr, rm,
28081 x = this,
28082 Ctor = x.constructor;
28083
28084 if (!x.isFinite()) return new Ctor(x.s);
28085 if (x.isZero()) return new Ctor(x);
28086
28087 pr = Ctor.precision;
28088 rm = Ctor.rounding;
28089 Ctor.precision = pr + 7;
28090 Ctor.rounding = 1;
28091
28092 return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);
28093 };
28094
28095
28096 /*
28097 * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of
28098 * this Decimal.
28099 *
28100 * Domain: [-1, 1]
28101 * Range: [0, pi]
28102 *
28103 * acos(x) = pi/2 - asin(x)
28104 *
28105 * acos(0) = pi/2
28106 * acos(-0) = pi/2
28107 * acos(1) = 0
28108 * acos(-1) = pi
28109 * acos(1/2) = pi/3
28110 * acos(-1/2) = 2*pi/3
28111 * acos(|x| > 1) = NaN
28112 * acos(NaN) = NaN
28113 *
28114 */
28115 P.inverseCosine = P.acos = function () {
28116 var halfPi,
28117 x = this,
28118 Ctor = x.constructor,
28119 k = x.abs().cmp(1),
28120 pr = Ctor.precision,
28121 rm = Ctor.rounding;
28122
28123 if (k !== -1) {
28124 return k === 0
28125 // |x| is 1
28126 ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)
28127 // |x| > 1 or x is NaN
28128 : new Ctor(NaN);
28129 }
28130
28131 if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);
28132
28133 // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3
28134
28135 Ctor.precision = pr + 6;
28136 Ctor.rounding = 1;
28137
28138 x = x.asin();
28139 halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
28140
28141 Ctor.precision = pr;
28142 Ctor.rounding = rm;
28143
28144 return halfPi.minus(x);
28145 };
28146
28147
28148 /*
28149 * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the
28150 * value of this Decimal.
28151 *
28152 * Domain: [1, Infinity]
28153 * Range: [0, Infinity]
28154 *
28155 * acosh(x) = ln(x + sqrt(x^2 - 1))
28156 *
28157 * acosh(x < 1) = NaN
28158 * acosh(NaN) = NaN
28159 * acosh(Infinity) = Infinity
28160 * acosh(-Infinity) = NaN
28161 * acosh(0) = NaN
28162 * acosh(-0) = NaN
28163 * acosh(1) = 0
28164 * acosh(-1) = NaN
28165 *
28166 */
28167 P.inverseHyperbolicCosine = P.acosh = function () {
28168 var pr, rm,
28169 x = this,
28170 Ctor = x.constructor;
28171
28172 if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);
28173 if (!x.isFinite()) return new Ctor(x);
28174
28175 pr = Ctor.precision;
28176 rm = Ctor.rounding;
28177 Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;
28178 Ctor.rounding = 1;
28179 external = false;
28180
28181 x = x.times(x).minus(1).sqrt().plus(x);
28182
28183 external = true;
28184 Ctor.precision = pr;
28185 Ctor.rounding = rm;
28186
28187 return x.ln();
28188 };
28189
28190
28191 /*
28192 * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value
28193 * of this Decimal.
28194 *
28195 * Domain: [-Infinity, Infinity]
28196 * Range: [-Infinity, Infinity]
28197 *
28198 * asinh(x) = ln(x + sqrt(x^2 + 1))
28199 *
28200 * asinh(NaN) = NaN
28201 * asinh(Infinity) = Infinity
28202 * asinh(-Infinity) = -Infinity
28203 * asinh(0) = 0
28204 * asinh(-0) = -0
28205 *
28206 */
28207 P.inverseHyperbolicSine = P.asinh = function () {
28208 var pr, rm,
28209 x = this,
28210 Ctor = x.constructor;
28211
28212 if (!x.isFinite() || x.isZero()) return new Ctor(x);
28213
28214 pr = Ctor.precision;
28215 rm = Ctor.rounding;
28216 Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;
28217 Ctor.rounding = 1;
28218 external = false;
28219
28220 x = x.times(x).plus(1).sqrt().plus(x);
28221
28222 external = true;
28223 Ctor.precision = pr;
28224 Ctor.rounding = rm;
28225
28226 return x.ln();
28227 };
28228
28229
28230 /*
28231 * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the
28232 * value of this Decimal.
28233 *
28234 * Domain: [-1, 1]
28235 * Range: [-Infinity, Infinity]
28236 *
28237 * atanh(x) = 0.5 * ln((1 + x) / (1 - x))
28238 *
28239 * atanh(|x| > 1) = NaN
28240 * atanh(NaN) = NaN
28241 * atanh(Infinity) = NaN
28242 * atanh(-Infinity) = NaN
28243 * atanh(0) = 0
28244 * atanh(-0) = -0
28245 * atanh(1) = Infinity
28246 * atanh(-1) = -Infinity
28247 *
28248 */
28249 P.inverseHyperbolicTangent = P.atanh = function () {
28250 var pr, rm, wpr, xsd,
28251 x = this,
28252 Ctor = x.constructor;
28253
28254 if (!x.isFinite()) return new Ctor(NaN);
28255 if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);
28256
28257 pr = Ctor.precision;
28258 rm = Ctor.rounding;
28259 xsd = x.sd();
28260
28261 if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);
28262
28263 Ctor.precision = wpr = xsd - x.e;
28264
28265 x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);
28266
28267 Ctor.precision = pr + 4;
28268 Ctor.rounding = 1;
28269
28270 x = x.ln();
28271
28272 Ctor.precision = pr;
28273 Ctor.rounding = rm;
28274
28275 return x.times(0.5);
28276 };
28277
28278
28279 /*
28280 * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this
28281 * Decimal.
28282 *
28283 * Domain: [-Infinity, Infinity]
28284 * Range: [-pi/2, pi/2]
28285 *
28286 * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))
28287 *
28288 * asin(0) = 0
28289 * asin(-0) = -0
28290 * asin(1/2) = pi/6
28291 * asin(-1/2) = -pi/6
28292 * asin(1) = pi/2
28293 * asin(-1) = -pi/2
28294 * asin(|x| > 1) = NaN
28295 * asin(NaN) = NaN
28296 *
28297 * TODO? Compare performance of Taylor series.
28298 *
28299 */
28300 P.inverseSine = P.asin = function () {
28301 var halfPi, k,
28302 pr, rm,
28303 x = this,
28304 Ctor = x.constructor;
28305
28306 if (x.isZero()) return new Ctor(x);
28307
28308 k = x.abs().cmp(1);
28309 pr = Ctor.precision;
28310 rm = Ctor.rounding;
28311
28312 if (k !== -1) {
28313
28314 // |x| is 1
28315 if (k === 0) {
28316 halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
28317 halfPi.s = x.s;
28318 return halfPi;
28319 }
28320
28321 // |x| > 1 or x is NaN
28322 return new Ctor(NaN);
28323 }
28324
28325 // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6
28326
28327 Ctor.precision = pr + 6;
28328 Ctor.rounding = 1;
28329
28330 x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();
28331
28332 Ctor.precision = pr;
28333 Ctor.rounding = rm;
28334
28335 return x.times(2);
28336 };
28337
28338
28339 /*
28340 * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value
28341 * of this Decimal.
28342 *
28343 * Domain: [-Infinity, Infinity]
28344 * Range: [-pi/2, pi/2]
28345 *
28346 * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
28347 *
28348 * atan(0) = 0
28349 * atan(-0) = -0
28350 * atan(1) = pi/4
28351 * atan(-1) = -pi/4
28352 * atan(Infinity) = pi/2
28353 * atan(-Infinity) = -pi/2
28354 * atan(NaN) = NaN
28355 *
28356 */
28357 P.inverseTangent = P.atan = function () {
28358 var i, j, k, n, px, t, r, wpr, x2,
28359 x = this,
28360 Ctor = x.constructor,
28361 pr = Ctor.precision,
28362 rm = Ctor.rounding;
28363
28364 if (!x.isFinite()) {
28365 if (!x.s) return new Ctor(NaN);
28366 if (pr + 4 <= PI_PRECISION) {
28367 r = getPi(Ctor, pr + 4, rm).times(0.5);
28368 r.s = x.s;
28369 return r;
28370 }
28371 } else if (x.isZero()) {
28372 return new Ctor(x);
28373 } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {
28374 r = getPi(Ctor, pr + 4, rm).times(0.25);
28375 r.s = x.s;
28376 return r;
28377 }
28378
28379 Ctor.precision = wpr = pr + 10;
28380 Ctor.rounding = 1;
28381
28382 // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);
28383
28384 // Argument reduction
28385 // Ensure |x| < 0.42
28386 // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))
28387
28388 k = Math.min(28, wpr / LOG_BASE + 2 | 0);
28389
28390 for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));
28391
28392 external = false;
28393
28394 j = Math.ceil(wpr / LOG_BASE);
28395 n = 1;
28396 x2 = x.times(x);
28397 r = new Ctor(x);
28398 px = x;
28399
28400 // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
28401 for (; i !== -1;) {
28402 px = px.times(x2);
28403 t = r.minus(px.div(n += 2));
28404
28405 px = px.times(x2);
28406 r = t.plus(px.div(n += 2));
28407
28408 if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);
28409 }
28410
28411 if (k) r = r.times(2 << (k - 1));
28412
28413 external = true;
28414
28415 return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);
28416 };
28417
28418
28419 /*
28420 * Return true if the value of this Decimal is a finite number, otherwise return false.
28421 *
28422 */
28423 P.isFinite = function () {
28424 return !!this.d;
28425 };
28426
28427
28428 /*
28429 * Return true if the value of this Decimal is an integer, otherwise return false.
28430 *
28431 */
28432 P.isInteger = P.isInt = function () {
28433 return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;
28434 };
28435
28436
28437 /*
28438 * Return true if the value of this Decimal is NaN, otherwise return false.
28439 *
28440 */
28441 P.isNaN = function () {
28442 return !this.s;
28443 };
28444
28445
28446 /*
28447 * Return true if the value of this Decimal is negative, otherwise return false.
28448 *
28449 */
28450 P.isNegative = P.isNeg = function () {
28451 return this.s < 0;
28452 };
28453
28454
28455 /*
28456 * Return true if the value of this Decimal is positive, otherwise return false.
28457 *
28458 */
28459 P.isPositive = P.isPos = function () {
28460 return this.s > 0;
28461 };
28462
28463
28464 /*
28465 * Return true if the value of this Decimal is 0 or -0, otherwise return false.
28466 *
28467 */
28468 P.isZero = function () {
28469 return !!this.d && this.d[0] === 0;
28470 };
28471
28472
28473 /*
28474 * Return true if the value of this Decimal is less than `y`, otherwise return false.
28475 *
28476 */
28477 P.lessThan = P.lt = function (y) {
28478 return this.cmp(y) < 0;
28479 };
28480
28481
28482 /*
28483 * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
28484 *
28485 */
28486 P.lessThanOrEqualTo = P.lte = function (y) {
28487 return this.cmp(y) < 1;
28488 };
28489
28490
28491 /*
28492 * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`
28493 * significant digits using rounding mode `rounding`.
28494 *
28495 * If no base is specified, return log[10](arg).
28496 *
28497 * log[base](arg) = ln(arg) / ln(base)
28498 *
28499 * The result will always be correctly rounded if the base of the log is 10, and 'almost always'
28500 * otherwise:
28501 *
28502 * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen
28503 * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error
28504 * between the result and the correctly rounded result will be one ulp (unit in the last place).
28505 *
28506 * log[-b](a) = NaN
28507 * log[0](a) = NaN
28508 * log[1](a) = NaN
28509 * log[NaN](a) = NaN
28510 * log[Infinity](a) = NaN
28511 * log[b](0) = -Infinity
28512 * log[b](-0) = -Infinity
28513 * log[b](-a) = NaN
28514 * log[b](1) = 0
28515 * log[b](Infinity) = Infinity
28516 * log[b](NaN) = NaN
28517 *
28518 * [base] {number|string|Decimal} The base of the logarithm.
28519 *
28520 */
28521 P.logarithm = P.log = function (base) {
28522 var isBase10, d, denominator, k, inf, num, sd, r,
28523 arg = this,
28524 Ctor = arg.constructor,
28525 pr = Ctor.precision,
28526 rm = Ctor.rounding,
28527 guard = 5;
28528
28529 // Default base is 10.
28530 if (base == null) {
28531 base = new Ctor(10);
28532 isBase10 = true;
28533 } else {
28534 base = new Ctor(base);
28535 d = base.d;
28536
28537 // Return NaN if base is negative, or non-finite, or is 0 or 1.
28538 if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);
28539
28540 isBase10 = base.eq(10);
28541 }
28542
28543 d = arg.d;
28544
28545 // Is arg negative, non-finite, 0 or 1?
28546 if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {
28547 return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);
28548 }
28549
28550 // The result will have a non-terminating decimal expansion if base is 10 and arg is not an
28551 // integer power of 10.
28552 if (isBase10) {
28553 if (d.length > 1) {
28554 inf = true;
28555 } else {
28556 for (k = d[0]; k % 10 === 0;) k /= 10;
28557 inf = k !== 1;
28558 }
28559 }
28560
28561 external = false;
28562 sd = pr + guard;
28563 num = naturalLogarithm(arg, sd);
28564 denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
28565
28566 // The result will have 5 rounding digits.
28567 r = divide(num, denominator, sd, 1);
28568
28569 // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,
28570 // calculate 10 further digits.
28571 //
28572 // If the result is known to have an infinite decimal expansion, repeat this until it is clear
28573 // that the result is above or below the boundary. Otherwise, if after calculating the 10
28574 // further digits, the last 14 are nines, round up and assume the result is exact.
28575 // Also assume the result is exact if the last 14 are zero.
28576 //
28577 // Example of a result that will be incorrectly rounded:
28578 // log[1048576](4503599627370502) = 2.60000000000000009610279511444746...
28579 // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it
28580 // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so
28581 // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal
28582 // place is still 2.6.
28583 if (checkRoundingDigits(r.d, k = pr, rm)) {
28584
28585 do {
28586 sd += 10;
28587 num = naturalLogarithm(arg, sd);
28588 denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
28589 r = divide(num, denominator, sd, 1);
28590
28591 if (!inf) {
28592
28593 // Check for 14 nines from the 2nd rounding digit, as the first may be 4.
28594 if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {
28595 r = finalise(r, pr + 1, 0);
28596 }
28597
28598 break;
28599 }
28600 } while (checkRoundingDigits(r.d, k += 10, rm));
28601 }
28602
28603 external = true;
28604
28605 return finalise(r, pr, rm);
28606 };
28607
28608
28609 /*
28610 * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.
28611 *
28612 * arguments {number|string|Decimal}
28613 *
28614 P.max = function () {
28615 Array.prototype.push.call(arguments, this);
28616 return maxOrMin(this.constructor, arguments, 'lt');
28617 };
28618 */
28619
28620
28621 /*
28622 * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.
28623 *
28624 * arguments {number|string|Decimal}
28625 *
28626 P.min = function () {
28627 Array.prototype.push.call(arguments, this);
28628 return maxOrMin(this.constructor, arguments, 'gt');
28629 };
28630 */
28631
28632
28633 /*
28634 * n - 0 = n
28635 * n - N = N
28636 * n - I = -I
28637 * 0 - n = -n
28638 * 0 - 0 = 0
28639 * 0 - N = N
28640 * 0 - I = -I
28641 * N - n = N
28642 * N - 0 = N
28643 * N - N = N
28644 * N - I = N
28645 * I - n = I
28646 * I - 0 = I
28647 * I - N = N
28648 * I - I = N
28649 *
28650 * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`
28651 * significant digits using rounding mode `rounding`.
28652 *
28653 */
28654 P.minus = P.sub = function (y) {
28655 var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,
28656 x = this,
28657 Ctor = x.constructor;
28658
28659 y = new Ctor(y);
28660
28661 // If either is not finite...
28662 if (!x.d || !y.d) {
28663
28664 // Return NaN if either is NaN.
28665 if (!x.s || !y.s) y = new Ctor(NaN);
28666
28667 // Return y negated if x is finite and y is ±Infinity.
28668 else if (x.d) y.s = -y.s;
28669
28670 // Return x if y is finite and x is ±Infinity.
28671 // Return x if both are ±Infinity with different signs.
28672 // Return NaN if both are ±Infinity with the same sign.
28673 else y = new Ctor(y.d || x.s !== y.s ? x : NaN);
28674
28675 return y;
28676 }
28677
28678 // If signs differ...
28679 if (x.s != y.s) {
28680 y.s = -y.s;
28681 return x.plus(y);
28682 }
28683
28684 xd = x.d;
28685 yd = y.d;
28686 pr = Ctor.precision;
28687 rm = Ctor.rounding;
28688
28689 // If either is zero...
28690 if (!xd[0] || !yd[0]) {
28691
28692 // Return y negated if x is zero and y is non-zero.
28693 if (yd[0]) y.s = -y.s;
28694
28695 // Return x if y is zero and x is non-zero.
28696 else if (xd[0]) y = new Ctor(x);
28697
28698 // Return zero if both are zero.
28699 // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.
28700 else return new Ctor(rm === 3 ? -0 : 0);
28701
28702 return external ? finalise(y, pr, rm) : y;
28703 }
28704
28705 // x and y are finite, non-zero numbers with the same sign.
28706
28707 // Calculate base 1e7 exponents.
28708 e = mathfloor(y.e / LOG_BASE);
28709 xe = mathfloor(x.e / LOG_BASE);
28710
28711 xd = xd.slice();
28712 k = xe - e;
28713
28714 // If base 1e7 exponents differ...
28715 if (k) {
28716 xLTy = k < 0;
28717
28718 if (xLTy) {
28719 d = xd;
28720 k = -k;
28721 len = yd.length;
28722 } else {
28723 d = yd;
28724 e = xe;
28725 len = xd.length;
28726 }
28727
28728 // Numbers with massively different exponents would result in a very high number of
28729 // zeros needing to be prepended, but this can be avoided while still ensuring correct
28730 // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.
28731 i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;
28732
28733 if (k > i) {
28734 k = i;
28735 d.length = 1;
28736 }
28737
28738 // Prepend zeros to equalise exponents.
28739 d.reverse();
28740 for (i = k; i--;) d.push(0);
28741 d.reverse();
28742
28743 // Base 1e7 exponents equal.
28744 } else {
28745
28746 // Check digits to determine which is the bigger number.
28747
28748 i = xd.length;
28749 len = yd.length;
28750 xLTy = i < len;
28751 if (xLTy) len = i;
28752
28753 for (i = 0; i < len; i++) {
28754 if (xd[i] != yd[i]) {
28755 xLTy = xd[i] < yd[i];
28756 break;
28757 }
28758 }
28759
28760 k = 0;
28761 }
28762
28763 if (xLTy) {
28764 d = xd;
28765 xd = yd;
28766 yd = d;
28767 y.s = -y.s;
28768 }
28769
28770 len = xd.length;
28771
28772 // Append zeros to `xd` if shorter.
28773 // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.
28774 for (i = yd.length - len; i > 0; --i) xd[len++] = 0;
28775
28776 // Subtract yd from xd.
28777 for (i = yd.length; i > k;) {
28778
28779 if (xd[--i] < yd[i]) {
28780 for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;
28781 --xd[j];
28782 xd[i] += BASE;
28783 }
28784
28785 xd[i] -= yd[i];
28786 }
28787
28788 // Remove trailing zeros.
28789 for (; xd[--len] === 0;) xd.pop();
28790
28791 // Remove leading zeros and adjust exponent accordingly.
28792 for (; xd[0] === 0; xd.shift()) --e;
28793
28794 // Zero?
28795 if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);
28796
28797 y.d = xd;
28798 y.e = getBase10Exponent(xd, e);
28799
28800 return external ? finalise(y, pr, rm) : y;
28801 };
28802
28803
28804 /*
28805 * n % 0 = N
28806 * n % N = N
28807 * n % I = n
28808 * 0 % n = 0
28809 * -0 % n = -0
28810 * 0 % 0 = N
28811 * 0 % N = N
28812 * 0 % I = 0
28813 * N % n = N
28814 * N % 0 = N
28815 * N % N = N
28816 * N % I = N
28817 * I % n = N
28818 * I % 0 = N
28819 * I % N = N
28820 * I % I = N
28821 *
28822 * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to
28823 * `precision` significant digits using rounding mode `rounding`.
28824 *
28825 * The result depends on the modulo mode.
28826 *
28827 */
28828 P.modulo = P.mod = function (y) {
28829 var q,
28830 x = this,
28831 Ctor = x.constructor;
28832
28833 y = new Ctor(y);
28834
28835 // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.
28836 if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);
28837
28838 // Return x if y is ±Infinity or x is ±0.
28839 if (!y.d || x.d && !x.d[0]) {
28840 return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);
28841 }
28842
28843 // Prevent rounding of intermediate calculations.
28844 external = false;
28845
28846 if (Ctor.modulo == 9) {
28847
28848 // Euclidian division: q = sign(y) * floor(x / abs(y))
28849 // result = x - q * y where 0 <= result < abs(y)
28850 q = divide(x, y.abs(), 0, 3, 1);
28851 q.s *= y.s;
28852 } else {
28853 q = divide(x, y, 0, Ctor.modulo, 1);
28854 }
28855
28856 q = q.times(y);
28857
28858 external = true;
28859
28860 return x.minus(q);
28861 };
28862
28863
28864 /*
28865 * Return a new Decimal whose value is the natural exponential of the value of this Decimal,
28866 * i.e. the base e raised to the power the value of this Decimal, rounded to `precision`
28867 * significant digits using rounding mode `rounding`.
28868 *
28869 */
28870 P.naturalExponential = P.exp = function () {
28871 return naturalExponential(this);
28872 };
28873
28874
28875 /*
28876 * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
28877 * rounded to `precision` significant digits using rounding mode `rounding`.
28878 *
28879 */
28880 P.naturalLogarithm = P.ln = function () {
28881 return naturalLogarithm(this);
28882 };
28883
28884
28885 /*
28886 * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
28887 * -1.
28888 *
28889 */
28890 P.negated = P.neg = function () {
28891 var x = new this.constructor(this);
28892 x.s = -x.s;
28893 return finalise(x);
28894 };
28895
28896
28897 /*
28898 * n + 0 = n
28899 * n + N = N
28900 * n + I = I
28901 * 0 + n = n
28902 * 0 + 0 = 0
28903 * 0 + N = N
28904 * 0 + I = I
28905 * N + n = N
28906 * N + 0 = N
28907 * N + N = N
28908 * N + I = N
28909 * I + n = I
28910 * I + 0 = I
28911 * I + N = N
28912 * I + I = I
28913 *
28914 * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`
28915 * significant digits using rounding mode `rounding`.
28916 *
28917 */
28918 P.plus = P.add = function (y) {
28919 var carry, d, e, i, k, len, pr, rm, xd, yd,
28920 x = this,
28921 Ctor = x.constructor;
28922
28923 y = new Ctor(y);
28924
28925 // If either is not finite...
28926 if (!x.d || !y.d) {
28927
28928 // Return NaN if either is NaN.
28929 if (!x.s || !y.s) y = new Ctor(NaN);
28930
28931 // Return x if y is finite and x is ±Infinity.
28932 // Return x if both are ±Infinity with the same sign.
28933 // Return NaN if both are ±Infinity with different signs.
28934 // Return y if x is finite and y is ±Infinity.
28935 else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);
28936
28937 return y;
28938 }
28939
28940 // If signs differ...
28941 if (x.s != y.s) {
28942 y.s = -y.s;
28943 return x.minus(y);
28944 }
28945
28946 xd = x.d;
28947 yd = y.d;
28948 pr = Ctor.precision;
28949 rm = Ctor.rounding;
28950
28951 // If either is zero...
28952 if (!xd[0] || !yd[0]) {
28953
28954 // Return x if y is zero.
28955 // Return y if y is non-zero.
28956 if (!yd[0]) y = new Ctor(x);
28957
28958 return external ? finalise(y, pr, rm) : y;
28959 }
28960
28961 // x and y are finite, non-zero numbers with the same sign.
28962
28963 // Calculate base 1e7 exponents.
28964 k = mathfloor(x.e / LOG_BASE);
28965 e = mathfloor(y.e / LOG_BASE);
28966
28967 xd = xd.slice();
28968 i = k - e;
28969
28970 // If base 1e7 exponents differ...
28971 if (i) {
28972
28973 if (i < 0) {
28974 d = xd;
28975 i = -i;
28976 len = yd.length;
28977 } else {
28978 d = yd;
28979 e = k;
28980 len = xd.length;
28981 }
28982
28983 // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
28984 k = Math.ceil(pr / LOG_BASE);
28985 len = k > len ? k + 1 : len + 1;
28986
28987 if (i > len) {
28988 i = len;
28989 d.length = 1;
28990 }
28991
28992 // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
28993 d.reverse();
28994 for (; i--;) d.push(0);
28995 d.reverse();
28996 }
28997
28998 len = xd.length;
28999 i = yd.length;
29000
29001 // If yd is longer than xd, swap xd and yd so xd points to the longer array.
29002 if (len - i < 0) {
29003 i = len;
29004 d = yd;
29005 yd = xd;
29006 xd = d;
29007 }
29008
29009 // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
29010 for (carry = 0; i;) {
29011 carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
29012 xd[i] %= BASE;
29013 }
29014
29015 if (carry) {
29016 xd.unshift(carry);
29017 ++e;
29018 }
29019
29020 // Remove trailing zeros.
29021 // No need to check for zero, as +x + +y != 0 && -x + -y != 0
29022 for (len = xd.length; xd[--len] == 0;) xd.pop();
29023
29024 y.d = xd;
29025 y.e = getBase10Exponent(xd, e);
29026
29027 return external ? finalise(y, pr, rm) : y;
29028 };
29029
29030
29031 /*
29032 * Return the number of significant digits of the value of this Decimal.
29033 *
29034 * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
29035 *
29036 */
29037 P.precision = P.sd = function (z) {
29038 var k,
29039 x = this;
29040
29041 if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);
29042
29043 if (x.d) {
29044 k = getPrecision(x.d);
29045 if (z && x.e + 1 > k) k = x.e + 1;
29046 } else {
29047 k = NaN;
29048 }
29049
29050 return k;
29051 };
29052
29053
29054 /*
29055 * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
29056 * rounding mode `rounding`.
29057 *
29058 */
29059 P.round = function () {
29060 var x = this,
29061 Ctor = x.constructor;
29062
29063 return finalise(new Ctor(x), x.e + 1, Ctor.rounding);
29064 };
29065
29066
29067 /*
29068 * Return a new Decimal whose value is the sine of the value in radians of this Decimal.
29069 *
29070 * Domain: [-Infinity, Infinity]
29071 * Range: [-1, 1]
29072 *
29073 * sin(x) = x - x^3/3! + x^5/5! - ...
29074 *
29075 * sin(0) = 0
29076 * sin(-0) = -0
29077 * sin(Infinity) = NaN
29078 * sin(-Infinity) = NaN
29079 * sin(NaN) = NaN
29080 *
29081 */
29082 P.sine = P.sin = function () {
29083 var pr, rm,
29084 x = this,
29085 Ctor = x.constructor;
29086
29087 if (!x.isFinite()) return new Ctor(NaN);
29088 if (x.isZero()) return new Ctor(x);
29089
29090 pr = Ctor.precision;
29091 rm = Ctor.rounding;
29092 Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
29093 Ctor.rounding = 1;
29094
29095 x = sine(Ctor, toLessThanHalfPi(Ctor, x));
29096
29097 Ctor.precision = pr;
29098 Ctor.rounding = rm;
29099
29100 return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);
29101 };
29102
29103
29104 /*
29105 * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`
29106 * significant digits using rounding mode `rounding`.
29107 *
29108 * sqrt(-n) = N
29109 * sqrt(N) = N
29110 * sqrt(-I) = N
29111 * sqrt(I) = I
29112 * sqrt(0) = 0
29113 * sqrt(-0) = -0
29114 *
29115 */
29116 P.squareRoot = P.sqrt = function () {
29117 var m, n, sd, r, rep, t,
29118 x = this,
29119 d = x.d,
29120 e = x.e,
29121 s = x.s,
29122 Ctor = x.constructor;
29123
29124 // Negative/NaN/Infinity/zero?
29125 if (s !== 1 || !d || !d[0]) {
29126 return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);
29127 }
29128
29129 external = false;
29130
29131 // Initial estimate.
29132 s = Math.sqrt(+x);
29133
29134 // Math.sqrt underflow/overflow?
29135 // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
29136 if (s == 0 || s == 1 / 0) {
29137 n = digitsToString(d);
29138
29139 if ((n.length + e) % 2 == 0) n += '0';
29140 s = Math.sqrt(n);
29141 e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
29142
29143 if (s == 1 / 0) {
29144 n = '1e' + e;
29145 } else {
29146 n = s.toExponential();
29147 n = n.slice(0, n.indexOf('e') + 1) + e;
29148 }
29149
29150 r = new Ctor(n);
29151 } else {
29152 r = new Ctor(s.toString());
29153 }
29154
29155 sd = (e = Ctor.precision) + 3;
29156
29157 // Newton-Raphson iteration.
29158 for (;;) {
29159 t = r;
29160 r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);
29161
29162 // TODO? Replace with for-loop and checkRoundingDigits.
29163 if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
29164 n = n.slice(sd - 3, sd + 1);
29165
29166 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
29167 // 4999, i.e. approaching a rounding boundary, continue the iteration.
29168 if (n == '9999' || !rep && n == '4999') {
29169
29170 // On the first iteration only, check to see if rounding up gives the exact result as the
29171 // nines may infinitely repeat.
29172 if (!rep) {
29173 finalise(t, e + 1, 0);
29174
29175 if (t.times(t).eq(x)) {
29176 r = t;
29177 break;
29178 }
29179 }
29180
29181 sd += 4;
29182 rep = 1;
29183 } else {
29184
29185 // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
29186 // If not, then there are further digits and m will be truthy.
29187 if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
29188
29189 // Truncate to the first rounding digit.
29190 finalise(r, e + 1, 1);
29191 m = !r.times(r).eq(x);
29192 }
29193
29194 break;
29195 }
29196 }
29197 }
29198
29199 external = true;
29200
29201 return finalise(r, e, Ctor.rounding, m);
29202 };
29203
29204
29205 /*
29206 * Return a new Decimal whose value is the tangent of the value in radians of this Decimal.
29207 *
29208 * Domain: [-Infinity, Infinity]
29209 * Range: [-Infinity, Infinity]
29210 *
29211 * tan(0) = 0
29212 * tan(-0) = -0
29213 * tan(Infinity) = NaN
29214 * tan(-Infinity) = NaN
29215 * tan(NaN) = NaN
29216 *
29217 */
29218 P.tangent = P.tan = function () {
29219 var pr, rm,
29220 x = this,
29221 Ctor = x.constructor;
29222
29223 if (!x.isFinite()) return new Ctor(NaN);
29224 if (x.isZero()) return new Ctor(x);
29225
29226 pr = Ctor.precision;
29227 rm = Ctor.rounding;
29228 Ctor.precision = pr + 10;
29229 Ctor.rounding = 1;
29230
29231 x = x.sin();
29232 x.s = 1;
29233 x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);
29234
29235 Ctor.precision = pr;
29236 Ctor.rounding = rm;
29237
29238 return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);
29239 };
29240
29241
29242 /*
29243 * n * 0 = 0
29244 * n * N = N
29245 * n * I = I
29246 * 0 * n = 0
29247 * 0 * 0 = 0
29248 * 0 * N = N
29249 * 0 * I = N
29250 * N * n = N
29251 * N * 0 = N
29252 * N * N = N
29253 * N * I = N
29254 * I * n = I
29255 * I * 0 = N
29256 * I * N = N
29257 * I * I = I
29258 *
29259 * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant
29260 * digits using rounding mode `rounding`.
29261 *
29262 */
29263 P.times = P.mul = function (y) {
29264 var carry, e, i, k, r, rL, t, xdL, ydL,
29265 x = this,
29266 Ctor = x.constructor,
29267 xd = x.d,
29268 yd = (y = new Ctor(y)).d;
29269
29270 y.s *= x.s;
29271
29272 // If either is NaN, ±Infinity or ±0...
29273 if (!xd || !xd[0] || !yd || !yd[0]) {
29274
29275 return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd
29276
29277 // Return NaN if either is NaN.
29278 // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.
29279 ? NaN
29280
29281 // Return ±Infinity if either is ±Infinity.
29282 // Return ±0 if either is ±0.
29283 : !xd || !yd ? y.s / 0 : y.s * 0);
29284 }
29285
29286 e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);
29287 xdL = xd.length;
29288 ydL = yd.length;
29289
29290 // Ensure xd points to the longer array.
29291 if (xdL < ydL) {
29292 r = xd;
29293 xd = yd;
29294 yd = r;
29295 rL = xdL;
29296 xdL = ydL;
29297 ydL = rL;
29298 }
29299
29300 // Initialise the result array with zeros.
29301 r = [];
29302 rL = xdL + ydL;
29303 for (i = rL; i--;) r.push(0);
29304
29305 // Multiply!
29306 for (i = ydL; --i >= 0;) {
29307 carry = 0;
29308 for (k = xdL + i; k > i;) {
29309 t = r[k] + yd[i] * xd[k - i - 1] + carry;
29310 r[k--] = t % BASE | 0;
29311 carry = t / BASE | 0;
29312 }
29313
29314 r[k] = (r[k] + carry) % BASE | 0;
29315 }
29316
29317 // Remove trailing zeros.
29318 for (; !r[--rL];) r.pop();
29319
29320 if (carry) ++e;
29321 else r.shift();
29322
29323 y.d = r;
29324 y.e = getBase10Exponent(r, e);
29325
29326 return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;
29327 };
29328
29329
29330 /*
29331 * Return a string representing the value of this Decimal in base 2, round to `sd` significant
29332 * digits using rounding mode `rm`.
29333 *
29334 * If the optional `sd` argument is present then return binary exponential notation.
29335 *
29336 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
29337 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
29338 *
29339 */
29340 P.toBinary = function (sd, rm) {
29341 return toStringBinary(this, 2, sd, rm);
29342 };
29343
29344
29345 /*
29346 * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
29347 * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
29348 *
29349 * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
29350 *
29351 * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
29352 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
29353 *
29354 */
29355 P.toDecimalPlaces = P.toDP = function (dp, rm) {
29356 var x = this,
29357 Ctor = x.constructor;
29358
29359 x = new Ctor(x);
29360 if (dp === void 0) return x;
29361
29362 checkInt32(dp, 0, MAX_DIGITS);
29363
29364 if (rm === void 0) rm = Ctor.rounding;
29365 else checkInt32(rm, 0, 8);
29366
29367 return finalise(x, dp + x.e + 1, rm);
29368 };
29369
29370
29371 /*
29372 * Return a string representing the value of this Decimal in exponential notation rounded to
29373 * `dp` fixed decimal places using rounding mode `rounding`.
29374 *
29375 * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
29376 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
29377 *
29378 */
29379 P.toExponential = function (dp, rm) {
29380 var str,
29381 x = this,
29382 Ctor = x.constructor;
29383
29384 if (dp === void 0) {
29385 str = finiteToString(x, true);
29386 } else {
29387 checkInt32(dp, 0, MAX_DIGITS);
29388
29389 if (rm === void 0) rm = Ctor.rounding;
29390 else checkInt32(rm, 0, 8);
29391
29392 x = finalise(new Ctor(x), dp + 1, rm);
29393 str = finiteToString(x, true, dp + 1);
29394 }
29395
29396 return x.isNeg() && !x.isZero() ? '-' + str : str;
29397 };
29398
29399
29400 /*
29401 * Return a string representing the value of this Decimal in normal (fixed-point) notation to
29402 * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
29403 * omitted.
29404 *
29405 * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
29406 *
29407 * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
29408 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
29409 *
29410 * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
29411 * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
29412 * (-0).toFixed(3) is '0.000'.
29413 * (-0.5).toFixed(0) is '-0'.
29414 *
29415 */
29416 P.toFixed = function (dp, rm) {
29417 var str, y,
29418 x = this,
29419 Ctor = x.constructor;
29420
29421 if (dp === void 0) {
29422 str = finiteToString(x);
29423 } else {
29424 checkInt32(dp, 0, MAX_DIGITS);
29425
29426 if (rm === void 0) rm = Ctor.rounding;
29427 else checkInt32(rm, 0, 8);
29428
29429 y = finalise(new Ctor(x), dp + x.e + 1, rm);
29430 str = finiteToString(y, false, dp + y.e + 1);
29431 }
29432
29433 // To determine whether to add the minus sign look at the value before it was rounded,
29434 // i.e. look at `x` rather than `y`.
29435 return x.isNeg() && !x.isZero() ? '-' + str : str;
29436 };
29437
29438
29439 /*
29440 * Return an array representing the value of this Decimal as a simple fraction with an integer
29441 * numerator and an integer denominator.
29442 *
29443 * The denominator will be a positive non-zero value less than or equal to the specified maximum
29444 * denominator. If a maximum denominator is not specified, the denominator will be the lowest
29445 * value necessary to represent the number exactly.
29446 *
29447 * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.
29448 *
29449 */
29450 P.toFraction = function (maxD) {
29451 var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,
29452 x = this,
29453 xd = x.d,
29454 Ctor = x.constructor;
29455
29456 if (!xd) return new Ctor(x);
29457
29458 n1 = d0 = new Ctor(1);
29459 d1 = n0 = new Ctor(0);
29460
29461 d = new Ctor(d1);
29462 e = d.e = getPrecision(xd) - x.e - 1;
29463 k = e % LOG_BASE;
29464 d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);
29465
29466 if (maxD == null) {
29467
29468 // d is 10**e, the minimum max-denominator needed.
29469 maxD = e > 0 ? d : n1;
29470 } else {
29471 n = new Ctor(maxD);
29472 if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);
29473 maxD = n.gt(d) ? (e > 0 ? d : n1) : n;
29474 }
29475
29476 external = false;
29477 n = new Ctor(digitsToString(xd));
29478 pr = Ctor.precision;
29479 Ctor.precision = e = xd.length * LOG_BASE * 2;
29480
29481 for (;;) {
29482 q = divide(n, d, 0, 1, 1);
29483 d2 = d0.plus(q.times(d1));
29484 if (d2.cmp(maxD) == 1) break;
29485 d0 = d1;
29486 d1 = d2;
29487 d2 = n1;
29488 n1 = n0.plus(q.times(d2));
29489 n0 = d2;
29490 d2 = d;
29491 d = n.minus(q.times(d2));
29492 n = d2;
29493 }
29494
29495 d2 = divide(maxD.minus(d0), d1, 0, 1, 1);
29496 n0 = n0.plus(d2.times(n1));
29497 d0 = d0.plus(d2.times(d1));
29498 n0.s = n1.s = x.s;
29499
29500 // Determine which fraction is closer to x, n0/d0 or n1/d1?
29501 r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1
29502 ? [n1, d1] : [n0, d0];
29503
29504 Ctor.precision = pr;
29505 external = true;
29506
29507 return r;
29508 };
29509
29510
29511 /*
29512 * Return a string representing the value of this Decimal in base 16, round to `sd` significant
29513 * digits using rounding mode `rm`.
29514 *
29515 * If the optional `sd` argument is present then return binary exponential notation.
29516 *
29517 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
29518 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
29519 *
29520 */
29521 P.toHexadecimal = P.toHex = function (sd, rm) {
29522 return toStringBinary(this, 16, sd, rm);
29523 };
29524
29525
29526
29527 /*
29528 * Returns a new Decimal whose value is the nearest multiple of the magnitude of `y` to the value
29529 * of this Decimal.
29530 *
29531 * If the value of this Decimal is equidistant from two multiples of `y`, the rounding mode `rm`,
29532 * or `Decimal.rounding` if `rm` is omitted, determines the direction of the nearest multiple.
29533 *
29534 * In the context of this method, rounding mode 4 (ROUND_HALF_UP) is the same as rounding mode 0
29535 * (ROUND_UP), and so on.
29536 *
29537 * The return value will always have the same sign as this Decimal, unless either this Decimal
29538 * or `y` is NaN, in which case the return value will be also be NaN.
29539 *
29540 * The return value is not affected by the value of `precision`.
29541 *
29542 * y {number|string|Decimal} The magnitude to round to a multiple of.
29543 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
29544 *
29545 * 'toNearest() rounding mode not an integer: {rm}'
29546 * 'toNearest() rounding mode out of range: {rm}'
29547 *
29548 */
29549 P.toNearest = function (y, rm) {
29550 var x = this,
29551 Ctor = x.constructor;
29552
29553 x = new Ctor(x);
29554
29555 if (y == null) {
29556
29557 // If x is not finite, return x.
29558 if (!x.d) return x;
29559
29560 y = new Ctor(1);
29561 rm = Ctor.rounding;
29562 } else {
29563 y = new Ctor(y);
29564 if (rm !== void 0) checkInt32(rm, 0, 8);
29565
29566 // If x is not finite, return x if y is not NaN, else NaN.
29567 if (!x.d) return y.s ? x : y;
29568
29569 // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.
29570 if (!y.d) {
29571 if (y.s) y.s = x.s;
29572 return y;
29573 }
29574 }
29575
29576 // If y is not zero, calculate the nearest multiple of y to x.
29577 if (y.d[0]) {
29578 external = false;
29579 if (rm < 4) rm = [4, 5, 7, 8][rm];
29580 x = divide(x, y, 0, rm, 1).times(y);
29581 external = true;
29582 finalise(x);
29583
29584 // If y is zero, return zero with the sign of x.
29585 } else {
29586 y.s = x.s;
29587 x = y;
29588 }
29589
29590 return x;
29591 };
29592
29593
29594 /*
29595 * Return the value of this Decimal converted to a number primitive.
29596 * Zero keeps its sign.
29597 *
29598 */
29599 P.toNumber = function () {
29600 return +this;
29601 };
29602
29603
29604 /*
29605 * Return a string representing the value of this Decimal in base 8, round to `sd` significant
29606 * digits using rounding mode `rm`.
29607 *
29608 * If the optional `sd` argument is present then return binary exponential notation.
29609 *
29610 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
29611 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
29612 *
29613 */
29614 P.toOctal = function (sd, rm) {
29615 return toStringBinary(this, 8, sd, rm);
29616 };
29617
29618
29619 /*
29620 * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded
29621 * to `precision` significant digits using rounding mode `rounding`.
29622 *
29623 * ECMAScript compliant.
29624 *
29625 * pow(x, NaN) = NaN
29626 * pow(x, ±0) = 1
29627
29628 * pow(NaN, non-zero) = NaN
29629 * pow(abs(x) > 1, +Infinity) = +Infinity
29630 * pow(abs(x) > 1, -Infinity) = +0
29631 * pow(abs(x) == 1, ±Infinity) = NaN
29632 * pow(abs(x) < 1, +Infinity) = +0
29633 * pow(abs(x) < 1, -Infinity) = +Infinity
29634 * pow(+Infinity, y > 0) = +Infinity
29635 * pow(+Infinity, y < 0) = +0
29636 * pow(-Infinity, odd integer > 0) = -Infinity
29637 * pow(-Infinity, even integer > 0) = +Infinity
29638 * pow(-Infinity, odd integer < 0) = -0
29639 * pow(-Infinity, even integer < 0) = +0
29640 * pow(+0, y > 0) = +0
29641 * pow(+0, y < 0) = +Infinity
29642 * pow(-0, odd integer > 0) = -0
29643 * pow(-0, even integer > 0) = +0
29644 * pow(-0, odd integer < 0) = -Infinity
29645 * pow(-0, even integer < 0) = +Infinity
29646 * pow(finite x < 0, finite non-integer) = NaN
29647 *
29648 * For non-integer or very large exponents pow(x, y) is calculated using
29649 *
29650 * x^y = exp(y*ln(x))
29651 *
29652 * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the
29653 * probability of an incorrectly rounded result
29654 * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14
29655 * i.e. 1 in 250,000,000,000,000
29656 *
29657 * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).
29658 *
29659 * y {number|string|Decimal} The power to which to raise this Decimal.
29660 *
29661 */
29662 P.toPower = P.pow = function (y) {
29663 var e, k, pr, r, rm, s,
29664 x = this,
29665 Ctor = x.constructor,
29666 yn = +(y = new Ctor(y));
29667
29668 // Either ±Infinity, NaN or ±0?
29669 if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));
29670
29671 x = new Ctor(x);
29672
29673 if (x.eq(1)) return x;
29674
29675 pr = Ctor.precision;
29676 rm = Ctor.rounding;
29677
29678 if (y.eq(1)) return finalise(x, pr, rm);
29679
29680 // y exponent
29681 e = mathfloor(y.e / LOG_BASE);
29682
29683 // If y is a small integer use the 'exponentiation by squaring' algorithm.
29684 if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
29685 r = intPow(Ctor, x, k, pr);
29686 return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);
29687 }
29688
29689 s = x.s;
29690
29691 // if x is negative
29692 if (s < 0) {
29693
29694 // if y is not an integer
29695 if (e < y.d.length - 1) return new Ctor(NaN);
29696
29697 // Result is positive if x is negative and the last digit of integer y is even.
29698 if ((y.d[e] & 1) == 0) s = 1;
29699
29700 // if x.eq(-1)
29701 if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {
29702 x.s = s;
29703 return x;
29704 }
29705 }
29706
29707 // Estimate result exponent.
29708 // x^y = 10^e, where e = y * log10(x)
29709 // log10(x) = log10(x_significand) + x_exponent
29710 // log10(x_significand) = ln(x_significand) / ln(10)
29711 k = mathpow(+x, yn);
29712 e = k == 0 || !isFinite(k)
29713 ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))
29714 : new Ctor(k + '').e;
29715
29716 // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.
29717
29718 // Overflow/underflow?
29719 if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);
29720
29721 external = false;
29722 Ctor.rounding = x.s = 1;
29723
29724 // Estimate the extra guard digits needed to ensure five correct rounding digits from
29725 // naturalLogarithm(x). Example of failure without these extra digits (precision: 10):
29726 // new Decimal(2.32456).pow('2087987436534566.46411')
29727 // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815
29728 k = Math.min(12, (e + '').length);
29729
29730 // r = x^y = exp(y*ln(x))
29731 r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);
29732
29733 // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)
29734 if (r.d) {
29735
29736 // Truncate to the required precision plus five rounding digits.
29737 r = finalise(r, pr + 5, 1);
29738
29739 // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate
29740 // the result.
29741 if (checkRoundingDigits(r.d, pr, rm)) {
29742 e = pr + 10;
29743
29744 // Truncate to the increased precision plus five rounding digits.
29745 r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);
29746
29747 // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).
29748 if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {
29749 r = finalise(r, pr + 1, 0);
29750 }
29751 }
29752 }
29753
29754 r.s = s;
29755 external = true;
29756 Ctor.rounding = rm;
29757
29758 return finalise(r, pr, rm);
29759 };
29760
29761
29762 /*
29763 * Return a string representing the value of this Decimal rounded to `sd` significant digits
29764 * using rounding mode `rounding`.
29765 *
29766 * Return exponential notation if `sd` is less than the number of digits necessary to represent
29767 * the integer part of the value in normal notation.
29768 *
29769 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
29770 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
29771 *
29772 */
29773 P.toPrecision = function (sd, rm) {
29774 var str,
29775 x = this,
29776 Ctor = x.constructor;
29777
29778 if (sd === void 0) {
29779 str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
29780 } else {
29781 checkInt32(sd, 1, MAX_DIGITS);
29782
29783 if (rm === void 0) rm = Ctor.rounding;
29784 else checkInt32(rm, 0, 8);
29785
29786 x = finalise(new Ctor(x), sd, rm);
29787 str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);
29788 }
29789
29790 return x.isNeg() && !x.isZero() ? '-' + str : str;
29791 };
29792
29793
29794 /*
29795 * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
29796 * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
29797 * omitted.
29798 *
29799 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
29800 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
29801 *
29802 * 'toSD() digits out of range: {sd}'
29803 * 'toSD() digits not an integer: {sd}'
29804 * 'toSD() rounding mode not an integer: {rm}'
29805 * 'toSD() rounding mode out of range: {rm}'
29806 *
29807 */
29808 P.toSignificantDigits = P.toSD = function (sd, rm) {
29809 var x = this,
29810 Ctor = x.constructor;
29811
29812 if (sd === void 0) {
29813 sd = Ctor.precision;
29814 rm = Ctor.rounding;
29815 } else {
29816 checkInt32(sd, 1, MAX_DIGITS);
29817
29818 if (rm === void 0) rm = Ctor.rounding;
29819 else checkInt32(rm, 0, 8);
29820 }
29821
29822 return finalise(new Ctor(x), sd, rm);
29823 };
29824
29825
29826 /*
29827 * Return a string representing the value of this Decimal.
29828 *
29829 * Return exponential notation if this Decimal has a positive exponent equal to or greater than
29830 * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
29831 *
29832 */
29833 P.toString = function () {
29834 var x = this,
29835 Ctor = x.constructor,
29836 str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
29837
29838 return x.isNeg() && !x.isZero() ? '-' + str : str;
29839 };
29840
29841
29842 /*
29843 * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.
29844 *
29845 */
29846 P.truncated = P.trunc = function () {
29847 return finalise(new this.constructor(this), this.e + 1, 1);
29848 };
29849
29850
29851 /*
29852 * Return a string representing the value of this Decimal.
29853 * Unlike `toString`, negative zero will include the minus sign.
29854 *
29855 */
29856 P.valueOf = P.toJSON = function () {
29857 var x = this,
29858 Ctor = x.constructor,
29859 str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
29860
29861 return x.isNeg() ? '-' + str : str;
29862 };
29863
29864
29865 /*
29866 // Add aliases to match BigDecimal method names.
29867 // P.add = P.plus;
29868 P.subtract = P.minus;
29869 P.multiply = P.times;
29870 P.divide = P.div;
29871 P.remainder = P.mod;
29872 P.compareTo = P.cmp;
29873 P.negate = P.neg;
29874 */
29875
29876
29877 // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
29878
29879
29880 /*
29881 * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,
29882 * finiteToString, naturalExponential, naturalLogarithm
29883 * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,
29884 * P.toPrecision, P.toSignificantDigits, toStringBinary, random
29885 * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm
29886 * convertBase toStringBinary, parseOther
29887 * cos P.cos
29888 * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,
29889 * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,
29890 * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,
29891 * taylorSeries, atan2, parseOther
29892 * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,
29893 * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,
29894 * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,
29895 * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,
29896 * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,
29897 * P.truncated, divide, getLn10, getPi, naturalExponential,
29898 * naturalLogarithm, ceil, floor, round, trunc
29899 * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,
29900 * toStringBinary
29901 * getBase10Exponent P.minus, P.plus, P.times, parseOther
29902 * getLn10 P.logarithm, naturalLogarithm
29903 * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2
29904 * getPrecision P.precision, P.toFraction
29905 * getZeroString digitsToString, finiteToString
29906 * intPow P.toPower, parseOther
29907 * isOdd toLessThanHalfPi
29908 * maxOrMin max, min
29909 * naturalExponential P.naturalExponential, P.toPower
29910 * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,
29911 * P.toPower, naturalExponential
29912 * nonFiniteToString finiteToString, toStringBinary
29913 * parseDecimal Decimal
29914 * parseOther Decimal
29915 * sin P.sin
29916 * taylorSeries P.cosh, P.sinh, cos, sin
29917 * toLessThanHalfPi P.cos, P.sin
29918 * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal
29919 * truncate intPow
29920 *
29921 * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,
29922 * naturalLogarithm, config, parseOther, random, Decimal
29923 */
29924
29925
29926 function digitsToString(d) {
29927 var i, k, ws,
29928 indexOfLastWord = d.length - 1,
29929 str = '',
29930 w = d[0];
29931
29932 if (indexOfLastWord > 0) {
29933 str += w;
29934 for (i = 1; i < indexOfLastWord; i++) {
29935 ws = d[i] + '';
29936 k = LOG_BASE - ws.length;
29937 if (k) str += getZeroString(k);
29938 str += ws;
29939 }
29940
29941 w = d[i];
29942 ws = w + '';
29943 k = LOG_BASE - ws.length;
29944 if (k) str += getZeroString(k);
29945 } else if (w === 0) {
29946 return '0';
29947 }
29948
29949 // Remove trailing zeros of last w.
29950 for (; w % 10 === 0;) w /= 10;
29951
29952 return str + w;
29953 }
29954
29955
29956 function checkInt32(i, min, max) {
29957 if (i !== ~~i || i < min || i > max) {
29958 throw Error(invalidArgument + i);
29959 }
29960 }
29961
29962
29963 /*
29964 * Check 5 rounding digits if `repeating` is null, 4 otherwise.
29965 * `repeating == null` if caller is `log` or `pow`,
29966 * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.
29967 */
29968 function checkRoundingDigits(d, i, rm, repeating) {
29969 var di, k, r, rd;
29970
29971 // Get the length of the first word of the array d.
29972 for (k = d[0]; k >= 10; k /= 10) --i;
29973
29974 // Is the rounding digit in the first word of d?
29975 if (--i < 0) {
29976 i += LOG_BASE;
29977 di = 0;
29978 } else {
29979 di = Math.ceil((i + 1) / LOG_BASE);
29980 i %= LOG_BASE;
29981 }
29982
29983 // i is the index (0 - 6) of the rounding digit.
29984 // E.g. if within the word 3487563 the first rounding digit is 5,
29985 // then i = 4, k = 1000, rd = 3487563 % 1000 = 563
29986 k = mathpow(10, LOG_BASE - i);
29987 rd = d[di] % k | 0;
29988
29989 if (repeating == null) {
29990 if (i < 3) {
29991 if (i == 0) rd = rd / 100 | 0;
29992 else if (i == 1) rd = rd / 10 | 0;
29993 r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;
29994 } else {
29995 r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&
29996 (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||
29997 (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;
29998 }
29999 } else {
30000 if (i < 4) {
30001 if (i == 0) rd = rd / 1000 | 0;
30002 else if (i == 1) rd = rd / 100 | 0;
30003 else if (i == 2) rd = rd / 10 | 0;
30004 r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;
30005 } else {
30006 r = ((repeating || rm < 4) && rd + 1 == k ||
30007 (!repeating && rm > 3) && rd + 1 == k / 2) &&
30008 (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;
30009 }
30010 }
30011
30012 return r;
30013 }
30014
30015
30016 // Convert string of `baseIn` to an array of numbers of `baseOut`.
30017 // Eg. convertBase('255', 10, 16) returns [15, 15].
30018 // Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
30019 function convertBase(str, baseIn, baseOut) {
30020 var j,
30021 arr = [0],
30022 arrL,
30023 i = 0,
30024 strL = str.length;
30025
30026 for (; i < strL;) {
30027 for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;
30028 arr[0] += NUMERALS.indexOf(str.charAt(i++));
30029 for (j = 0; j < arr.length; j++) {
30030 if (arr[j] > baseOut - 1) {
30031 if (arr[j + 1] === void 0) arr[j + 1] = 0;
30032 arr[j + 1] += arr[j] / baseOut | 0;
30033 arr[j] %= baseOut;
30034 }
30035 }
30036 }
30037
30038 return arr.reverse();
30039 }
30040
30041
30042 /*
30043 * cos(x) = 1 - x^2/2! + x^4/4! - ...
30044 * |x| < pi/2
30045 *
30046 */
30047 function cosine(Ctor, x) {
30048 var k, y,
30049 len = x.d.length;
30050
30051 // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1
30052 // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1
30053
30054 // Estimate the optimum number of times to use the argument reduction.
30055 if (len < 32) {
30056 k = Math.ceil(len / 3);
30057 y = Math.pow(4, -k).toString();
30058 } else {
30059 k = 16;
30060 y = '2.3283064365386962890625e-10';
30061 }
30062
30063 Ctor.precision += k;
30064
30065 x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));
30066
30067 // Reverse argument reduction
30068 for (var i = k; i--;) {
30069 var cos2x = x.times(x);
30070 x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);
30071 }
30072
30073 Ctor.precision -= k;
30074
30075 return x;
30076 }
30077
30078
30079 /*
30080 * Perform division in the specified base.
30081 */
30082 var divide = (function () {
30083
30084 // Assumes non-zero x and k, and hence non-zero result.
30085 function multiplyInteger(x, k, base) {
30086 var temp,
30087 carry = 0,
30088 i = x.length;
30089
30090 for (x = x.slice(); i--;) {
30091 temp = x[i] * k + carry;
30092 x[i] = temp % base | 0;
30093 carry = temp / base | 0;
30094 }
30095
30096 if (carry) x.unshift(carry);
30097
30098 return x;
30099 }
30100
30101 function compare(a, b, aL, bL) {
30102 var i, r;
30103
30104 if (aL != bL) {
30105 r = aL > bL ? 1 : -1;
30106 } else {
30107 for (i = r = 0; i < aL; i++) {
30108 if (a[i] != b[i]) {
30109 r = a[i] > b[i] ? 1 : -1;
30110 break;
30111 }
30112 }
30113 }
30114
30115 return r;
30116 }
30117
30118 function subtract(a, b, aL, base) {
30119 var i = 0;
30120
30121 // Subtract b from a.
30122 for (; aL--;) {
30123 a[aL] -= i;
30124 i = a[aL] < b[aL] ? 1 : 0;
30125 a[aL] = i * base + a[aL] - b[aL];
30126 }
30127
30128 // Remove leading zeros.
30129 for (; !a[0] && a.length > 1;) a.shift();
30130 }
30131
30132 return function (x, y, pr, rm, dp, base) {
30133 var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,
30134 yL, yz,
30135 Ctor = x.constructor,
30136 sign = x.s == y.s ? 1 : -1,
30137 xd = x.d,
30138 yd = y.d;
30139
30140 // Either NaN, Infinity or 0?
30141 if (!xd || !xd[0] || !yd || !yd[0]) {
30142
30143 return new Ctor(// Return NaN if either NaN, or both Infinity or 0.
30144 !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :
30145
30146 // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.
30147 xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);
30148 }
30149
30150 if (base) {
30151 logBase = 1;
30152 e = x.e - y.e;
30153 } else {
30154 base = BASE;
30155 logBase = LOG_BASE;
30156 e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);
30157 }
30158
30159 yL = yd.length;
30160 xL = xd.length;
30161 q = new Ctor(sign);
30162 qd = q.d = [];
30163
30164 // Result exponent may be one less than e.
30165 // The digit array of a Decimal from toStringBinary may have trailing zeros.
30166 for (i = 0; yd[i] == (xd[i] || 0); i++);
30167
30168 if (yd[i] > (xd[i] || 0)) e--;
30169
30170 if (pr == null) {
30171 sd = pr = Ctor.precision;
30172 rm = Ctor.rounding;
30173 } else if (dp) {
30174 sd = pr + (x.e - y.e) + 1;
30175 } else {
30176 sd = pr;
30177 }
30178
30179 if (sd < 0) {
30180 qd.push(1);
30181 more = true;
30182 } else {
30183
30184 // Convert precision in number of base 10 digits to base 1e7 digits.
30185 sd = sd / logBase + 2 | 0;
30186 i = 0;
30187
30188 // divisor < 1e7
30189 if (yL == 1) {
30190 k = 0;
30191 yd = yd[0];
30192 sd++;
30193
30194 // k is the carry.
30195 for (; (i < xL || k) && sd--; i++) {
30196 t = k * base + (xd[i] || 0);
30197 qd[i] = t / yd | 0;
30198 k = t % yd | 0;
30199 }
30200
30201 more = k || i < xL;
30202
30203 // divisor >= 1e7
30204 } else {
30205
30206 // Normalise xd and yd so highest order digit of yd is >= base/2
30207 k = base / (yd[0] + 1) | 0;
30208
30209 if (k > 1) {
30210 yd = multiplyInteger(yd, k, base);
30211 xd = multiplyInteger(xd, k, base);
30212 yL = yd.length;
30213 xL = xd.length;
30214 }
30215
30216 xi = yL;
30217 rem = xd.slice(0, yL);
30218 remL = rem.length;
30219
30220 // Add zeros to make remainder as long as divisor.
30221 for (; remL < yL;) rem[remL++] = 0;
30222
30223 yz = yd.slice();
30224 yz.unshift(0);
30225 yd0 = yd[0];
30226
30227 if (yd[1] >= base / 2) ++yd0;
30228
30229 do {
30230 k = 0;
30231
30232 // Compare divisor and remainder.
30233 cmp = compare(yd, rem, yL, remL);
30234
30235 // If divisor < remainder.
30236 if (cmp < 0) {
30237
30238 // Calculate trial digit, k.
30239 rem0 = rem[0];
30240 if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
30241
30242 // k will be how many times the divisor goes into the current remainder.
30243 k = rem0 / yd0 | 0;
30244
30245 // Algorithm:
30246 // 1. product = divisor * trial digit (k)
30247 // 2. if product > remainder: product -= divisor, k--
30248 // 3. remainder -= product
30249 // 4. if product was < remainder at 2:
30250 // 5. compare new remainder and divisor
30251 // 6. If remainder > divisor: remainder -= divisor, k++
30252
30253 if (k > 1) {
30254 if (k >= base) k = base - 1;
30255
30256 // product = divisor * trial digit.
30257 prod = multiplyInteger(yd, k, base);
30258 prodL = prod.length;
30259 remL = rem.length;
30260
30261 // Compare product and remainder.
30262 cmp = compare(prod, rem, prodL, remL);
30263
30264 // product > remainder.
30265 if (cmp == 1) {
30266 k--;
30267
30268 // Subtract divisor from product.
30269 subtract(prod, yL < prodL ? yz : yd, prodL, base);
30270 }
30271 } else {
30272
30273 // cmp is -1.
30274 // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1
30275 // to avoid it. If k is 1 there is a need to compare yd and rem again below.
30276 if (k == 0) cmp = k = 1;
30277 prod = yd.slice();
30278 }
30279
30280 prodL = prod.length;
30281 if (prodL < remL) prod.unshift(0);
30282
30283 // Subtract product from remainder.
30284 subtract(rem, prod, remL, base);
30285
30286 // If product was < previous remainder.
30287 if (cmp == -1) {
30288 remL = rem.length;
30289
30290 // Compare divisor and new remainder.
30291 cmp = compare(yd, rem, yL, remL);
30292
30293 // If divisor < new remainder, subtract divisor from remainder.
30294 if (cmp < 1) {
30295 k++;
30296
30297 // Subtract divisor from remainder.
30298 subtract(rem, yL < remL ? yz : yd, remL, base);
30299 }
30300 }
30301
30302 remL = rem.length;
30303 } else if (cmp === 0) {
30304 k++;
30305 rem = [0];
30306 } // if cmp === 1, k will be 0
30307
30308 // Add the next digit, k, to the result array.
30309 qd[i++] = k;
30310
30311 // Update the remainder.
30312 if (cmp && rem[0]) {
30313 rem[remL++] = xd[xi] || 0;
30314 } else {
30315 rem = [xd[xi]];
30316 remL = 1;
30317 }
30318
30319 } while ((xi++ < xL || rem[0] !== void 0) && sd--);
30320
30321 more = rem[0] !== void 0;
30322 }
30323
30324 // Leading zero?
30325 if (!qd[0]) qd.shift();
30326 }
30327
30328 // logBase is 1 when divide is being used for base conversion.
30329 if (logBase == 1) {
30330 q.e = e;
30331 inexact = more;
30332 } else {
30333
30334 // To calculate q.e, first get the number of digits of qd[0].
30335 for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;
30336 q.e = i + e * logBase - 1;
30337
30338 finalise(q, dp ? pr + q.e + 1 : pr, rm, more);
30339 }
30340
30341 return q;
30342 };
30343 })();
30344
30345
30346 /*
30347 * Round `x` to `sd` significant digits using rounding mode `rm`.
30348 * Check for over/under-flow.
30349 */
30350 function finalise(x, sd, rm, isTruncated) {
30351 var digits, i, j, k, rd, roundUp, w, xd, xdi,
30352 Ctor = x.constructor;
30353
30354 // Don't round if sd is null or undefined.
30355 out: if (sd != null) {
30356 xd = x.d;
30357
30358 // Infinity/NaN.
30359 if (!xd) return x;
30360
30361 // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.
30362 // w: the word of xd containing rd, a base 1e7 number.
30363 // xdi: the index of w within xd.
30364 // digits: the number of digits of w.
30365 // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if
30366 // they had leading zeros)
30367 // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).
30368
30369 // Get the length of the first word of the digits array xd.
30370 for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;
30371 i = sd - digits;
30372
30373 // Is the rounding digit in the first word of xd?
30374 if (i < 0) {
30375 i += LOG_BASE;
30376 j = sd;
30377 w = xd[xdi = 0];
30378
30379 // Get the rounding digit at index j of w.
30380 rd = w / mathpow(10, digits - j - 1) % 10 | 0;
30381 } else {
30382 xdi = Math.ceil((i + 1) / LOG_BASE);
30383 k = xd.length;
30384 if (xdi >= k) {
30385 if (isTruncated) {
30386
30387 // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.
30388 for (; k++ <= xdi;) xd.push(0);
30389 w = rd = 0;
30390 digits = 1;
30391 i %= LOG_BASE;
30392 j = i - LOG_BASE + 1;
30393 } else {
30394 break out;
30395 }
30396 } else {
30397 w = k = xd[xdi];
30398
30399 // Get the number of digits of w.
30400 for (digits = 1; k >= 10; k /= 10) digits++;
30401
30402 // Get the index of rd within w.
30403 i %= LOG_BASE;
30404
30405 // Get the index of rd within w, adjusted for leading zeros.
30406 // The number of leading zeros of w is given by LOG_BASE - digits.
30407 j = i - LOG_BASE + digits;
30408
30409 // Get the rounding digit at index j of w.
30410 rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;
30411 }
30412 }
30413
30414 // Are there any non-zero digits after the rounding digit?
30415 isTruncated = isTruncated || sd < 0 ||
30416 xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));
30417
30418 // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right
30419 // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression
30420 // will give 714.
30421
30422 roundUp = rm < 4
30423 ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
30424 : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&
30425
30426 // Check whether the digit to the left of the rounding digit is odd.
30427 ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||
30428 rm == (x.s < 0 ? 8 : 7));
30429
30430 if (sd < 1 || !xd[0]) {
30431 xd.length = 0;
30432 if (roundUp) {
30433
30434 // Convert sd to decimal places.
30435 sd -= x.e + 1;
30436
30437 // 1, 0.1, 0.01, 0.001, 0.0001 etc.
30438 xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
30439 x.e = -sd || 0;
30440 } else {
30441
30442 // Zero.
30443 xd[0] = x.e = 0;
30444 }
30445
30446 return x;
30447 }
30448
30449 // Remove excess digits.
30450 if (i == 0) {
30451 xd.length = xdi;
30452 k = 1;
30453 xdi--;
30454 } else {
30455 xd.length = xdi + 1;
30456 k = mathpow(10, LOG_BASE - i);
30457
30458 // E.g. 56700 becomes 56000 if 7 is the rounding digit.
30459 // j > 0 means i > number of leading zeros of w.
30460 xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;
30461 }
30462
30463 if (roundUp) {
30464 for (;;) {
30465
30466 // Is the digit to be rounded up in the first word of xd?
30467 if (xdi == 0) {
30468
30469 // i will be the length of xd[0] before k is added.
30470 for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;
30471 j = xd[0] += k;
30472 for (k = 1; j >= 10; j /= 10) k++;
30473
30474 // if i != k the length has increased.
30475 if (i != k) {
30476 x.e++;
30477 if (xd[0] == BASE) xd[0] = 1;
30478 }
30479
30480 break;
30481 } else {
30482 xd[xdi] += k;
30483 if (xd[xdi] != BASE) break;
30484 xd[xdi--] = 0;
30485 k = 1;
30486 }
30487 }
30488 }
30489
30490 // Remove trailing zeros.
30491 for (i = xd.length; xd[--i] === 0;) xd.pop();
30492 }
30493
30494 if (external) {
30495
30496 // Overflow?
30497 if (x.e > Ctor.maxE) {
30498
30499 // Infinity.
30500 x.d = null;
30501 x.e = NaN;
30502
30503 // Underflow?
30504 } else if (x.e < Ctor.minE) {
30505
30506 // Zero.
30507 x.e = 0;
30508 x.d = [0];
30509 // Ctor.underflow = true;
30510 } // else Ctor.underflow = false;
30511 }
30512
30513 return x;
30514 }
30515
30516
30517 function finiteToString(x, isExp, sd) {
30518 if (!x.isFinite()) return nonFiniteToString(x);
30519 var k,
30520 e = x.e,
30521 str = digitsToString(x.d),
30522 len = str.length;
30523
30524 if (isExp) {
30525 if (sd && (k = sd - len) > 0) {
30526 str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);
30527 } else if (len > 1) {
30528 str = str.charAt(0) + '.' + str.slice(1);
30529 }
30530
30531 str = str + (x.e < 0 ? 'e' : 'e+') + x.e;
30532 } else if (e < 0) {
30533 str = '0.' + getZeroString(-e - 1) + str;
30534 if (sd && (k = sd - len) > 0) str += getZeroString(k);
30535 } else if (e >= len) {
30536 str += getZeroString(e + 1 - len);
30537 if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);
30538 } else {
30539 if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);
30540 if (sd && (k = sd - len) > 0) {
30541 if (e + 1 === len) str += '.';
30542 str += getZeroString(k);
30543 }
30544 }
30545
30546 return str;
30547 }
30548
30549
30550 // Calculate the base 10 exponent from the base 1e7 exponent.
30551 function getBase10Exponent(digits, e) {
30552 var w = digits[0];
30553
30554 // Add the number of digits of the first word of the digits array.
30555 for ( e *= LOG_BASE; w >= 10; w /= 10) e++;
30556 return e;
30557 }
30558
30559
30560 function getLn10(Ctor, sd, pr) {
30561 if (sd > LN10_PRECISION) {
30562
30563 // Reset global state in case the exception is caught.
30564 external = true;
30565 if (pr) Ctor.precision = pr;
30566 throw Error(precisionLimitExceeded);
30567 }
30568 return finalise(new Ctor(LN10), sd, 1, true);
30569 }
30570
30571
30572 function getPi(Ctor, sd, rm) {
30573 if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);
30574 return finalise(new Ctor(PI), sd, rm, true);
30575 }
30576
30577
30578 function getPrecision(digits) {
30579 var w = digits.length - 1,
30580 len = w * LOG_BASE + 1;
30581
30582 w = digits[w];
30583
30584 // If non-zero...
30585 if (w) {
30586
30587 // Subtract the number of trailing zeros of the last word.
30588 for (; w % 10 == 0; w /= 10) len--;
30589
30590 // Add the number of digits of the first word.
30591 for (w = digits[0]; w >= 10; w /= 10) len++;
30592 }
30593
30594 return len;
30595 }
30596
30597
30598 function getZeroString(k) {
30599 var zs = '';
30600 for (; k--;) zs += '0';
30601 return zs;
30602 }
30603
30604
30605 /*
30606 * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an
30607 * integer of type number.
30608 *
30609 * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.
30610 *
30611 */
30612 function intPow(Ctor, x, n, pr) {
30613 var isTruncated,
30614 r = new Ctor(1),
30615
30616 // Max n of 9007199254740991 takes 53 loop iterations.
30617 // Maximum digits array length; leaves [28, 34] guard digits.
30618 k = Math.ceil(pr / LOG_BASE + 4);
30619
30620 external = false;
30621
30622 for (;;) {
30623 if (n % 2) {
30624 r = r.times(x);
30625 if (truncate(r.d, k)) isTruncated = true;
30626 }
30627
30628 n = mathfloor(n / 2);
30629 if (n === 0) {
30630
30631 // To ensure correct rounding when r.d is truncated, increment the last word if it is zero.
30632 n = r.d.length - 1;
30633 if (isTruncated && r.d[n] === 0) ++r.d[n];
30634 break;
30635 }
30636
30637 x = x.times(x);
30638 truncate(x.d, k);
30639 }
30640
30641 external = true;
30642
30643 return r;
30644 }
30645
30646
30647 function isOdd(n) {
30648 return n.d[n.d.length - 1] & 1;
30649 }
30650
30651
30652 /*
30653 * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.
30654 */
30655 function maxOrMin(Ctor, args, ltgt) {
30656 var y,
30657 x = new Ctor(args[0]),
30658 i = 0;
30659
30660 for (; ++i < args.length;) {
30661 y = new Ctor(args[i]);
30662 if (!y.s) {
30663 x = y;
30664 break;
30665 } else if (x[ltgt](y)) {
30666 x = y;
30667 }
30668 }
30669
30670 return x;
30671 }
30672
30673
30674 /*
30675 * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant
30676 * digits.
30677 *
30678 * Taylor/Maclaurin series.
30679 *
30680 * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
30681 *
30682 * Argument reduction:
30683 * Repeat x = x / 32, k += 5, until |x| < 0.1
30684 * exp(x) = exp(x / 2^k)^(2^k)
30685 *
30686 * Previously, the argument was initially reduced by
30687 * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)
30688 * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
30689 * found to be slower than just dividing repeatedly by 32 as above.
30690 *
30691 * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000
30692 * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000
30693 * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)
30694 *
30695 * exp(Infinity) = Infinity
30696 * exp(-Infinity) = 0
30697 * exp(NaN) = NaN
30698 * exp(±0) = 1
30699 *
30700 * exp(x) is non-terminating for any finite, non-zero x.
30701 *
30702 * The result will always be correctly rounded.
30703 *
30704 */
30705 function naturalExponential(x, sd) {
30706 var denominator, guard, j, pow, sum, t, wpr,
30707 rep = 0,
30708 i = 0,
30709 k = 0,
30710 Ctor = x.constructor,
30711 rm = Ctor.rounding,
30712 pr = Ctor.precision;
30713
30714 // 0/NaN/Infinity?
30715 if (!x.d || !x.d[0] || x.e > 17) {
30716
30717 return new Ctor(x.d
30718 ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0
30719 : x.s ? x.s < 0 ? 0 : x : 0 / 0);
30720 }
30721
30722 if (sd == null) {
30723 external = false;
30724 wpr = pr;
30725 } else {
30726 wpr = sd;
30727 }
30728
30729 t = new Ctor(0.03125);
30730
30731 // while abs(x) >= 0.1
30732 while (x.e > -2) {
30733
30734 // x = x / 2^5
30735 x = x.times(t);
30736 k += 5;
30737 }
30738
30739 // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision
30740 // necessary to ensure the first 4 rounding digits are correct.
30741 guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
30742 wpr += guard;
30743 denominator = pow = sum = new Ctor(1);
30744 Ctor.precision = wpr;
30745
30746 for (;;) {
30747 pow = finalise(pow.times(x), wpr, 1);
30748 denominator = denominator.times(++i);
30749 t = sum.plus(divide(pow, denominator, wpr, 1));
30750
30751 if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
30752 j = k;
30753 while (j--) sum = finalise(sum.times(sum), wpr, 1);
30754
30755 // Check to see if the first 4 rounding digits are [49]999.
30756 // If so, repeat the summation with a higher precision, otherwise
30757 // e.g. with precision: 18, rounding: 1
30758 // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)
30759 // `wpr - guard` is the index of first rounding digit.
30760 if (sd == null) {
30761
30762 if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
30763 Ctor.precision = wpr += 10;
30764 denominator = pow = t = new Ctor(1);
30765 i = 0;
30766 rep++;
30767 } else {
30768 return finalise(sum, Ctor.precision = pr, rm, external = true);
30769 }
30770 } else {
30771 Ctor.precision = pr;
30772 return sum;
30773 }
30774 }
30775
30776 sum = t;
30777 }
30778 }
30779
30780
30781 /*
30782 * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant
30783 * digits.
30784 *
30785 * ln(-n) = NaN
30786 * ln(0) = -Infinity
30787 * ln(-0) = -Infinity
30788 * ln(1) = 0
30789 * ln(Infinity) = Infinity
30790 * ln(-Infinity) = NaN
30791 * ln(NaN) = NaN
30792 *
30793 * ln(n) (n != 1) is non-terminating.
30794 *
30795 */
30796 function naturalLogarithm(y, sd) {
30797 var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,
30798 n = 1,
30799 guard = 10,
30800 x = y,
30801 xd = x.d,
30802 Ctor = x.constructor,
30803 rm = Ctor.rounding,
30804 pr = Ctor.precision;
30805
30806 // Is x negative or Infinity, NaN, 0 or 1?
30807 if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {
30808 return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);
30809 }
30810
30811 if (sd == null) {
30812 external = false;
30813 wpr = pr;
30814 } else {
30815 wpr = sd;
30816 }
30817
30818 Ctor.precision = wpr += guard;
30819 c = digitsToString(xd);
30820 c0 = c.charAt(0);
30821
30822 if (Math.abs(e = x.e) < 1.5e15) {
30823
30824 // Argument reduction.
30825 // The series converges faster the closer the argument is to 1, so using
30826 // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b
30827 // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
30828 // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
30829 // later be divided by this number, then separate out the power of 10 using
30830 // ln(a*10^b) = ln(a) + b*ln(10).
30831
30832 // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
30833 //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
30834 // max n is 6 (gives 0.7 - 1.3)
30835 while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
30836 x = x.times(y);
30837 c = digitsToString(x.d);
30838 c0 = c.charAt(0);
30839 n++;
30840 }
30841
30842 e = x.e;
30843
30844 if (c0 > 1) {
30845 x = new Ctor('0.' + c);
30846 e++;
30847 } else {
30848 x = new Ctor(c0 + '.' + c.slice(1));
30849 }
30850 } else {
30851
30852 // The argument reduction method above may result in overflow if the argument y is a massive
30853 // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
30854 // function using ln(x*10^e) = ln(x) + e*ln(10).
30855 t = getLn10(Ctor, wpr + 2, pr).times(e + '');
30856 x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);
30857 Ctor.precision = pr;
30858
30859 return sd == null ? finalise(x, pr, rm, external = true) : x;
30860 }
30861
30862 // x1 is x reduced to a value near 1.
30863 x1 = x;
30864
30865 // Taylor series.
30866 // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
30867 // where x = (y - 1)/(y + 1) (|x| < 1)
30868 sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);
30869 x2 = finalise(x.times(x), wpr, 1);
30870 denominator = 3;
30871
30872 for (;;) {
30873 numerator = finalise(numerator.times(x2), wpr, 1);
30874 t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));
30875
30876 if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
30877 sum = sum.times(2);
30878
30879 // Reverse the argument reduction. Check that e is not 0 because, besides preventing an
30880 // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.
30881 if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
30882 sum = divide(sum, new Ctor(n), wpr, 1);
30883
30884 // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has
30885 // been repeated previously) and the first 4 rounding digits 9999?
30886 // If so, restart the summation with a higher precision, otherwise
30887 // e.g. with precision: 12, rounding: 1
30888 // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.
30889 // `wpr - guard` is the index of first rounding digit.
30890 if (sd == null) {
30891 if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
30892 Ctor.precision = wpr += guard;
30893 t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);
30894 x2 = finalise(x.times(x), wpr, 1);
30895 denominator = rep = 1;
30896 } else {
30897 return finalise(sum, Ctor.precision = pr, rm, external = true);
30898 }
30899 } else {
30900 Ctor.precision = pr;
30901 return sum;
30902 }
30903 }
30904
30905 sum = t;
30906 denominator += 2;
30907 }
30908 }
30909
30910
30911 // ±Infinity, NaN.
30912 function nonFiniteToString(x) {
30913 // Unsigned.
30914 return String(x.s * x.s / 0);
30915 }
30916
30917
30918 /*
30919 * Parse the value of a new Decimal `x` from string `str`.
30920 */
30921 function parseDecimal(x, str) {
30922 var e, i, len;
30923
30924 // Decimal point?
30925 if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
30926
30927 // Exponential form?
30928 if ((i = str.search(/e/i)) > 0) {
30929
30930 // Determine exponent.
30931 if (e < 0) e = i;
30932 e += +str.slice(i + 1);
30933 str = str.substring(0, i);
30934 } else if (e < 0) {
30935
30936 // Integer.
30937 e = str.length;
30938 }
30939
30940 // Determine leading zeros.
30941 for (i = 0; str.charCodeAt(i) === 48; i++);
30942
30943 // Determine trailing zeros.
30944 for (len = str.length; str.charCodeAt(len - 1) === 48; --len);
30945 str = str.slice(i, len);
30946
30947 if (str) {
30948 len -= i;
30949 x.e = e = e - i - 1;
30950 x.d = [];
30951
30952 // Transform base
30953
30954 // e is the base 10 exponent.
30955 // i is where to slice str to get the first word of the digits array.
30956 i = (e + 1) % LOG_BASE;
30957 if (e < 0) i += LOG_BASE;
30958
30959 if (i < len) {
30960 if (i) x.d.push(+str.slice(0, i));
30961 for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
30962 str = str.slice(i);
30963 i = LOG_BASE - str.length;
30964 } else {
30965 i -= len;
30966 }
30967
30968 for (; i--;) str += '0';
30969 x.d.push(+str);
30970
30971 if (external) {
30972
30973 // Overflow?
30974 if (x.e > x.constructor.maxE) {
30975
30976 // Infinity.
30977 x.d = null;
30978 x.e = NaN;
30979
30980 // Underflow?
30981 } else if (x.e < x.constructor.minE) {
30982
30983 // Zero.
30984 x.e = 0;
30985 x.d = [0];
30986 // x.constructor.underflow = true;
30987 } // else x.constructor.underflow = false;
30988 }
30989 } else {
30990
30991 // Zero.
30992 x.e = 0;
30993 x.d = [0];
30994 }
30995
30996 return x;
30997 }
30998
30999
31000 /*
31001 * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.
31002 */
31003 function parseOther(x, str) {
31004 var base, Ctor, divisor, i, isFloat, len, p, xd, xe;
31005
31006 if (str === 'Infinity' || str === 'NaN') {
31007 if (!+str) x.s = NaN;
31008 x.e = NaN;
31009 x.d = null;
31010 return x;
31011 }
31012
31013 if (isHex.test(str)) {
31014 base = 16;
31015 str = str.toLowerCase();
31016 } else if (isBinary.test(str)) {
31017 base = 2;
31018 } else if (isOctal.test(str)) {
31019 base = 8;
31020 } else {
31021 throw Error(invalidArgument + str);
31022 }
31023
31024 // Is there a binary exponent part?
31025 i = str.search(/p/i);
31026
31027 if (i > 0) {
31028 p = +str.slice(i + 1);
31029 str = str.substring(2, i);
31030 } else {
31031 str = str.slice(2);
31032 }
31033
31034 // Convert `str` as an integer then divide the result by `base` raised to a power such that the
31035 // fraction part will be restored.
31036 i = str.indexOf('.');
31037 isFloat = i >= 0;
31038 Ctor = x.constructor;
31039
31040 if (isFloat) {
31041 str = str.replace('.', '');
31042 len = str.length;
31043 i = len - i;
31044
31045 // log[10](16) = 1.2041... , log[10](88) = 1.9444....
31046 divisor = intPow(Ctor, new Ctor(base), i, i * 2);
31047 }
31048
31049 xd = convertBase(str, base, BASE);
31050 xe = xd.length - 1;
31051
31052 // Remove trailing zeros.
31053 for (i = xe; xd[i] === 0; --i) xd.pop();
31054 if (i < 0) return new Ctor(x.s * 0);
31055 x.e = getBase10Exponent(xd, xe);
31056 x.d = xd;
31057 external = false;
31058
31059 // At what precision to perform the division to ensure exact conversion?
31060 // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)
31061 // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412
31062 // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.
31063 // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount
31064 // Therefore using 4 * the number of digits of str will always be enough.
31065 if (isFloat) x = divide(x, divisor, len * 4);
31066
31067 // Multiply by the binary exponent part if present.
31068 if (p) x = x.times(Math.abs(p) < 54 ? Math.pow(2, p) : Decimal.pow(2, p));
31069 external = true;
31070
31071 return x;
31072 }
31073
31074
31075 /*
31076 * sin(x) = x - x^3/3! + x^5/5! - ...
31077 * |x| < pi/2
31078 *
31079 */
31080 function sine(Ctor, x) {
31081 var k,
31082 len = x.d.length;
31083
31084 if (len < 3) return taylorSeries(Ctor, 2, x, x);
31085
31086 // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)
31087 // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)
31088 // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))
31089
31090 // Estimate the optimum number of times to use the argument reduction.
31091 k = 1.4 * Math.sqrt(len);
31092 k = k > 16 ? 16 : k | 0;
31093
31094 // Max k before Math.pow precision loss is 22
31095 x = x.times(Math.pow(5, -k));
31096 x = taylorSeries(Ctor, 2, x, x);
31097
31098 // Reverse argument reduction
31099 var sin2_x,
31100 d5 = new Ctor(5),
31101 d16 = new Ctor(16),
31102 d20 = new Ctor(20);
31103 for (; k--;) {
31104 sin2_x = x.times(x);
31105 x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));
31106 }
31107
31108 return x;
31109 }
31110
31111
31112 // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.
31113 function taylorSeries(Ctor, n, x, y, isHyperbolic) {
31114 var j, t, u, x2,
31115 i = 1,
31116 pr = Ctor.precision,
31117 k = Math.ceil(pr / LOG_BASE);
31118
31119 external = false;
31120 x2 = x.times(x);
31121 u = new Ctor(y);
31122
31123 for (;;) {
31124 t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);
31125 u = isHyperbolic ? y.plus(t) : y.minus(t);
31126 y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);
31127 t = u.plus(y);
31128
31129 if (t.d[k] !== void 0) {
31130 for (j = k; t.d[j] === u.d[j] && j--;);
31131 if (j == -1) break;
31132 }
31133
31134 j = u;
31135 u = y;
31136 y = t;
31137 t = j;
31138 i++;
31139 }
31140
31141 external = true;
31142 t.d.length = k + 1;
31143
31144 return t;
31145 }
31146
31147
31148 // Return the absolute value of `x` reduced to less than or equal to half pi.
31149 function toLessThanHalfPi(Ctor, x) {
31150 var t,
31151 isNeg = x.s < 0,
31152 pi = getPi(Ctor, Ctor.precision, 1),
31153 halfPi = pi.times(0.5);
31154
31155 x = x.abs();
31156
31157 if (x.lte(halfPi)) {
31158 quadrant = isNeg ? 4 : 1;
31159 return x;
31160 }
31161
31162 t = x.divToInt(pi);
31163
31164 if (t.isZero()) {
31165 quadrant = isNeg ? 3 : 2;
31166 } else {
31167 x = x.minus(t.times(pi));
31168
31169 // 0 <= x < pi
31170 if (x.lte(halfPi)) {
31171 quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);
31172 return x;
31173 }
31174
31175 quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);
31176 }
31177
31178 return x.minus(pi).abs();
31179 }
31180
31181
31182 /*
31183 * Return the value of Decimal `x` as a string in base `baseOut`.
31184 *
31185 * If the optional `sd` argument is present include a binary exponent suffix.
31186 */
31187 function toStringBinary(x, baseOut, sd, rm) {
31188 var base, e, i, k, len, roundUp, str, xd, y,
31189 Ctor = x.constructor,
31190 isExp = sd !== void 0;
31191
31192 if (isExp) {
31193 checkInt32(sd, 1, MAX_DIGITS);
31194 if (rm === void 0) rm = Ctor.rounding;
31195 else checkInt32(rm, 0, 8);
31196 } else {
31197 sd = Ctor.precision;
31198 rm = Ctor.rounding;
31199 }
31200
31201 if (!x.isFinite()) {
31202 str = nonFiniteToString(x);
31203 } else {
31204 str = finiteToString(x);
31205 i = str.indexOf('.');
31206
31207 // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:
31208 // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))
31209 // minBinaryExponent = floor(decimalExponent * log[2](10))
31210 // log[2](10) = 3.321928094887362347870319429489390175864
31211
31212 if (isExp) {
31213 base = 2;
31214 if (baseOut == 16) {
31215 sd = sd * 4 - 3;
31216 } else if (baseOut == 8) {
31217 sd = sd * 3 - 2;
31218 }
31219 } else {
31220 base = baseOut;
31221 }
31222
31223 // Convert the number as an integer then divide the result by its base raised to a power such
31224 // that the fraction part will be restored.
31225
31226 // Non-integer.
31227 if (i >= 0) {
31228 str = str.replace('.', '');
31229 y = new Ctor(1);
31230 y.e = str.length - i;
31231 y.d = convertBase(finiteToString(y), 10, base);
31232 y.e = y.d.length;
31233 }
31234
31235 xd = convertBase(str, 10, base);
31236 e = len = xd.length;
31237
31238 // Remove trailing zeros.
31239 for (; xd[--len] == 0;) xd.pop();
31240
31241 if (!xd[0]) {
31242 str = isExp ? '0p+0' : '0';
31243 } else {
31244 if (i < 0) {
31245 e--;
31246 } else {
31247 x = new Ctor(x);
31248 x.d = xd;
31249 x.e = e;
31250 x = divide(x, y, sd, rm, 0, base);
31251 xd = x.d;
31252 e = x.e;
31253 roundUp = inexact;
31254 }
31255
31256 // The rounding digit, i.e. the digit after the digit that may be rounded up.
31257 i = xd[sd];
31258 k = base / 2;
31259 roundUp = roundUp || xd[sd + 1] !== void 0;
31260
31261 roundUp = rm < 4
31262 ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))
31263 : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||
31264 rm === (x.s < 0 ? 8 : 7));
31265
31266 xd.length = sd;
31267
31268 if (roundUp) {
31269
31270 // Rounding up may mean the previous digit has to be rounded up and so on.
31271 for (; ++xd[--sd] > base - 1;) {
31272 xd[sd] = 0;
31273 if (!sd) {
31274 ++e;
31275 xd.unshift(1);
31276 }
31277 }
31278 }
31279
31280 // Determine trailing zeros.
31281 for (len = xd.length; !xd[len - 1]; --len);
31282
31283 // E.g. [4, 11, 15] becomes 4bf.
31284 for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);
31285
31286 // Add binary exponent suffix?
31287 if (isExp) {
31288 if (len > 1) {
31289 if (baseOut == 16 || baseOut == 8) {
31290 i = baseOut == 16 ? 4 : 3;
31291 for (--len; len % i; len++) str += '0';
31292 xd = convertBase(str, base, baseOut);
31293 for (len = xd.length; !xd[len - 1]; --len);
31294
31295 // xd[0] will always be be 1
31296 for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);
31297 } else {
31298 str = str.charAt(0) + '.' + str.slice(1);
31299 }
31300 }
31301
31302 str = str + (e < 0 ? 'p' : 'p+') + e;
31303 } else if (e < 0) {
31304 for (; ++e;) str = '0' + str;
31305 str = '0.' + str;
31306 } else {
31307 if (++e > len) for (e -= len; e-- ;) str += '0';
31308 else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);
31309 }
31310 }
31311
31312 str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;
31313 }
31314
31315 return x.s < 0 ? '-' + str : str;
31316 }
31317
31318
31319 // Does not strip trailing zeros.
31320 function truncate(arr, len) {
31321 if (arr.length > len) {
31322 arr.length = len;
31323 return true;
31324 }
31325 }
31326
31327
31328 // Decimal methods
31329
31330
31331 /*
31332 * abs
31333 * acos
31334 * acosh
31335 * add
31336 * asin
31337 * asinh
31338 * atan
31339 * atanh
31340 * atan2
31341 * cbrt
31342 * ceil
31343 * clone
31344 * config
31345 * cos
31346 * cosh
31347 * div
31348 * exp
31349 * floor
31350 * hypot
31351 * ln
31352 * log
31353 * log2
31354 * log10
31355 * max
31356 * min
31357 * mod
31358 * mul
31359 * pow
31360 * random
31361 * round
31362 * set
31363 * sign
31364 * sin
31365 * sinh
31366 * sqrt
31367 * sub
31368 * tan
31369 * tanh
31370 * trunc
31371 */
31372
31373
31374 /*
31375 * Return a new Decimal whose value is the absolute value of `x`.
31376 *
31377 * x {number|string|Decimal}
31378 *
31379 */
31380 function abs(x) {
31381 return new this(x).abs();
31382 }
31383
31384
31385 /*
31386 * Return a new Decimal whose value is the arccosine in radians of `x`.
31387 *
31388 * x {number|string|Decimal}
31389 *
31390 */
31391 function acos(x) {
31392 return new this(x).acos();
31393 }
31394
31395
31396 /*
31397 * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to
31398 * `precision` significant digits using rounding mode `rounding`.
31399 *
31400 * x {number|string|Decimal} A value in radians.
31401 *
31402 */
31403 function acosh(x) {
31404 return new this(x).acosh();
31405 }
31406
31407
31408 /*
31409 * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant
31410 * digits using rounding mode `rounding`.
31411 *
31412 * x {number|string|Decimal}
31413 * y {number|string|Decimal}
31414 *
31415 */
31416 function add(x, y) {
31417 return new this(x).plus(y);
31418 }
31419
31420
31421 /*
31422 * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`
31423 * significant digits using rounding mode `rounding`.
31424 *
31425 * x {number|string|Decimal}
31426 *
31427 */
31428 function asin(x) {
31429 return new this(x).asin();
31430 }
31431
31432
31433 /*
31434 * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to
31435 * `precision` significant digits using rounding mode `rounding`.
31436 *
31437 * x {number|string|Decimal} A value in radians.
31438 *
31439 */
31440 function asinh(x) {
31441 return new this(x).asinh();
31442 }
31443
31444
31445 /*
31446 * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`
31447 * significant digits using rounding mode `rounding`.
31448 *
31449 * x {number|string|Decimal}
31450 *
31451 */
31452 function atan(x) {
31453 return new this(x).atan();
31454 }
31455
31456
31457 /*
31458 * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to
31459 * `precision` significant digits using rounding mode `rounding`.
31460 *
31461 * x {number|string|Decimal} A value in radians.
31462 *
31463 */
31464 function atanh(x) {
31465 return new this(x).atanh();
31466 }
31467
31468
31469 /*
31470 * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi
31471 * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.
31472 *
31473 * Domain: [-Infinity, Infinity]
31474 * Range: [-pi, pi]
31475 *
31476 * y {number|string|Decimal} The y-coordinate.
31477 * x {number|string|Decimal} The x-coordinate.
31478 *
31479 * atan2(±0, -0) = ±pi
31480 * atan2(±0, +0) = ±0
31481 * atan2(±0, -x) = ±pi for x > 0
31482 * atan2(±0, x) = ±0 for x > 0
31483 * atan2(-y, ±0) = -pi/2 for y > 0
31484 * atan2(y, ±0) = pi/2 for y > 0
31485 * atan2(±y, -Infinity) = ±pi for finite y > 0
31486 * atan2(±y, +Infinity) = ±0 for finite y > 0
31487 * atan2(±Infinity, x) = ±pi/2 for finite x
31488 * atan2(±Infinity, -Infinity) = ±3*pi/4
31489 * atan2(±Infinity, +Infinity) = ±pi/4
31490 * atan2(NaN, x) = NaN
31491 * atan2(y, NaN) = NaN
31492 *
31493 */
31494 function atan2(y, x) {
31495 y = new this(y);
31496 x = new this(x);
31497 var r,
31498 pr = this.precision,
31499 rm = this.rounding,
31500 wpr = pr + 4;
31501
31502 // Either NaN
31503 if (!y.s || !x.s) {
31504 r = new this(NaN);
31505
31506 // Both ±Infinity
31507 } else if (!y.d && !x.d) {
31508 r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);
31509 r.s = y.s;
31510
31511 // x is ±Infinity or y is ±0
31512 } else if (!x.d || y.isZero()) {
31513 r = x.s < 0 ? getPi(this, pr, rm) : new this(0);
31514 r.s = y.s;
31515
31516 // y is ±Infinity or x is ±0
31517 } else if (!y.d || x.isZero()) {
31518 r = getPi(this, wpr, 1).times(0.5);
31519 r.s = y.s;
31520
31521 // Both non-zero and finite
31522 } else if (x.s < 0) {
31523 this.precision = wpr;
31524 this.rounding = 1;
31525 r = this.atan(divide(y, x, wpr, 1));
31526 x = getPi(this, wpr, 1);
31527 this.precision = pr;
31528 this.rounding = rm;
31529 r = y.s < 0 ? r.minus(x) : r.plus(x);
31530 } else {
31531 r = this.atan(divide(y, x, wpr, 1));
31532 }
31533
31534 return r;
31535 }
31536
31537
31538 /*
31539 * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant
31540 * digits using rounding mode `rounding`.
31541 *
31542 * x {number|string|Decimal}
31543 *
31544 */
31545 function cbrt(x) {
31546 return new this(x).cbrt();
31547 }
31548
31549
31550 /*
31551 * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.
31552 *
31553 * x {number|string|Decimal}
31554 *
31555 */
31556 function ceil(x) {
31557 return finalise(x = new this(x), x.e + 1, 2);
31558 }
31559
31560
31561 /*
31562 * Configure global settings for a Decimal constructor.
31563 *
31564 * `obj` is an object with one or more of the following properties,
31565 *
31566 * precision {number}
31567 * rounding {number}
31568 * toExpNeg {number}
31569 * toExpPos {number}
31570 * maxE {number}
31571 * minE {number}
31572 * modulo {number}
31573 * crypto {boolean|number}
31574 * defaults {true}
31575 *
31576 * E.g. Decimal.config({ precision: 20, rounding: 4 })
31577 *
31578 */
31579 function config(obj) {
31580 if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');
31581 var i, p, v,
31582 useDefaults = obj.defaults === true,
31583 ps = [
31584 'precision', 1, MAX_DIGITS,
31585 'rounding', 0, 8,
31586 'toExpNeg', -EXP_LIMIT, 0,
31587 'toExpPos', 0, EXP_LIMIT,
31588 'maxE', 0, EXP_LIMIT,
31589 'minE', -EXP_LIMIT, 0,
31590 'modulo', 0, 9
31591 ];
31592
31593 for (i = 0; i < ps.length; i += 3) {
31594 if (p = ps[i], useDefaults) this[p] = DEFAULTS[p];
31595 if ((v = obj[p]) !== void 0) {
31596 if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;
31597 else throw Error(invalidArgument + p + ': ' + v);
31598 }
31599 }
31600
31601 if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p];
31602 if ((v = obj[p]) !== void 0) {
31603 if (v === true || v === false || v === 0 || v === 1) {
31604 if (v) {
31605 if (typeof crypto != 'undefined' && crypto &&
31606 (crypto.getRandomValues || crypto.randomBytes)) {
31607 this[p] = true;
31608 } else {
31609 throw Error(cryptoUnavailable);
31610 }
31611 } else {
31612 this[p] = false;
31613 }
31614 } else {
31615 throw Error(invalidArgument + p + ': ' + v);
31616 }
31617 }
31618
31619 return this;
31620 }
31621
31622
31623 /*
31624 * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant
31625 * digits using rounding mode `rounding`.
31626 *
31627 * x {number|string|Decimal} A value in radians.
31628 *
31629 */
31630 function cos(x) {
31631 return new this(x).cos();
31632 }
31633
31634
31635 /*
31636 * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision
31637 * significant digits using rounding mode `rounding`.
31638 *
31639 * x {number|string|Decimal} A value in radians.
31640 *
31641 */
31642 function cosh(x) {
31643 return new this(x).cosh();
31644 }
31645
31646
31647 /*
31648 * Create and return a Decimal constructor with the same configuration properties as this Decimal
31649 * constructor.
31650 *
31651 */
31652 function clone(obj) {
31653 var i, p, ps;
31654
31655 /*
31656 * The Decimal constructor and exported function.
31657 * Return a new Decimal instance.
31658 *
31659 * v {number|string|Decimal} A numeric value.
31660 *
31661 */
31662 function Decimal(v) {
31663 var e, i, t,
31664 x = this;
31665
31666 // Decimal called without new.
31667 if (!(x instanceof Decimal)) return new Decimal(v);
31668
31669 // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
31670 // which points to Object.
31671 x.constructor = Decimal;
31672
31673 // Duplicate.
31674 if (v instanceof Decimal) {
31675 x.s = v.s;
31676 x.e = v.e;
31677 x.d = (v = v.d) ? v.slice() : v;
31678 return;
31679 }
31680
31681 t = typeof v;
31682
31683 if (t === 'number') {
31684 if (v === 0) {
31685 x.s = 1 / v < 0 ? -1 : 1;
31686 x.e = 0;
31687 x.d = [0];
31688 return;
31689 }
31690
31691 if (v < 0) {
31692 v = -v;
31693 x.s = -1;
31694 } else {
31695 x.s = 1;
31696 }
31697
31698 // Fast path for small integers.
31699 if (v === ~~v && v < 1e7) {
31700 for (e = 0, i = v; i >= 10; i /= 10) e++;
31701 x.e = e;
31702 x.d = [v];
31703 return;
31704
31705 // Infinity, NaN.
31706 } else if (v * 0 !== 0) {
31707 if (!v) x.s = NaN;
31708 x.e = NaN;
31709 x.d = null;
31710 return;
31711 }
31712
31713 return parseDecimal(x, v.toString());
31714
31715 } else if (t !== 'string') {
31716 throw Error(invalidArgument + v);
31717 }
31718
31719 // Minus sign?
31720 if (v.charCodeAt(0) === 45) {
31721 v = v.slice(1);
31722 x.s = -1;
31723 } else {
31724 x.s = 1;
31725 }
31726
31727 return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);
31728 }
31729
31730 Decimal.prototype = P;
31731
31732 Decimal.ROUND_UP = 0;
31733 Decimal.ROUND_DOWN = 1;
31734 Decimal.ROUND_CEIL = 2;
31735 Decimal.ROUND_FLOOR = 3;
31736 Decimal.ROUND_HALF_UP = 4;
31737 Decimal.ROUND_HALF_DOWN = 5;
31738 Decimal.ROUND_HALF_EVEN = 6;
31739 Decimal.ROUND_HALF_CEIL = 7;
31740 Decimal.ROUND_HALF_FLOOR = 8;
31741 Decimal.EUCLID = 9;
31742
31743 Decimal.config = Decimal.set = config;
31744 Decimal.clone = clone;
31745 Decimal.isDecimal = isDecimalInstance;
31746
31747 Decimal.abs = abs;
31748 Decimal.acos = acos;
31749 Decimal.acosh = acosh; // ES6
31750 Decimal.add = add;
31751 Decimal.asin = asin;
31752 Decimal.asinh = asinh; // ES6
31753 Decimal.atan = atan;
31754 Decimal.atanh = atanh; // ES6
31755 Decimal.atan2 = atan2;
31756 Decimal.cbrt = cbrt; // ES6
31757 Decimal.ceil = ceil;
31758 Decimal.cos = cos;
31759 Decimal.cosh = cosh; // ES6
31760 Decimal.div = div;
31761 Decimal.exp = exp;
31762 Decimal.floor = floor;
31763 Decimal.hypot = hypot; // ES6
31764 Decimal.ln = ln;
31765 Decimal.log = log;
31766 Decimal.log10 = log10; // ES6
31767 Decimal.log2 = log2; // ES6
31768 Decimal.max = max;
31769 Decimal.min = min;
31770 Decimal.mod = mod;
31771 Decimal.mul = mul;
31772 Decimal.pow = pow;
31773 Decimal.random = random;
31774 Decimal.round = round;
31775 Decimal.sign = sign; // ES6
31776 Decimal.sin = sin;
31777 Decimal.sinh = sinh; // ES6
31778 Decimal.sqrt = sqrt;
31779 Decimal.sub = sub;
31780 Decimal.tan = tan;
31781 Decimal.tanh = tanh; // ES6
31782 Decimal.trunc = trunc; // ES6
31783
31784 if (obj === void 0) obj = {};
31785 if (obj) {
31786 if (obj.defaults !== true) {
31787 ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];
31788 for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
31789 }
31790 }
31791
31792 Decimal.config(obj);
31793
31794 return Decimal;
31795 }
31796
31797
31798 /*
31799 * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant
31800 * digits using rounding mode `rounding`.
31801 *
31802 * x {number|string|Decimal}
31803 * y {number|string|Decimal}
31804 *
31805 */
31806 function div(x, y) {
31807 return new this(x).div(y);
31808 }
31809
31810
31811 /*
31812 * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`
31813 * significant digits using rounding mode `rounding`.
31814 *
31815 * x {number|string|Decimal} The power to which to raise the base of the natural log.
31816 *
31817 */
31818 function exp(x) {
31819 return new this(x).exp();
31820 }
31821
31822
31823 /*
31824 * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.
31825 *
31826 * x {number|string|Decimal}
31827 *
31828 */
31829 function floor(x) {
31830 return finalise(x = new this(x), x.e + 1, 3);
31831 }
31832
31833
31834 /*
31835 * Return a new Decimal whose value is the square root of the sum of the squares of the arguments,
31836 * rounded to `precision` significant digits using rounding mode `rounding`.
31837 *
31838 * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)
31839 *
31840 */
31841 function hypot() {
31842 var i, n,
31843 t = new this(0);
31844
31845 external = false;
31846
31847 for (i = 0; i < arguments.length;) {
31848 n = new this(arguments[i++]);
31849 if (!n.d) {
31850 if (n.s) {
31851 external = true;
31852 return new this(1 / 0);
31853 }
31854 t = n;
31855 } else if (t.d) {
31856 t = t.plus(n.times(n));
31857 }
31858 }
31859
31860 external = true;
31861
31862 return t.sqrt();
31863 }
31864
31865
31866 /*
31867 * Return true if object is a Decimal instance (where Decimal is any Decimal constructor),
31868 * otherwise return false.
31869 *
31870 */
31871 function isDecimalInstance(obj) {
31872 return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false;
31873 }
31874
31875
31876 /*
31877 * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`
31878 * significant digits using rounding mode `rounding`.
31879 *
31880 * x {number|string|Decimal}
31881 *
31882 */
31883 function ln(x) {
31884 return new this(x).ln();
31885 }
31886
31887
31888 /*
31889 * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base
31890 * is specified, rounded to `precision` significant digits using rounding mode `rounding`.
31891 *
31892 * log[y](x)
31893 *
31894 * x {number|string|Decimal} The argument of the logarithm.
31895 * y {number|string|Decimal} The base of the logarithm.
31896 *
31897 */
31898 function log(x, y) {
31899 return new this(x).log(y);
31900 }
31901
31902
31903 /*
31904 * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`
31905 * significant digits using rounding mode `rounding`.
31906 *
31907 * x {number|string|Decimal}
31908 *
31909 */
31910 function log2(x) {
31911 return new this(x).log(2);
31912 }
31913
31914
31915 /*
31916 * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`
31917 * significant digits using rounding mode `rounding`.
31918 *
31919 * x {number|string|Decimal}
31920 *
31921 */
31922 function log10(x) {
31923 return new this(x).log(10);
31924 }
31925
31926
31927 /*
31928 * Return a new Decimal whose value is the maximum of the arguments.
31929 *
31930 * arguments {number|string|Decimal}
31931 *
31932 */
31933 function max() {
31934 return maxOrMin(this, arguments, 'lt');
31935 }
31936
31937
31938 /*
31939 * Return a new Decimal whose value is the minimum of the arguments.
31940 *
31941 * arguments {number|string|Decimal}
31942 *
31943 */
31944 function min() {
31945 return maxOrMin(this, arguments, 'gt');
31946 }
31947
31948
31949 /*
31950 * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits
31951 * using rounding mode `rounding`.
31952 *
31953 * x {number|string|Decimal}
31954 * y {number|string|Decimal}
31955 *
31956 */
31957 function mod(x, y) {
31958 return new this(x).mod(y);
31959 }
31960
31961
31962 /*
31963 * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant
31964 * digits using rounding mode `rounding`.
31965 *
31966 * x {number|string|Decimal}
31967 * y {number|string|Decimal}
31968 *
31969 */
31970 function mul(x, y) {
31971 return new this(x).mul(y);
31972 }
31973
31974
31975 /*
31976 * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision
31977 * significant digits using rounding mode `rounding`.
31978 *
31979 * x {number|string|Decimal} The base.
31980 * y {number|string|Decimal} The exponent.
31981 *
31982 */
31983 function pow(x, y) {
31984 return new this(x).pow(y);
31985 }
31986
31987
31988 /*
31989 * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with
31990 * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros
31991 * are produced).
31992 *
31993 * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.
31994 *
31995 */
31996 function random(sd) {
31997 var d, e, k, n,
31998 i = 0,
31999 r = new this(1),
32000 rd = [];
32001
32002 if (sd === void 0) sd = this.precision;
32003 else checkInt32(sd, 1, MAX_DIGITS);
32004
32005 k = Math.ceil(sd / LOG_BASE);
32006
32007 if (!this.crypto) {
32008 for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;
32009
32010 // Browsers supporting crypto.getRandomValues.
32011 } else if (crypto.getRandomValues) {
32012 d = crypto.getRandomValues(new Uint32Array(k));
32013
32014 for (; i < k;) {
32015 n = d[i];
32016
32017 // 0 <= n < 4294967296
32018 // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).
32019 if (n >= 4.29e9) {
32020 d[i] = crypto.getRandomValues(new Uint32Array(1))[0];
32021 } else {
32022
32023 // 0 <= n <= 4289999999
32024 // 0 <= (n % 1e7) <= 9999999
32025 rd[i++] = n % 1e7;
32026 }
32027 }
32028
32029 // Node.js supporting crypto.randomBytes.
32030 } else if (crypto.randomBytes) {
32031
32032 // buffer
32033 d = crypto.randomBytes(k *= 4);
32034
32035 for (; i < k;) {
32036
32037 // 0 <= n < 2147483648
32038 n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);
32039
32040 // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).
32041 if (n >= 2.14e9) {
32042 crypto.randomBytes(4).copy(d, i);
32043 } else {
32044
32045 // 0 <= n <= 2139999999
32046 // 0 <= (n % 1e7) <= 9999999
32047 rd.push(n % 1e7);
32048 i += 4;
32049 }
32050 }
32051
32052 i = k / 4;
32053 } else {
32054 throw Error(cryptoUnavailable);
32055 }
32056
32057 k = rd[--i];
32058 sd %= LOG_BASE;
32059
32060 // Convert trailing digits to zeros according to sd.
32061 if (k && sd) {
32062 n = mathpow(10, LOG_BASE - sd);
32063 rd[i] = (k / n | 0) * n;
32064 }
32065
32066 // Remove trailing words which are zero.
32067 for (; rd[i] === 0; i--) rd.pop();
32068
32069 // Zero?
32070 if (i < 0) {
32071 e = 0;
32072 rd = [0];
32073 } else {
32074 e = -1;
32075
32076 // Remove leading words which are zero and adjust exponent accordingly.
32077 for (; rd[0] === 0; e -= LOG_BASE) rd.shift();
32078
32079 // Count the digits of the first word of rd to determine leading zeros.
32080 for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;
32081
32082 // Adjust the exponent for leading zeros of the first word of rd.
32083 if (k < LOG_BASE) e -= LOG_BASE - k;
32084 }
32085
32086 r.e = e;
32087 r.d = rd;
32088
32089 return r;
32090 }
32091
32092
32093 /*
32094 * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.
32095 *
32096 * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).
32097 *
32098 * x {number|string|Decimal}
32099 *
32100 */
32101 function round(x) {
32102 return finalise(x = new this(x), x.e + 1, this.rounding);
32103 }
32104
32105
32106 /*
32107 * Return
32108 * 1 if x > 0,
32109 * -1 if x < 0,
32110 * 0 if x is 0,
32111 * -0 if x is -0,
32112 * NaN otherwise
32113 *
32114 */
32115 function sign(x) {
32116 x = new this(x);
32117 return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;
32118 }
32119
32120
32121 /*
32122 * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits
32123 * using rounding mode `rounding`.
32124 *
32125 * x {number|string|Decimal} A value in radians.
32126 *
32127 */
32128 function sin(x) {
32129 return new this(x).sin();
32130 }
32131
32132
32133 /*
32134 * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`
32135 * significant digits using rounding mode `rounding`.
32136 *
32137 * x {number|string|Decimal} A value in radians.
32138 *
32139 */
32140 function sinh(x) {
32141 return new this(x).sinh();
32142 }
32143
32144
32145 /*
32146 * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant
32147 * digits using rounding mode `rounding`.
32148 *
32149 * x {number|string|Decimal}
32150 *
32151 */
32152 function sqrt(x) {
32153 return new this(x).sqrt();
32154 }
32155
32156
32157 /*
32158 * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits
32159 * using rounding mode `rounding`.
32160 *
32161 * x {number|string|Decimal}
32162 * y {number|string|Decimal}
32163 *
32164 */
32165 function sub(x, y) {
32166 return new this(x).sub(y);
32167 }
32168
32169
32170 /*
32171 * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant
32172 * digits using rounding mode `rounding`.
32173 *
32174 * x {number|string|Decimal} A value in radians.
32175 *
32176 */
32177 function tan(x) {
32178 return new this(x).tan();
32179 }
32180
32181
32182 /*
32183 * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`
32184 * significant digits using rounding mode `rounding`.
32185 *
32186 * x {number|string|Decimal} A value in radians.
32187 *
32188 */
32189 function tanh(x) {
32190 return new this(x).tanh();
32191 }
32192
32193
32194 /*
32195 * Return a new Decimal whose value is `x` truncated to an integer.
32196 *
32197 * x {number|string|Decimal}
32198 *
32199 */
32200 function trunc(x) {
32201 return finalise(x = new this(x), x.e + 1, 1);
32202 }
32203
32204
32205 // Create and configure initial Decimal constructor.
32206 Decimal = clone(DEFAULTS);
32207
32208 Decimal['default'] = Decimal.Decimal = Decimal;
32209
32210 // Create the internal constants from their string values.
32211 LN10 = new Decimal(LN10);
32212 PI = new Decimal(PI);
32213
32214
32215 // Export.
32216
32217
32218 // AMD.
32219 if (true) {
32220 !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
32221 return Decimal;
32222 }).call(exports, __webpack_require__, exports, module),
32223 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
32224
32225 // Node and other environments that support module.exports.
32226 } else if (typeof module != 'undefined' && module.exports) {
32227 module.exports = Decimal;
32228
32229 // Browser.
32230 } else {
32231 if (!globalScope) {
32232 globalScope = typeof self != 'undefined' && self && self.self == self
32233 ? self : Function('return this')();
32234 }
32235
32236 noConflict = globalScope.Decimal;
32237 Decimal.noConflict = function () {
32238 globalScope.Decimal = noConflict;
32239 return Decimal;
32240 };
32241
32242 globalScope.Decimal = Decimal;
32243 }
32244})(this);
32245
32246
32247/***/ }),
32248/* 164 */
32249/***/ (function(module, exports, __webpack_require__) {
32250
32251"use strict";
32252
32253
32254var deepMap = __webpack_require__(1);
32255
32256function factory (type, config, load, typed) {
32257 /**
32258 * Create a BigNumber, which can store numbers with arbitrary precision.
32259 * When a matrix is provided, all elements will be converted to BigNumber.
32260 *
32261 * Syntax:
32262 *
32263 * math.bignumber(x)
32264 *
32265 * Examples:
32266 *
32267 * 0.1 + 0.2; // returns number 0.30000000000000004
32268 * math.bignumber(0.1) + math.bignumber(0.2); // returns BigNumber 0.3
32269 *
32270 *
32271 * 7.2e500; // returns number Infinity
32272 * math.bignumber('7.2e500'); // returns BigNumber 7.2e500
32273 *
32274 * See also:
32275 *
32276 * boolean, complex, index, matrix, string, unit
32277 *
32278 * @param {number | string | Fraction | BigNumber | Array | Matrix | boolean | null} [value] Value for the big number,
32279 * 0 by default.
32280 * @returns {BigNumber} The created bignumber
32281 */
32282 var bignumber = typed('bignumber', {
32283 '': function () {
32284 return new type.BigNumber(0);
32285 },
32286
32287 'number': function (x) {
32288 // convert to string to prevent errors in case of >15 digits
32289 return new type.BigNumber(x + '');
32290 },
32291
32292 'string': function (x) {
32293 return new type.BigNumber(x);
32294 },
32295
32296 'BigNumber': function (x) {
32297 // we assume a BigNumber is immutable
32298 return x;
32299 },
32300
32301 'Fraction': function (x) {
32302 return new type.BigNumber(x.n).div(x.d);
32303 },
32304
32305 'Array | Matrix': function (x) {
32306 return deepMap(x, bignumber);
32307 }
32308 });
32309
32310 bignumber.toTex = {
32311 0: '0',
32312 1: '\\left(${args[0]}\\right)'
32313 };
32314
32315 return bignumber;
32316}
32317
32318exports.name = 'bignumber';
32319exports.factory = factory;
32320
32321
32322/***/ }),
32323/* 165 */
32324/***/ (function(module, exports, __webpack_require__) {
32325
32326"use strict";
32327
32328
32329var deepMap = __webpack_require__(1);
32330
32331function factory (type, config, load, typed) {
32332 /**
32333 * Create a boolean or convert a string or number to a boolean.
32334 * In case of a number, `true` is returned for non-zero numbers, and `false` in
32335 * case of zero.
32336 * Strings can be `'true'` or `'false'`, or can contain a number.
32337 * When value is a matrix, all elements will be converted to boolean.
32338 *
32339 * Syntax:
32340 *
32341 * math.boolean(x)
32342 *
32343 * Examples:
32344 *
32345 * math.boolean(0); // returns false
32346 * math.boolean(1); // returns true
32347 * math.boolean(-3); // returns true
32348 * math.boolean('true'); // returns true
32349 * math.boolean('false'); // returns false
32350 * math.boolean([1, 0, 1, 1]); // returns [true, false, true, true]
32351 *
32352 * See also:
32353 *
32354 * bignumber, complex, index, matrix, string, unit
32355 *
32356 * @param {string | number | boolean | Array | Matrix | null} value A value of any type
32357 * @return {boolean | Array | Matrix} The boolean value
32358 */
32359 var bool = typed('bool', {
32360 '': function () {
32361 return false;
32362 },
32363
32364 'boolean': function (x) {
32365 return x;
32366 },
32367
32368 'number': function (x) {
32369 return !!x;
32370 },
32371
32372 'BigNumber': function (x) {
32373 return !x.isZero();
32374 },
32375
32376 'string': function (x) {
32377 // try case insensitive
32378 var lcase = x.toLowerCase();
32379 if (lcase === 'true') {
32380 return true;
32381 }
32382 else if (lcase === 'false') {
32383 return false;
32384 }
32385
32386 // test whether value is a valid number
32387 var num = Number(x);
32388 if (x != '' && !isNaN(num)) {
32389 return !!num;
32390 }
32391
32392 throw new Error('Cannot convert "' + x + '" to a boolean');
32393 },
32394
32395 'Array | Matrix': function (x) {
32396 return deepMap(x, bool);
32397 }
32398 });
32399
32400 return bool;
32401}
32402
32403exports.name = 'boolean';
32404exports.factory = factory;
32405
32406
32407/***/ }),
32408/* 166 */
32409/***/ (function(module, exports, __webpack_require__) {
32410
32411module.exports = [
32412 // type
32413 __webpack_require__(167),
32414
32415 // construction function
32416 __webpack_require__(169)
32417];
32418
32419
32420/***/ }),
32421/* 167 */
32422/***/ (function(module, exports, __webpack_require__) {
32423
32424"use strict";
32425
32426
32427var format = __webpack_require__(9).format;
32428var lazy = __webpack_require__(5).lazy;
32429
32430function factory (type, config, load, typed, math) {
32431 /**
32432 * @constructor Chain
32433 * Wrap any value in a chain, allowing to perform chained operations on
32434 * the value.
32435 *
32436 * All methods available in the math.js library can be called upon the chain,
32437 * and then will be evaluated with the value itself as first argument.
32438 * The chain can be closed by executing chain.done(), which will return
32439 * the final value.
32440 *
32441 * The Chain has a number of special functions:
32442 * - done() Finalize the chained operation and return the
32443 * chain's value.
32444 * - valueOf() The same as done()
32445 * - toString() Returns a string representation of the chain's value.
32446 *
32447 * @param {*} [value]
32448 */
32449 function Chain (value) {
32450 if (!(this instanceof Chain)) {
32451 throw new SyntaxError('Constructor must be called with the new operator');
32452 }
32453
32454 if (type.isChain(value)) {
32455 this.value = value.value;
32456 }
32457 else {
32458 this.value = value;
32459 }
32460 }
32461
32462 /**
32463 * Attach type information
32464 */
32465 Chain.prototype.type = 'Chain';
32466 Chain.prototype.isChain = true;
32467
32468 /**
32469 * Close the chain. Returns the final value.
32470 * Does the same as method valueOf()
32471 * @returns {*} value
32472 */
32473 Chain.prototype.done = function () {
32474 return this.value;
32475 };
32476
32477 /**
32478 * Close the chain. Returns the final value.
32479 * Does the same as method done()
32480 * @returns {*} value
32481 */
32482 Chain.prototype.valueOf = function () {
32483 return this.value;
32484 };
32485
32486 /**
32487 * Get a string representation of the value in the chain
32488 * @returns {string}
32489 */
32490 Chain.prototype.toString = function () {
32491 return format(this.value);
32492 };
32493
32494 /**
32495 * Create a proxy method for the chain
32496 * @param {string} name
32497 * @param {Function} fn The function to be proxied
32498 * If fn is no function, it is silently ignored.
32499 * @private
32500 */
32501 function createProxy(name, fn) {
32502 if (typeof fn === 'function') {
32503 Chain.prototype[name] = chainify(fn);
32504 }
32505 }
32506
32507 /**
32508 * Create a proxy method for the chain
32509 * @param {string} name
32510 * @param {function} resolver The function resolving with the
32511 * function to be proxied
32512 * @private
32513 */
32514 function createLazyProxy(name, resolver) {
32515 lazy(Chain.prototype, name, function outerResolver() {
32516 var fn = resolver();
32517 if (typeof fn === 'function') {
32518 return chainify(fn);
32519 }
32520
32521 return undefined; // if not a function, ignore
32522 });
32523 }
32524
32525 /**
32526 * Make a function chainable
32527 * @param {function} fn
32528 * @return {Function} chain function
32529 * @private
32530 */
32531 function chainify (fn) {
32532 return function () {
32533 var args = [this.value]; // `this` will be the context of a Chain instance
32534 for (var i = 0; i < arguments.length; i++) {
32535 args[i + 1] = arguments[i];
32536 }
32537
32538 return new Chain(fn.apply(fn, args));
32539 }
32540 }
32541
32542 /**
32543 * Create a proxy for a single method, or an object with multiple methods.
32544 * Example usage:
32545 *
32546 * Chain.createProxy('add', function add (x, y) {...});
32547 * Chain.createProxy({
32548 * add: function add (x, y) {...},
32549 * subtract: function subtract (x, y) {...}
32550 * }
32551 *
32552 * @param {string | Object} arg0 A name (string), or an object with
32553 * functions
32554 * @param {*} [arg1] A function, when arg0 is a name
32555 */
32556 Chain.createProxy = function (arg0, arg1) {
32557 if (typeof arg0 === 'string') {
32558 // createProxy(name, value)
32559 createProxy(arg0, arg1);
32560 }
32561 else {
32562 // createProxy(values)
32563 for (var prop in arg0) {
32564 if (arg0.hasOwnProperty(prop)) {
32565 createProxy(prop, arg0[prop]);
32566 }
32567 }
32568 }
32569 };
32570
32571 // create proxy for everything that is in math.js
32572 Chain.createProxy(math);
32573
32574 // register on the import event, automatically add a proxy for every imported function.
32575 math.on('import', function (name, resolver, path) {
32576 if (path === undefined) {
32577 // an imported function (not a data type or something special)
32578 createLazyProxy(name, resolver);
32579 }
32580 });
32581
32582 return Chain;
32583}
32584
32585exports.name = 'Chain';
32586exports.path = 'type';
32587exports.factory = factory;
32588exports.math = true; // require providing the math namespace as 5th argument
32589exports.lazy = false; // we need to register a listener on the import events, so no lazy loading
32590
32591
32592/***/ }),
32593/* 168 */
32594/***/ (function(module, exports) {
32595
32596/**
32597 * Convert a BigNumber to a formatted string representation.
32598 *
32599 * Syntax:
32600 *
32601 * format(value)
32602 * format(value, options)
32603 * format(value, precision)
32604 * format(value, fn)
32605 *
32606 * Where:
32607 *
32608 * {number} value The value to be formatted
32609 * {Object} options An object with formatting options. Available options:
32610 * {string} notation
32611 * Number notation. Choose from:
32612 * 'fixed' Always use regular number notation.
32613 * For example '123.40' and '14000000'
32614 * 'exponential' Always use exponential notation.
32615 * For example '1.234e+2' and '1.4e+7'
32616 * 'auto' (default) Regular number notation for numbers
32617 * having an absolute value between
32618 * `lower` and `upper` bounds, and uses
32619 * exponential notation elsewhere.
32620 * Lower bound is included, upper bound
32621 * is excluded.
32622 * For example '123.4' and '1.4e7'.
32623 * {number} precision A number between 0 and 16 to round
32624 * the digits of the number.
32625 * In case of notations 'exponential' and
32626 * 'auto', `precision` defines the total
32627 * number of significant digits returned
32628 * and is undefined by default.
32629 * In case of notation 'fixed',
32630 * `precision` defines the number of
32631 * significant digits after the decimal
32632 * point, and is 0 by default.
32633 * {Object} exponential An object containing two parameters,
32634 * {number} lower and {number} upper,
32635 * used by notation 'auto' to determine
32636 * when to return exponential notation.
32637 * Default values are `lower=1e-3` and
32638 * `upper=1e5`.
32639 * Only applicable for notation `auto`.
32640 * {Function} fn A custom formatting function. Can be used to override the
32641 * built-in notations. Function `fn` is called with `value` as
32642 * parameter and must return a string. Is useful for example to
32643 * format all values inside a matrix in a particular way.
32644 *
32645 * Examples:
32646 *
32647 * format(6.4); // '6.4'
32648 * format(1240000); // '1.24e6'
32649 * format(1/3); // '0.3333333333333333'
32650 * format(1/3, 3); // '0.333'
32651 * format(21385, 2); // '21000'
32652 * format(12.071, {notation: 'fixed'}); // '12'
32653 * format(2.3, {notation: 'fixed', precision: 2}); // '2.30'
32654 * format(52.8, {notation: 'exponential'}); // '5.28e+1'
32655 *
32656 * @param {BigNumber} value
32657 * @param {Object | Function | number} [options]
32658 * @return {string} str The formatted value
32659 */
32660exports.format = function (value, options) {
32661 if (typeof options === 'function') {
32662 // handle format(value, fn)
32663 return options(value);
32664 }
32665
32666 // handle special cases
32667 if (!value.isFinite()) {
32668 return value.isNaN() ? 'NaN' : (value.gt(0) ? 'Infinity' : '-Infinity');
32669 }
32670
32671 // default values for options
32672 var notation = 'auto';
32673 var precision = undefined;
32674
32675 if (options !== undefined) {
32676 // determine notation from options
32677 if (options.notation) {
32678 notation = options.notation;
32679 }
32680
32681 // determine precision from options
32682 if (typeof options === 'number') {
32683 precision = options;
32684 }
32685 else if (options.precision) {
32686 precision = options.precision;
32687 }
32688 }
32689
32690 // handle the various notations
32691 switch (notation) {
32692 case 'fixed':
32693 return exports.toFixed(value, precision);
32694
32695 case 'exponential':
32696 return exports.toExponential(value, precision);
32697
32698 case 'auto':
32699 // determine lower and upper bound for exponential notation.
32700 // TODO: implement support for upper and lower to be BigNumbers themselves
32701 var lower = 1e-3;
32702 var upper = 1e5;
32703 if (options && options.exponential) {
32704 if (options.exponential.lower !== undefined) {
32705 lower = options.exponential.lower;
32706 }
32707 if (options.exponential.upper !== undefined) {
32708 upper = options.exponential.upper;
32709 }
32710 }
32711
32712 // adjust the configuration of the BigNumber constructor (yeah, this is quite tricky...)
32713 var oldConfig = {
32714 toExpNeg: value.constructor.toExpNeg,
32715 toExpPos: value.constructor.toExpPos
32716 };
32717
32718 value.constructor.config({
32719 toExpNeg: Math.round(Math.log(lower) / Math.LN10),
32720 toExpPos: Math.round(Math.log(upper) / Math.LN10)
32721 });
32722
32723 // handle special case zero
32724 if (value.isZero()) return '0';
32725
32726 // determine whether or not to output exponential notation
32727 var str;
32728 var abs = value.abs();
32729 if (abs.gte(lower) && abs.lt(upper)) {
32730 // normal number notation
32731 str = value.toSignificantDigits(precision).toFixed();
32732 }
32733 else {
32734 // exponential notation
32735 str = exports.toExponential(value, precision);
32736 }
32737
32738 // remove trailing zeros after the decimal point
32739 return str.replace(/((\.\d*?)(0+))($|e)/, function () {
32740 var digits = arguments[2];
32741 var e = arguments[4];
32742 return (digits !== '.') ? digits + e : e;
32743 });
32744
32745 default:
32746 throw new Error('Unknown notation "' + notation + '". ' +
32747 'Choose "auto", "exponential", or "fixed".');
32748 }
32749};
32750
32751/**
32752 * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3'
32753 * @param {BigNumber} value
32754 * @param {number} [precision] Number of digits in formatted output.
32755 * If not provided, the maximum available digits
32756 * is used.
32757 * @returns {string} str
32758 */
32759exports.toExponential = function (value, precision) {
32760 if (precision !== undefined) {
32761 return value.toExponential(precision - 1); // Note the offset of one
32762 }
32763 else {
32764 return value.toExponential();
32765 }
32766};
32767
32768/**
32769 * Format a number with fixed notation.
32770 * @param {BigNumber} value
32771 * @param {number} [precision=0] Optional number of decimals after the
32772 * decimal point. Zero by default.
32773 */
32774exports.toFixed = function (value, precision) {
32775 return value.toFixed(precision || 0);
32776 // Note: the (precision || 0) is needed as the toFixed of BigNumber has an
32777 // undefined default precision instead of 0.
32778};
32779
32780
32781/***/ }),
32782/* 169 */
32783/***/ (function(module, exports, __webpack_require__) {
32784
32785"use strict";
32786
32787
32788function factory (type, config, load, typed) {
32789 /**
32790 * Wrap any value in a chain, allowing to perform chained operations on
32791 * the value.
32792 *
32793 * All methods available in the math.js library can be called upon the chain,
32794 * and then will be evaluated with the value itself as first argument.
32795 * The chain can be closed by executing `chain.done()`, which returns
32796 * the final value.
32797 *
32798 * The chain has a number of special functions:
32799 *
32800 * - `done()` Finalize the chain and return the chain's value.
32801 * - `valueOf()` The same as `done()`
32802 * - `toString()` Executes `math.format()` onto the chain's value, returning
32803 * a string representation of the value.
32804 *
32805 * Syntax:
32806 *
32807 * math.chain(value)
32808 *
32809 * Examples:
32810 *
32811 * math.chain(3)
32812 * .add(4)
32813 * .subtract(2)
32814 * .done(); // 5
32815 *
32816 * math.chain( [[1, 2], [3, 4]] )
32817 * .subset(math.index(0, 0), 8)
32818 * .multiply(3)
32819 * .done(); // [[24, 6], [9, 12]]
32820 *
32821 * @param {*} [value] A value of any type on which to start a chained operation.
32822 * @return {math.type.Chain} The created chain
32823 */
32824 return typed('chain', {
32825 '': function() {
32826 return new type.Chain();
32827 },
32828
32829 'any': function(value) {
32830 return new type.Chain(value);
32831 }
32832 });
32833}
32834
32835exports.name = 'chain';
32836exports.factory = factory;
32837
32838
32839/***/ }),
32840/* 170 */
32841/***/ (function(module, exports, __webpack_require__) {
32842
32843module.exports = [
32844 // type
32845 __webpack_require__(92),
32846
32847 // construction function
32848 __webpack_require__(172)
32849];
32850
32851
32852/***/ }),
32853/* 171 */
32854/***/ (function(module, exports, __webpack_require__) {
32855
32856var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
32857 * @license Complex.js v2.0.3 11/02/2016
32858 *
32859 * Copyright (c) 2016, Robert Eisele (robert@xarg.org)
32860 * Dual licensed under the MIT or GPL Version 2 licenses.
32861 **/
32862
32863/**
32864 *
32865 * This class allows the manipulation of complex numbers.
32866 * You can pass a complex number in different formats. Either as object, double, string or two integer parameters.
32867 *
32868 * Object form
32869 * { re: <real>, im: <imaginary> }
32870 * { arg: <angle>, abs: <radius> }
32871 * { phi: <angle>, r: <radius> }
32872 *
32873 * Array / Vector form
32874 * [ real, imaginary ]
32875 *
32876 * Double form
32877 * 99.3 - Single double value
32878 *
32879 * String form
32880 * '23.1337' - Simple real number
32881 * '15+3i' - a simple complex number
32882 * '3-i' - a simple complex number
32883 *
32884 * Example:
32885 *
32886 * var c = new Complex('99.3+8i');
32887 * c.mul({r: 3, i: 9}).div(4.9).sub(3, 2);
32888 *
32889 */
32890
32891(function(root) {
32892
32893 'use strict';
32894
32895 var P = {'re': 0, 'im': 0};
32896
32897 var cosh = function(x) {
32898 return (Math.exp(x) + Math.exp(-x)) * 0.5;
32899 };
32900
32901 var sinh = function(x) {
32902 return (Math.exp(x) - Math.exp(-x)) * 0.5;
32903 };
32904
32905 var hypot = function(x, y) {
32906
32907 var a = Math.abs(x);
32908 var b = Math.abs(y);
32909
32910 if (a < 3000 && b < 3000) {
32911 return Math.sqrt(a * a + b * b);
32912 }
32913
32914 if (a < b) {
32915 a = b;
32916 b = x / y;
32917 } else {
32918 b = y / x;
32919 }
32920 return a * Math.sqrt(1 + b * b);
32921 };
32922
32923 var parser_exit = function() {
32924 throw SyntaxError('Invalid Param');
32925 };
32926
32927 /**
32928 * Calculates log(sqrt(a^2+b^2)) in a way to avoid overflows
32929 *
32930 * @param {number} a
32931 * @param {number} b
32932 * @returns {number}
32933 */
32934 function logHypot(a, b) {
32935
32936 var _a = Math.abs(a);
32937 var _b = Math.abs(b);
32938
32939 if (a === 0) {
32940 return Math.log(_b);
32941 }
32942
32943 if (b === 0) {
32944 return Math.log(_a);
32945 }
32946
32947 if (_a < 3000 && _b < 3000) {
32948 return Math.log(a * a + b * b) * 0.5;
32949 }
32950
32951 /* I got 4 ideas to compute this property without overflow:
32952 *
32953 * Testing 1000000 times with random samples for a,b ∈ [1, 1000000000] against a big decimal library to get an error estimate
32954 *
32955 * 1. Only eliminate the square root: (OVERALL ERROR: 3.9122483030951116e-11)
32956
32957 Math.log(a * a + b * b) / 2
32958
32959 *
32960 *
32961 * 2. Try to use the non-overflowing pythagoras: (OVERALL ERROR: 8.889760039210159e-10)
32962
32963 var fn = function(a, b) {
32964 a = Math.abs(a);
32965 b = Math.abs(b);
32966 var t = Math.min(a, b);
32967 a = Math.max(a, b);
32968 t = t / a;
32969
32970 return Math.log(a) + Math.log(1 + t * t) / 2;
32971 };
32972
32973 * 3. Abuse the identity cos(atan(y/x) = x / sqrt(x^2+y^2): (OVERALL ERROR: 3.4780178737037204e-10)
32974
32975 Math.log(a / Math.cos(Math.atan2(b, a)))
32976
32977 * 4. Use 3. and apply log rules: (OVERALL ERROR: 1.2014087502620896e-9)
32978
32979 Math.log(a) - Math.log(Math.cos(Math.atan2(b, a)))
32980
32981 */
32982
32983 return Math.log(a / Math.cos(Math.atan2(b, a)));
32984 }
32985
32986 var parse = function(a, b) {
32987
32988 if (a === undefined || a === null) {
32989 P['re'] =
32990 P['im'] = 0;
32991 } else if (b !== undefined) {
32992 P['re'] = a;
32993 P['im'] = b;
32994 } else switch (typeof a) {
32995
32996 case 'object':
32997
32998 if ('im' in a && 're' in a) {
32999 P['re'] = a['re'];
33000 P['im'] = a['im'];
33001 } else if ('abs' in a && 'arg' in a) {
33002 P['re'] = a['abs'] * Math.cos(a['arg']);
33003 P['im'] = a['abs'] * Math.sin(a['arg']);
33004 } else if ('r' in a && 'phi' in a) {
33005 P['re'] = a['r'] * Math.cos(a['phi']);
33006 P['im'] = a['r'] * Math.sin(a['phi']);
33007 } else if (a.length === 2) { // Quick array check
33008 P['re'] = a[0];
33009 P['im'] = a[1];
33010 } else {
33011 parser_exit();
33012 }
33013 break;
33014
33015 case 'string':
33016
33017 P['im'] = /* void */
33018 P['re'] = 0;
33019
33020 var tokens = a.match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g);
33021 var plus = 1;
33022 var minus = 0;
33023
33024 if (tokens === null) {
33025 parser_exit();
33026 }
33027
33028 for (var i = 0; i < tokens.length; i++) {
33029
33030 var c = tokens[i];
33031
33032 if (c === ' ' || c === '\t' || c === '\n') {
33033 /* void */
33034 } else if (c === '+') {
33035 plus++;
33036 } else if (c === '-') {
33037 minus++;
33038 } else if (c === 'i' || c === 'I') {
33039
33040 if (plus + minus === 0) {
33041 parser_exit();
33042 }
33043
33044 if (tokens[i + 1] !== ' ' && !isNaN(tokens[i + 1])) {
33045 P['im']+= parseFloat((minus % 2 ? '-' : '') + tokens[i + 1]);
33046 i++;
33047 } else {
33048 P['im']+= parseFloat((minus % 2 ? '-' : '') + '1');
33049 }
33050 plus = minus = 0;
33051
33052 } else {
33053
33054 if (plus + minus === 0 || isNaN(c)) {
33055 parser_exit();
33056 }
33057
33058 if (tokens[i + 1] === 'i' || tokens[i + 1] === 'I') {
33059 P['im']+= parseFloat((minus % 2 ? '-' : '') + c);
33060 i++;
33061 } else {
33062 P['re']+= parseFloat((minus % 2 ? '-' : '') + c);
33063 }
33064 plus = minus = 0;
33065 }
33066 }
33067
33068 // Still something on the stack
33069 if (plus + minus > 0) {
33070 parser_exit();
33071 }
33072 break;
33073
33074 case 'number':
33075 P['im'] = 0;
33076 P['re'] = a;
33077 break;
33078
33079 default:
33080 parser_exit();
33081 }
33082
33083 if (isNaN(P['re']) || isNaN(P['im'])) {
33084 // If a calculation is NaN, we treat it as NaN and don't throw
33085 //parser_exit();
33086 }
33087 };
33088
33089 /**
33090 * @constructor
33091 * @returns {Complex}
33092 */
33093 function Complex(a, b) {
33094
33095 if (!(this instanceof Complex)) {
33096 return new Complex(a, b);
33097 }
33098
33099 parse(a, b); // mutates P
33100
33101 this['re'] = P['re'];
33102 this['im'] = P['im'];
33103 }
33104
33105 Complex.prototype = {
33106
33107 're': 0,
33108 'im': 0,
33109
33110 /**
33111 * Calculates the sign of a complex number, which is a normalized complex
33112 *
33113 * @returns {Complex}
33114 */
33115 'sign': function() {
33116
33117 var abs = this['abs']();
33118
33119 return new Complex(
33120 this['re'] / abs,
33121 this['im'] / abs);
33122 },
33123
33124 /**
33125 * Adds two complex numbers
33126 *
33127 * @returns {Complex}
33128 */
33129 'add': function(a, b) {
33130
33131 parse(a, b); // mutates P
33132
33133 return new Complex(
33134 this['re'] + P['re'],
33135 this['im'] + P['im']);
33136 },
33137
33138 /**
33139 * Subtracts two complex numbers
33140 *
33141 * @returns {Complex}
33142 */
33143 'sub': function(a, b) {
33144
33145 parse(a, b); // mutates P
33146
33147 return new Complex(
33148 this['re'] - P['re'],
33149 this['im'] - P['im']);
33150 },
33151
33152 /**
33153 * Multiplies two complex numbers
33154 *
33155 * @returns {Complex}
33156 */
33157 'mul': function(a, b) {
33158
33159 parse(a, b); // mutates P
33160
33161 // Besides the addition/subtraction, this helps having a solution for real Infinity
33162 if (P['im'] === 0 && this['im'] === 0) {
33163 return new Complex(this['re'] * P['re'], 0);
33164 }
33165
33166 return new Complex(
33167 this['re'] * P['re'] - this['im'] * P['im'],
33168 this['re'] * P['im'] + this['im'] * P['re']);
33169 },
33170
33171 /**
33172 * Divides two complex numbers
33173 *
33174 * @returns {Complex}
33175 */
33176 'div': function(a, b) {
33177
33178 parse(a, b); // mutates P
33179
33180 a = this['re'];
33181 b = this['im'];
33182
33183 var c = P['re'];
33184 var d = P['im'];
33185 var t, x;
33186
33187 if (0 === d) {
33188 if (0 === c) {
33189 // Divisor is zero
33190 return new Complex(
33191 (a !== 0) ? (a / 0) : 0,
33192 (b !== 0) ? (b / 0) : 0);
33193 } else {
33194 // Divisor is real
33195 return new Complex(a / c, b / c);
33196 }
33197 }
33198
33199 if (Math.abs(c) < Math.abs(d)) {
33200
33201 x = c / d;
33202 t = c * x + d;
33203
33204 return new Complex(
33205 (a * x + b) / t,
33206 (b * x - a) / t);
33207
33208 } else {
33209
33210 x = d / c;
33211 t = d * x + c;
33212
33213 return new Complex(
33214 (a + b * x) / t,
33215 (b - a * x) / t);
33216 }
33217 },
33218
33219 /**
33220 * Calculate the power of two complex numbers
33221 *
33222 * @returns {Complex}
33223 */
33224 'pow': function(a, b) {
33225
33226 parse(a, b); // mutates P
33227
33228 a = this['re'];
33229 b = this['im'];
33230
33231 if (a === 0 && b === 0) {
33232 return Complex['ZERO'];
33233 }
33234
33235 // If the exponent is real
33236 if (P['im'] === 0) {
33237
33238 if (b === 0 && a >= 0) {
33239
33240 return new Complex(Math.pow(a, P['re']), 0);
33241
33242 } else if (a === 0) { // If base is fully imaginary
33243
33244 switch ((P['re'] % 4 + 4) % 4) {
33245 case 0:
33246 return new Complex(Math.pow(b, P['re']), 0);
33247 case 1:
33248 return new Complex(0, Math.pow(b, P['re']));
33249 case 2:
33250 return new Complex(-Math.pow(b, P['re']), 0);
33251 case 3:
33252 return new Complex(0, -Math.pow(b, P['re']));
33253 }
33254 }
33255 }
33256
33257 /* I couldn't find a good formula, so here is a derivation and optimization
33258 *
33259 * z_1^z_2 = (a + bi)^(c + di)
33260 * = exp((c + di) * log(a + bi)
33261 * = pow(a^2 + b^2, (c + di) / 2) * exp(i(c + di)atan2(b, a))
33262 * =>...
33263 * 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))
33264 * 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))
33265 *
33266 * =>...
33267 * 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))
33268 * 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))
33269 *
33270 * =>
33271 * Re = exp(c * logsq2 - d * arg(z_1)) * cos(d * logsq2 + c * arg(z_1))
33272 * Im = exp(c * logsq2 - d * arg(z_1)) * sin(d * logsq2 + c * arg(z_1))
33273 *
33274 */
33275
33276 var arg = Math.atan2(b, a);
33277 var loh = logHypot(a, b);
33278
33279 a = Math.exp(P['re'] * loh - P['im'] * arg);
33280 b = P['im'] * loh + P['re'] * arg;
33281 return new Complex(
33282 a * Math.cos(b),
33283 a * Math.sin(b));
33284 },
33285
33286 /**
33287 * Calculate the complex square root
33288 *
33289 * @returns {Complex}
33290 */
33291 'sqrt': function() {
33292
33293 var a = this['re'];
33294 var b = this['im'];
33295 var r = this['abs']();
33296
33297 var re, im;
33298
33299 if (a >= 0) {
33300
33301 if (b === 0) {
33302 return new Complex(Math.sqrt(a), 0);
33303 }
33304
33305 re = 0.5 * Math.sqrt(2.0 * (r + a));
33306 } else {
33307 re = Math.abs(b) / Math.sqrt(2 * (r - a));
33308 }
33309
33310 if (a <= 0) {
33311 im = 0.5 * Math.sqrt(2.0 * (r - a));
33312 } else {
33313 im = Math.abs(b) / Math.sqrt(2 * (r + a));
33314 }
33315
33316 return new Complex(re, b < 0 ? -im : im);
33317 },
33318
33319 /**
33320 * Calculate the complex exponent
33321 *
33322 * @returns {Complex}
33323 */
33324 'exp': function() {
33325
33326 var tmp = Math.exp(this['re']);
33327
33328 if (this['im'] === 0) {
33329 //return new Complex(tmp, 0);
33330 }
33331 return new Complex(
33332 tmp * Math.cos(this['im']),
33333 tmp * Math.sin(this['im']));
33334 },
33335
33336 /**
33337 * Calculate the natural log
33338 *
33339 * @returns {Complex}
33340 */
33341 'log': function() {
33342
33343 var a = this['re'];
33344 var b = this['im'];
33345
33346 if (b === 0 && a > 0) {
33347 //return new Complex(Math.log(a), 0);
33348 }
33349
33350 return new Complex(
33351 logHypot(a, b),
33352 Math.atan2(b, a));
33353 },
33354
33355 /**
33356 * Calculate the magnitude of the complex number
33357 *
33358 * @returns {number}
33359 */
33360 'abs': function() {
33361
33362 return hypot(this['re'], this['im']);
33363 },
33364
33365 /**
33366 * Calculate the angle of the complex number
33367 *
33368 * @returns {number}
33369 */
33370 'arg': function() {
33371
33372 return Math.atan2(this['im'], this['re']);
33373 },
33374
33375 /**
33376 * Calculate the sine of the complex number
33377 *
33378 * @returns {Complex}
33379 */
33380 'sin': function() {
33381
33382 // sin(c) = (e^b - e^(-b)) / (2i)
33383
33384 var a = this['re'];
33385 var b = this['im'];
33386
33387 return new Complex(
33388 Math.sin(a) * cosh(b),
33389 Math.cos(a) * sinh(b));
33390 },
33391
33392 /**
33393 * Calculate the cosine
33394 *
33395 * @returns {Complex}
33396 */
33397 'cos': function() {
33398
33399 // cos(z) = (e^b + e^(-b)) / 2
33400
33401 var a = this['re'];
33402 var b = this['im'];
33403
33404 return new Complex(
33405 Math.cos(a) * cosh(b),
33406 -Math.sin(a) * sinh(b));
33407 },
33408
33409 /**
33410 * Calculate the tangent
33411 *
33412 * @returns {Complex}
33413 */
33414 'tan': function() {
33415
33416 // tan(c) = (e^(ci) - e^(-ci)) / (i(e^(ci) + e^(-ci)))
33417
33418 var a = 2 * this['re'];
33419 var b = 2 * this['im'];
33420 var d = Math.cos(a) + cosh(b);
33421
33422 return new Complex(
33423 Math.sin(a) / d,
33424 sinh(b) / d);
33425 },
33426
33427 /**
33428 * Calculate the cotangent
33429 *
33430 * @returns {Complex}
33431 */
33432 'cot': function() {
33433
33434 // cot(c) = i(e^(ci) + e^(-ci)) / (e^(ci) - e^(-ci))
33435
33436 var a = 2 * this['re'];
33437 var b = 2 * this['im'];
33438 var d = Math.cos(a) - cosh(b);
33439
33440 return new Complex(
33441 -Math.sin(a) / d,
33442 sinh(b) / d);
33443 },
33444
33445 /**
33446 * Calculate the secant
33447 *
33448 * @returns {Complex}
33449 */
33450 'sec': function() {
33451
33452 // sec(c) = 2 / (e^(ci) + e^(-ci))
33453
33454 var a = this['re'];
33455 var b = this['im'];
33456 var d = 0.5 * cosh(2 * b) + 0.5 * Math.cos(2 * a);
33457
33458 return new Complex(
33459 Math.cos(a) * cosh(b) / d,
33460 Math.sin(a) * sinh(b) / d);
33461 },
33462
33463 /**
33464 * Calculate the cosecans
33465 *
33466 * @returns {Complex}
33467 */
33468 'csc': function() {
33469
33470 // csc(c) = 2i / (e^(ci) - e^(-ci))
33471
33472 var a = this['re'];
33473 var b = this['im'];
33474 var d = 0.5 * cosh(2 * b) - 0.5 * Math.cos(2 * a);
33475
33476 return new Complex(
33477 Math.sin(a) * cosh(b) / d,
33478 -Math.cos(a) * sinh(b) / d);
33479 },
33480
33481 /**
33482 * Calculate the complex arcus sinus
33483 *
33484 * @returns {Complex}
33485 */
33486 'asin': function() {
33487
33488 // asin(c) = -i * log(ci + sqrt(1 - c^2))
33489
33490 var a = this['re'];
33491 var b = this['im'];
33492
33493 var t1 = new Complex(
33494 b * b - a * a + 1,
33495 -2 * a * b)['sqrt']();
33496
33497 var t2 = new Complex(
33498 t1['re'] - b,
33499 t1['im'] + a)['log']();
33500
33501 return new Complex(t2['im'], -t2['re']);
33502 },
33503
33504 /**
33505 * Calculate the complex arcus cosinus
33506 *
33507 * @returns {Complex}
33508 */
33509 'acos': function() {
33510
33511 // acos(c) = i * log(c - i * sqrt(1 - c^2))
33512
33513 var a = this['re'];
33514 var b = this['im'];
33515
33516 var t1 = new Complex(
33517 b * b - a * a + 1,
33518 -2 * a * b)['sqrt']();
33519
33520 var t2 = new Complex(
33521 t1['re'] - b,
33522 t1['im'] + a)['log']();
33523
33524 return new Complex(Math.PI / 2 - t2['im'], t2['re']);
33525 },
33526
33527 /**
33528 * Calculate the complex arcus tangent
33529 *
33530 * @returns {Complex}
33531 */
33532 'atan': function() {
33533
33534 // atan(c) = i / 2 log((i + x) / (i - x))
33535
33536 var a = this['re'];
33537 var b = this['im'];
33538
33539 if (a === 0) {
33540
33541 if (b === 1) {
33542 return new Complex(0, Infinity);
33543 }
33544
33545 if (b === -1) {
33546 return new Complex(0, -Infinity);
33547 }
33548 }
33549
33550 var d = a * a + (1.0 - b) * (1.0 - b);
33551
33552 var t1 = new Complex(
33553 (1 - b * b - a * a) / d,
33554 -2 * a / d).log();
33555
33556 return new Complex(-0.5 * t1['im'], 0.5 * t1['re']);
33557 },
33558
33559 /**
33560 * Calculate the complex arcus cotangent
33561 *
33562 * @returns {Complex}
33563 */
33564 'acot': function() {
33565
33566 // acot(c) = i / 2 log((c - i) / (c + i))
33567
33568 var a = this['re'];
33569 var b = this['im'];
33570
33571 if (b === 0) {
33572 return new Complex(Math.atan2(1, a), 0);
33573 }
33574
33575 var d = a * a + b * b;
33576 return (d !== 0)
33577 ? new Complex(
33578 a / d,
33579 -b / d).atan()
33580 : new Complex(
33581 (a !== 0) ? a / 0 : 0,
33582 (b !== 0) ?-b / 0 : 0).atan();
33583 },
33584
33585 /**
33586 * Calculate the complex arcus secant
33587 *
33588 * @returns {Complex}
33589 */
33590 'asec': function() {
33591
33592 // asec(c) = -i * log(1 / c + sqrt(1 - i / c^2))
33593
33594 var a = this['re'];
33595 var b = this['im'];
33596
33597 if (a === 0 && b === 0) {
33598 return new Complex(0, Infinity);
33599 }
33600
33601 var d = a * a + b * b;
33602 return (d !== 0)
33603 ? new Complex(
33604 a / d,
33605 -b / d).acos()
33606 : new Complex(
33607 (a !== 0) ? a / 0 : 0,
33608 (b !== 0) ?-b / 0 : 0).acos();
33609 },
33610
33611 /**
33612 * Calculate the complex arcus cosecans
33613 *
33614 * @returns {Complex}
33615 */
33616 'acsc': function() {
33617
33618 // acsc(c) = -i * log(i / c + sqrt(1 - 1 / c^2))
33619
33620 var a = this['re'];
33621 var b = this['im'];
33622
33623 if (a === 0 && b === 0) {
33624 return new Complex(Math.PI / 2, Infinity);
33625 }
33626
33627 var d = a * a + b * b;
33628 return (d !== 0)
33629 ? new Complex(
33630 a / d,
33631 -b / d).asin()
33632 : new Complex(
33633 (a !== 0) ? a / 0 : 0,
33634 (b !== 0) ?-b / 0 : 0).asin();
33635 },
33636
33637 /**
33638 * Calculate the complex sinh
33639 *
33640 * @returns {Complex}
33641 */
33642 'sinh': function() {
33643
33644 // sinh(c) = (e^c - e^-c) / 2
33645
33646 var a = this['re'];
33647 var b = this['im'];
33648
33649 return new Complex(
33650 sinh(a) * Math.cos(b),
33651 cosh(a) * Math.sin(b));
33652 },
33653
33654 /**
33655 * Calculate the complex cosh
33656 *
33657 * @returns {Complex}
33658 */
33659 'cosh': function() {
33660
33661 // cosh(c) = (e^c + e^-c) / 2
33662
33663 var a = this['re'];
33664 var b = this['im'];
33665
33666 return new Complex(
33667 cosh(a) * Math.cos(b),
33668 sinh(a) * Math.sin(b));
33669 },
33670
33671 /**
33672 * Calculate the complex tanh
33673 *
33674 * @returns {Complex}
33675 */
33676 'tanh': function() {
33677
33678 // tanh(c) = (e^c - e^-c) / (e^c + e^-c)
33679
33680 var a = 2 * this['re'];
33681 var b = 2 * this['im'];
33682 var d = cosh(a) + Math.cos(b);
33683
33684 return new Complex(
33685 sinh(a) / d,
33686 Math.sin(b) / d);
33687 },
33688
33689 /**
33690 * Calculate the complex coth
33691 *
33692 * @returns {Complex}
33693 */
33694 'coth': function() {
33695
33696 // coth(c) = (e^c + e^-c) / (e^c - e^-c)
33697
33698 var a = 2 * this['re'];
33699 var b = 2 * this['im'];
33700 var d = cosh(a) - Math.cos(b);
33701
33702 return new Complex(
33703 sinh(a) / d,
33704 -Math.sin(b) / d);
33705 },
33706
33707 /**
33708 * Calculate the complex coth
33709 *
33710 * @returns {Complex}
33711 */
33712 'csch': function() {
33713
33714 // csch(c) = 2 / (e^c - e^-c)
33715
33716 var a = this['re'];
33717 var b = this['im'];
33718 var d = Math.cos(2 * b) - cosh(2 * a);
33719
33720 return new Complex(
33721 -2 * sinh(a) * Math.cos(b) / d,
33722 2 * cosh(a) * Math.sin(b) / d);
33723 },
33724
33725 /**
33726 * Calculate the complex sech
33727 *
33728 * @returns {Complex}
33729 */
33730 'sech': function() {
33731
33732 // sech(c) = 2 / (e^c + e^-c)
33733
33734 var a = this['re'];
33735 var b = this['im'];
33736 var d = Math.cos(2 * b) + cosh(2 * a);
33737
33738 return new Complex(
33739 2 * cosh(a) * Math.cos(b) / d,
33740 -2 * sinh(a) * Math.sin(b) / d);
33741 },
33742
33743 /**
33744 * Calculate the complex asinh
33745 *
33746 * @returns {Complex}
33747 */
33748 'asinh': function() {
33749
33750 // asinh(c) = log(c + sqrt(c^2 + 1))
33751
33752 var tmp = this['im'];
33753 this['im'] = -this['re'];
33754 this['re'] = tmp;
33755 var res = this['asin']();
33756
33757 this['re'] = -this['im'];
33758 this['im'] = tmp;
33759 tmp = res['re'];
33760
33761 res['re'] = -res['im'];
33762 res['im'] = tmp;
33763 return res;
33764 },
33765
33766 /**
33767 * Calculate the complex asinh
33768 *
33769 * @returns {Complex}
33770 */
33771 'acosh': function() {
33772
33773 // acosh(c) = log(c + sqrt(c^2 - 1))
33774
33775 var tmp;
33776 var res = this['acos']();
33777 if (res['im'] <= 0) {
33778 tmp = res['re'];
33779 res['re'] = -res['im'];
33780 res['im'] = tmp;
33781 } else {
33782 tmp = res['im'];
33783 res['im'] = -res['re'];
33784 res['re'] = tmp;
33785 }
33786 return res;
33787 },
33788
33789 /**
33790 * Calculate the complex atanh
33791 *
33792 * @returns {Complex}
33793 */
33794 'atanh': function() {
33795
33796 // atanh(c) = log((1+c) / (1-c)) / 2
33797
33798 var a = this['re'];
33799 var b = this['im'];
33800
33801 var noIM = a > 1 && b === 0;
33802 var oneMinus = 1 - a;
33803 var onePlus = 1 + a;
33804 var d = oneMinus * oneMinus + b * b;
33805
33806 var x = (d !== 0)
33807 ? new Complex(
33808 (onePlus * oneMinus - b * b) / d,
33809 (b * oneMinus + onePlus * b) / d)
33810 : new Complex(
33811 (a !== -1) ? (a / 0) : 0,
33812 (b !== 0) ? (b / 0) : 0);
33813
33814 var temp = x['re'];
33815 x['re'] = logHypot(x['re'], x['im']) / 2;
33816 x['im'] = Math.atan2(x['im'], temp) / 2;
33817 if (noIM) {
33818 x['im'] = -x['im'];
33819 }
33820 return x;
33821 },
33822
33823 /**
33824 * Calculate the complex acoth
33825 *
33826 * @returns {Complex}
33827 */
33828 'acoth': function() {
33829
33830 // acoth(c) = log((c+1) / (c-1)) / 2
33831
33832 var a = this['re'];
33833 var b = this['im'];
33834
33835 if (a === 0 && b === 0) {
33836
33837 return new Complex(0, Math.PI / 2);
33838 }
33839
33840 var d = a * a + b * b;
33841 return (d !== 0)
33842 ? new Complex(
33843 a / d,
33844 -b / d).atanh()
33845 : new Complex(
33846 (a !== 0) ? a / 0 : 0,
33847 (b !== 0) ?-b / 0 : 0).atanh();
33848 },
33849
33850 /**
33851 * Calculate the complex acsch
33852 *
33853 * @returns {Complex}
33854 */
33855 'acsch': function() {
33856
33857 // acsch(c) = log((1+sqrt(1+c^2))/c)
33858
33859 var a = this['re'];
33860 var b = this['im'];
33861
33862 if (b === 0) {
33863
33864 return new Complex(
33865 (a !== 0)
33866 ? Math.log(a + Math.sqrt(a * a + 1))
33867 : Infinity, 0);
33868 }
33869
33870 var d = a * a + b * b;
33871 return (d !== 0)
33872 ? new Complex(
33873 a / d,
33874 -b / d).asinh()
33875 : new Complex(
33876 (a !== 0) ? a / 0 : 0,
33877 (b !== 0) ?-b / 0 : 0).asinh();
33878 },
33879
33880 /**
33881 * Calculate the complex asech
33882 *
33883 * @returns {Complex}
33884 */
33885 'asech': function() {
33886
33887 // asech(c) = log((1+sqrt(1-c^2))/c)
33888
33889 var a = this['re'];
33890 var b = this['im'];
33891
33892 if (a === 0 && b === 0) {
33893 return new Complex(Infinity, 0);
33894 }
33895
33896 var d = a * a + b * b;
33897 return (d !== 0)
33898 ? new Complex(
33899 a / d,
33900 -b / d).acosh()
33901 : new Complex(
33902 (a !== 0) ? a / 0 : 0,
33903 (b !== 0) ?-b / 0 : 0).acosh();
33904 },
33905
33906 /**
33907 * Calculate the complex inverse 1/z
33908 *
33909 * @returns {Complex}
33910 */
33911 'inverse': function() {
33912
33913 var a = this['re'];
33914 var b = this['im'];
33915
33916 var d = a * a + b * b;
33917
33918 return new Complex(
33919 a !== 0 ? a / d : 0,
33920 b !== 0 ?-b / d : 0);
33921 },
33922
33923 /**
33924 * Returns the complex conjugate
33925 *
33926 * @returns {Complex}
33927 */
33928 'conjugate': function() {
33929
33930 return new Complex(this['re'], -this['im']);
33931 },
33932
33933 /**
33934 * Gets the negated complex number
33935 *
33936 * @returns {Complex}
33937 */
33938 'neg': function() {
33939
33940 return new Complex(-this['re'], -this['im']);
33941 },
33942
33943 /**
33944 * Ceils the actual complex number
33945 *
33946 * @returns {Complex}
33947 */
33948 'ceil': function(places) {
33949
33950 places = Math.pow(10, places || 0);
33951
33952 return new Complex(
33953 Math.ceil(this['re'] * places) / places,
33954 Math.ceil(this['im'] * places) / places);
33955 },
33956
33957 /**
33958 * Floors the actual complex number
33959 *
33960 * @returns {Complex}
33961 */
33962 'floor': function(places) {
33963
33964 places = Math.pow(10, places || 0);
33965
33966 return new Complex(
33967 Math.floor(this['re'] * places) / places,
33968 Math.floor(this['im'] * places) / places);
33969 },
33970
33971 /**
33972 * Ceils the actual complex number
33973 *
33974 * @returns {Complex}
33975 */
33976 'round': function(places) {
33977
33978 places = Math.pow(10, places || 0);
33979
33980 return new Complex(
33981 Math.round(this['re'] * places) / places,
33982 Math.round(this['im'] * places) / places);
33983 },
33984
33985 /**
33986 * Compares two complex numbers
33987 *
33988 * @returns {boolean}
33989 */
33990 'equals': function(a, b) {
33991
33992 parse(a, b); // mutates P
33993
33994 return Math.abs(P['re'] - this['re']) <= Complex['EPSILON'] &&
33995 Math.abs(P['im'] - this['im']) <= Complex['EPSILON'];
33996 },
33997
33998 /**
33999 * Clones the actual object
34000 *
34001 * @returns {Complex}
34002 */
34003 'clone': function() {
34004
34005 return new Complex(this['re'], this['im']);
34006 },
34007
34008 /**
34009 * Gets a string of the actual complex number
34010 *
34011 * @returns {string}
34012 */
34013 'toString': function() {
34014
34015 var a = this['re'];
34016 var b = this['im'];
34017 var ret = '';
34018
34019 if (isNaN(a) || isNaN(b)) {
34020 return 'NaN';
34021 }
34022
34023 if (a !== 0) {
34024 ret+= a;
34025 }
34026
34027 if (b !== 0) {
34028
34029 if (a !== 0) {
34030 ret+= b < 0 ? ' - ' : ' + ';
34031 } else if (b < 0) {
34032 ret+= '-';
34033 }
34034
34035 b = Math.abs(b);
34036
34037 if (1 !== b) {
34038 ret+= b;
34039 }
34040 ret+= 'i';
34041 }
34042
34043 if (!ret)
34044 return '0';
34045
34046 return ret;
34047 },
34048
34049 /**
34050 * Returns the actual number as a vector
34051 *
34052 * @returns {Array}
34053 */
34054 'toVector': function() {
34055
34056 return [this['re'], this['im']];
34057 },
34058
34059 /**
34060 * Returns the actual real value of the current object
34061 *
34062 * @returns {number|null}
34063 */
34064 'valueOf': function() {
34065
34066 if (this['im'] === 0) {
34067 return this['re'];
34068 }
34069 return null;
34070 },
34071
34072 /**
34073 * Checks if the given complex number is not a number
34074 *
34075 * @returns {boolean}
34076 */
34077 'isNaN': function() {
34078 return isNaN(this['re']) || isNaN(this['im']);
34079 },
34080
34081 /**
34082 * Checks if the given complex number is finite
34083 *
34084 * @returns {boolean}
34085 */
34086 'isFinite': function() {
34087 return isFinite(this['re']) && isFinite(this['im']);
34088 }
34089 };
34090
34091 Complex['ZERO'] = new Complex(0, 0);
34092 Complex['ONE'] = new Complex(1, 0);
34093 Complex['I'] = new Complex(0, 1);
34094 Complex['PI'] = new Complex(Math.PI, 0);
34095 Complex['E'] = new Complex(Math.E, 0);
34096 Complex['EPSILON'] = 1e-16;
34097
34098 if (true) {
34099 !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() {
34100 return Complex;
34101 }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
34102 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
34103 } else if (typeof exports === 'object') {
34104 module['exports'] = Complex;
34105 } else {
34106 root['Complex'] = Complex;
34107 }
34108
34109})(this);
34110
34111
34112/***/ }),
34113/* 172 */
34114/***/ (function(module, exports, __webpack_require__) {
34115
34116"use strict";
34117
34118
34119var deepMap = __webpack_require__(1);
34120
34121function factory (type, config, load, typed) {
34122 var latex = __webpack_require__(4);
34123
34124 /**
34125 * Create a complex value or convert a value to a complex value.
34126 *
34127 * Syntax:
34128 *
34129 * math.complex() // creates a complex value with zero
34130 * // as real and imaginary part.
34131 * math.complex(re : number, im : string) // creates a complex value with provided
34132 * // values for real and imaginary part.
34133 * math.complex(re : number) // creates a complex value with provided
34134 * // real value and zero imaginary part.
34135 * math.complex(complex : Complex) // clones the provided complex value.
34136 * math.complex(arg : string) // parses a string into a complex value.
34137 * math.complex(array : Array) // converts the elements of the array
34138 * // or matrix element wise into a
34139 * // complex value.
34140 * math.complex({re: number, im: number}) // creates a complex value with provided
34141 * // values for real an imaginary part.
34142 * math.complex({r: number, phi: number}) // creates a complex value with provided
34143 * // polar coordinates
34144 *
34145 * Examples:
34146 *
34147 * var a = math.complex(3, -4); // a = Complex 3 - 4i
34148 * a.re = 5; // a = Complex 5 - 4i
34149 * var i = a.im; // Number -4;
34150 * var b = math.complex('2 + 6i'); // Complex 2 + 6i
34151 * var c = math.complex(); // Complex 0 + 0i
34152 * var d = math.add(a, b); // Complex 5 + 2i
34153 *
34154 * See also:
34155 *
34156 * bignumber, boolean, index, matrix, number, string, unit
34157 *
34158 * @param {* | Array | Matrix} [args]
34159 * Arguments specifying the real and imaginary part of the complex number
34160 * @return {Complex | Array | Matrix} Returns a complex value
34161 */
34162 var complex = typed('complex', {
34163 '': function () {
34164 return type.Complex.ZERO;
34165 },
34166
34167 'number': function (x) {
34168 return new type.Complex(x, 0);
34169 },
34170
34171 'number, number': function (re, im) {
34172 return new type.Complex(re, im);
34173 },
34174
34175 // TODO: this signature should be redundant
34176 'BigNumber, BigNumber': function (re, im) {
34177 return new type.Complex(re.toNumber(), im.toNumber());
34178 },
34179
34180 'Complex': function (x) {
34181 return x.clone();
34182 },
34183
34184 'string': function (x) {
34185 return type.Complex(x); // for example '2 + 3i'
34186 },
34187
34188 'Object': function (x) {
34189 if('re' in x && 'im' in x) {
34190 return new type.Complex(x.re, x.im);
34191 }
34192
34193 if ('r' in x && 'phi' in x) {
34194 return new type.Complex(x);
34195 }
34196
34197 throw new Error('Expected object with either properties re and im, or properties r and phi.');
34198 },
34199
34200 'Array | Matrix': function (x) {
34201 return deepMap(x, complex);
34202 }
34203 });
34204
34205 complex.toTex = {
34206 0: '0',
34207 1: '\\left(${args[0]}\\right)',
34208 2: '\\left(\\left(${args[0]}\\right)+'
34209 + latex.symbols['i'] + '\\cdot\\left(${args[1]}\\right)\\right)'
34210 };
34211
34212 return complex;
34213}
34214
34215exports.name = 'complex';
34216exports.factory = factory;
34217
34218
34219/***/ }),
34220/* 173 */
34221/***/ (function(module, exports, __webpack_require__) {
34222
34223"use strict";
34224
34225
34226// Map the characters to escape to their escaped values. The list is derived
34227// from http://www.cespedes.org/blog/85/how-to-escape-latex-special-characters
34228
34229var defaultEscapes = {
34230 "{": "\\{",
34231 "}": "\\}",
34232 "\\": "\\textbackslash{}",
34233 "#": "\\#",
34234 $: "\\$",
34235 "%": "\\%",
34236 "&": "\\&",
34237 "^": "\\textasciicircum{}",
34238 _: "\\_",
34239 "~": "\\textasciitilde{}"
34240};
34241var formatEscapes = {
34242 "–": "\\--",
34243 "—": "\\---",
34244 " ": "~",
34245 "\t": "\\qquad{}",
34246 "\r\n": "\\\\newline{}",
34247 "\n": "\\\\newline{}"
34248};
34249
34250var defaultEscapeMapFn = function defaultEscapeMapFn(defaultEscapes, formatEscapes) {
34251 return Object.assign({}, defaultEscapes, formatEscapes);
34252};
34253
34254/**
34255 * Escape a string to be used in LaTeX documents.
34256 * @param {string} str the string to be escaped.
34257 * @param {boolean} params.preserveFormatting whether formatting escapes should
34258 * be performed (default: false).
34259 * @param {function} params.escapeMapFn the function to modify the escape maps.
34260 * @return {string} the escaped string, ready to be used in LaTeX.
34261 */
34262module.exports = function (str) {
34263 var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
34264 _ref$preserveFormatti = _ref.preserveFormatting,
34265 preserveFormatting = _ref$preserveFormatti === undefined ? false : _ref$preserveFormatti,
34266 _ref$escapeMapFn = _ref.escapeMapFn,
34267 escapeMapFn = _ref$escapeMapFn === undefined ? defaultEscapeMapFn : _ref$escapeMapFn;
34268
34269 var runningStr = String(str);
34270 var result = "";
34271
34272 var escapes = escapeMapFn(Object.assign({}, defaultEscapes), preserveFormatting ? Object.assign({}, formatEscapes) : {});
34273 var escapeKeys = Object.keys(escapes); // as it is reused later on
34274
34275 // Algorithm: Go through the string character by character, if it matches
34276 // with one of the special characters then we'll replace it with the escaped
34277 // version.
34278
34279 var _loop = function _loop() {
34280 var specialCharFound = false;
34281 escapeKeys.forEach(function (key, index) {
34282 if (specialCharFound) {
34283 return;
34284 }
34285 if (runningStr.startsWith(key)) {
34286 result += escapes[escapeKeys[index]];
34287 runningStr = runningStr.slice(key.length, runningStr.length);
34288 specialCharFound = true;
34289 }
34290 });
34291 if (!specialCharFound) {
34292 result += runningStr.slice(0, 1);
34293 runningStr = runningStr.slice(1, runningStr.length);
34294 }
34295 };
34296
34297 while (runningStr) {
34298 _loop();
34299 }
34300 return result;
34301};
34302
34303/***/ }),
34304/* 174 */
34305/***/ (function(module, exports, __webpack_require__) {
34306
34307module.exports = [
34308 // type
34309 __webpack_require__(175),
34310
34311 // construction function
34312 __webpack_require__(93)
34313];
34314
34315
34316/***/ }),
34317/* 175 */
34318/***/ (function(module, exports, __webpack_require__) {
34319
34320var Fraction = __webpack_require__(176);
34321
34322/**
34323 * Attach type information
34324 */
34325Fraction.prototype.type = 'Fraction';
34326Fraction.prototype.isFraction = true;
34327
34328/**
34329 * Get a JSON representation of a Fraction containing type information
34330 * @returns {Object} Returns a JSON object structured as:
34331 * `{"mathjs": "Fraction", "n": 3, "d": 8}`
34332 */
34333Fraction.prototype.toJSON = function () {
34334 return {
34335 mathjs: 'Fraction',
34336 n: this.s * this.n,
34337 d: this.d
34338 };
34339};
34340
34341/**
34342 * Instantiate a Fraction from a JSON object
34343 * @param {Object} json a JSON object structured as:
34344 * `{"mathjs": "Fraction", "n": 3, "d": 8}`
34345 * @return {BigNumber}
34346 */
34347Fraction.fromJSON = function (json) {
34348 return new Fraction(json);
34349};
34350
34351
34352function factory (type, config, load, typed) {
34353 return Fraction;
34354}
34355
34356exports.name = 'Fraction';
34357exports.path = 'type';
34358exports.factory = factory;
34359
34360
34361/***/ }),
34362/* 176 */
34363/***/ (function(module, exports, __webpack_require__) {
34364
34365var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
34366 * @license Fraction.js v4.0.4 09/09/2015
34367 * http://www.xarg.org/2014/03/rational-numbers-in-javascript/
34368 *
34369 * Copyright (c) 2015, Robert Eisele (robert@xarg.org)
34370 * Dual licensed under the MIT or GPL Version 2 licenses.
34371 **/
34372
34373
34374/**
34375 *
34376 * This class offers the possibility to calculate fractions.
34377 * You can pass a fraction in different formats. Either as array, as double, as string or as an integer.
34378 *
34379 * Array/Object form
34380 * [ 0 => <nominator>, 1 => <denominator> ]
34381 * [ n => <nominator>, d => <denominator> ]
34382 *
34383 * Integer form
34384 * - Single integer value
34385 *
34386 * Double form
34387 * - Single double value
34388 *
34389 * String form
34390 * 123.456 - a simple double
34391 * 123/456 - a string fraction
34392 * 123.'456' - a double with repeating decimal places
34393 * 123.(456) - synonym
34394 * 123.45'6' - a double with repeating last place
34395 * 123.45(6) - synonym
34396 *
34397 * Example:
34398 *
34399 * var f = new Fraction("9.4'31'");
34400 * f.mul([-4, 3]).div(4.9);
34401 *
34402 */
34403
34404(function (root) {
34405
34406 "use strict";
34407
34408 // Maximum search depth for cyclic rational numbers. 2000 should be more than enough.
34409 // Example: 1/7 = 0.(142857) has 6 repeating decimal places.
34410 // If MAX_CYCLE_LEN gets reduced, long cycles will not be detected and toString() only gets the first 10 digits
34411 var MAX_CYCLE_LEN = 2000;
34412
34413 // Parsed data to avoid calling "new" all the time
34414 var P = {
34415 "s": 1,
34416 "n": 0,
34417 "d": 1
34418 };
34419
34420 function createError(name) {
34421 var errorConstructor = function () {
34422 var temp = Error.apply(this, arguments);
34423 temp.name = this.name = name;
34424 this.stack = temp.stack;
34425 this.message = temp.message;
34426 };
34427
34428 var IntermediateInheritor = function () {};
34429 IntermediateInheritor.prototype = Error.prototype;
34430 errorConstructor.prototype = new IntermediateInheritor();
34431
34432 return errorConstructor;
34433 }
34434
34435 var DivisionByZero = Fraction['DivisionByZero'] = createError('DivisionByZero');
34436 var InvalidParameter = Fraction['InvalidParameter'] = createError('InvalidParameter');
34437
34438 function assign(n, s) {
34439
34440 if (isNaN(n = parseInt(n, 10))) {
34441 throwInvalidParam();
34442 }
34443 return n * s;
34444 }
34445
34446 function throwInvalidParam() {
34447 throw new InvalidParameter();
34448 }
34449
34450 var parse = function (p1, p2) {
34451
34452 var n = 0, d = 1, s = 1;
34453 var v = 0, w = 0, x = 0, y = 1, z = 1;
34454
34455 var A = 0, B = 1;
34456 var C = 1, D = 1;
34457
34458 var N = 10000000;
34459 var M;
34460
34461 if (p1 === undefined || p1 === null) {
34462 /* void */
34463 } else if (p2 !== undefined) {
34464 n = p1;
34465 d = p2;
34466 s = n * d;
34467 } else
34468 switch (typeof p1) {
34469
34470 case "object":
34471 {
34472 if ("d" in p1 && "n" in p1) {
34473 n = p1["n"];
34474 d = p1["d"];
34475 if ("s" in p1)
34476 n*= p1["s"];
34477 } else if (0 in p1) {
34478 n = p1[0];
34479 if (1 in p1)
34480 d = p1[1];
34481 } else {
34482 throwInvalidParam();
34483 }
34484 s = n * d;
34485 break;
34486 }
34487 case "number":
34488 {
34489 if (p1 < 0) {
34490 s = p1;
34491 p1 = -p1;
34492 }
34493
34494 if (p1 % 1 === 0) {
34495 n = p1;
34496 } else if (p1 > 0) { // check for != 0, scale would become NaN (log(0)), which converges really slow
34497
34498 if (p1 >= 1) {
34499 z = Math.pow(10, Math.floor(1 + Math.log(p1) / Math.LN10));
34500 p1/= z;
34501 }
34502
34503 // Using Farey Sequences
34504 // http://www.johndcook.com/blog/2010/10/20/best-rational-approximation/
34505
34506 while (B <= N && D <= N) {
34507 M = (A + C) / (B + D);
34508
34509 if (p1 === M) {
34510 if (B + D <= N) {
34511 n = A + C;
34512 d = B + D;
34513 } else if (D > B) {
34514 n = C;
34515 d = D;
34516 } else {
34517 n = A;
34518 d = B;
34519 }
34520 break;
34521
34522 } else {
34523
34524 if (p1 > M) {
34525 A+= C;
34526 B+= D;
34527 } else {
34528 C+= A;
34529 D+= B;
34530 }
34531
34532 if (B > N) {
34533 n = C;
34534 d = D;
34535 } else {
34536 n = A;
34537 d = B;
34538 }
34539 }
34540 }
34541 n*= z;
34542 } else if (isNaN(p1) || isNaN(p2)) {
34543 d = n = NaN;
34544 }
34545 break;
34546 }
34547 case "string":
34548 {
34549 B = p1.match(/\d+|./g);
34550
34551 if (B === null)
34552 throwInvalidParam();
34553
34554 if (B[A] === '-') {// Check for minus sign at the beginning
34555 s = -1;
34556 A++;
34557 } else if (B[A] === '+') {// Check for plus sign at the beginning
34558 A++;
34559 }
34560
34561 if (B.length === A + 1) { // Check if it's just a simple number "1234"
34562 w = assign(B[A++], s);
34563 } else if (B[A + 1] === '.' || B[A] === '.') { // Check if it's a decimal number
34564
34565 if (B[A] !== '.') { // Handle 0.5 and .5
34566 v = assign(B[A++], s);
34567 }
34568 A++;
34569
34570 // Check for decimal places
34571 if (A + 1 === B.length || B[A + 1] === '(' && B[A + 3] === ')' || B[A + 1] === "'" && B[A + 3] === "'") {
34572 w = assign(B[A], s);
34573 y = Math.pow(10, B[A].length);
34574 A++;
34575 }
34576
34577 // Check for repeating places
34578 if (B[A] === '(' && B[A + 2] === ')' || B[A] === "'" && B[A + 2] === "'") {
34579 x = assign(B[A + 1], s);
34580 z = Math.pow(10, B[A + 1].length) - 1;
34581 A+= 3;
34582 }
34583
34584 } else if (B[A + 1] === '/' || B[A + 1] === ':') { // Check for a simple fraction "123/456" or "123:456"
34585 w = assign(B[A], s);
34586 y = assign(B[A + 2], 1);
34587 A+= 3;
34588 } else if (B[A + 3] === '/' && B[A + 1] === ' ') { // Check for a complex fraction "123 1/2"
34589 v = assign(B[A], s);
34590 w = assign(B[A + 2], s);
34591 y = assign(B[A + 4], 1);
34592 A+= 5;
34593 }
34594
34595 if (B.length <= A) { // Check for more tokens on the stack
34596 d = y * z;
34597 s = /* void */
34598 n = x + d * v + z * w;
34599 break;
34600 }
34601
34602 /* Fall through on error */
34603 }
34604 default:
34605 throwInvalidParam();
34606 }
34607
34608 if (d === 0) {
34609 throw new DivisionByZero();
34610 }
34611
34612 P["s"] = s < 0 ? -1 : 1;
34613 P["n"] = Math.abs(n);
34614 P["d"] = Math.abs(d);
34615 };
34616
34617 var modpow = function (b, e, m) {
34618
34619 for (var r = 1; e > 0; b = (b * b) % m, e >>= 1) {
34620
34621 if (e & 1) {
34622 r = (r * b) % m;
34623 }
34624 }
34625 return r;
34626 };
34627
34628 var cycleLen = function (n, d) {
34629
34630 for (; d % 2 === 0;
34631 d/= 2) {}
34632
34633 for (; d % 5 === 0;
34634 d/= 5) {}
34635
34636 if (d === 1) // Catch non-cyclic numbers
34637 return 0;
34638
34639 // If we would like to compute really large numbers quicker, we could make use of Fermat's little theorem:
34640 // 10^(d-1) % d == 1
34641 // However, we don't need such large numbers and MAX_CYCLE_LEN should be the capstone,
34642 // as we want to translate the numbers to strings.
34643
34644 var rem = 10 % d;
34645
34646 for (var t = 1; rem !== 1; t++) {
34647 rem = rem * 10 % d;
34648
34649 if (t > MAX_CYCLE_LEN)
34650 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`
34651 }
34652 return t;
34653 };
34654
34655 var cycleStart = function (n, d, len) {
34656
34657 var rem1 = 1;
34658 var rem2 = modpow(10, len, d);
34659
34660 for (var t = 0; t < 300; t++) { // s < ~log10(Number.MAX_VALUE)
34661 // Solve 10^s == 10^(s+t) (mod d)
34662
34663 if (rem1 === rem2)
34664 return t;
34665
34666 rem1 = rem1 * 10 % d;
34667 rem2 = rem2 * 10 % d;
34668 }
34669 return 0;
34670 };
34671
34672 var gcd = function (a, b) {
34673
34674 if (!a) return b;
34675 if (!b) return a;
34676
34677 while (1) {
34678 a%= b;
34679 if (!a) return b;
34680 b%= a;
34681 if (!b) return a;
34682 }
34683 };
34684
34685 /**
34686 * Module constructor
34687 *
34688 * @constructor
34689 * @param {number|Fraction} a
34690 * @param {number=} b
34691 */
34692 function Fraction(a, b) {
34693
34694 if (!(this instanceof Fraction)) {
34695 return new Fraction(a, b);
34696 }
34697
34698 parse(a, b);
34699
34700 if (Fraction['REDUCE']) {
34701 a = gcd(P["d"], P["n"]); // Abuse a
34702 } else {
34703 a = 1;
34704 }
34705
34706 this["s"] = P["s"];
34707 this["n"] = P["n"] / a;
34708 this["d"] = P["d"] / a;
34709 }
34710
34711 /**
34712 * Boolean global variable to be able to disable automatic reduction of the fraction
34713 *
34714 */
34715 Fraction['REDUCE'] = 1;
34716
34717 Fraction.prototype = {
34718
34719 "s": 1,
34720 "n": 0,
34721 "d": 1,
34722
34723 /**
34724 * Calculates the absolute value
34725 *
34726 * Ex: new Fraction(-4).abs() => 4
34727 **/
34728 "abs": function () {
34729
34730 return new Fraction(this["n"], this["d"]);
34731 },
34732
34733 /**
34734 * Inverts the sign of the current fraction
34735 *
34736 * Ex: new Fraction(-4).neg() => 4
34737 **/
34738 "neg": function () {
34739
34740 return new Fraction(-this["s"] * this["n"], this["d"]);
34741 },
34742
34743 /**
34744 * Adds two rational numbers
34745 *
34746 * Ex: new Fraction({n: 2, d: 3}).add("14.9") => 467 / 30
34747 **/
34748 "add": function (a, b) {
34749
34750 parse(a, b);
34751 return new Fraction(
34752 this["s"] * this["n"] * P["d"] + P["s"] * this["d"] * P["n"],
34753 this["d"] * P["d"]
34754 );
34755 },
34756
34757 /**
34758 * Subtracts two rational numbers
34759 *
34760 * Ex: new Fraction({n: 2, d: 3}).add("14.9") => -427 / 30
34761 **/
34762 "sub": function (a, b) {
34763
34764 parse(a, b);
34765 return new Fraction(
34766 this["s"] * this["n"] * P["d"] - P["s"] * this["d"] * P["n"],
34767 this["d"] * P["d"]
34768 );
34769 },
34770
34771 /**
34772 * Multiplies two rational numbers
34773 *
34774 * Ex: new Fraction("-17.(345)").mul(3) => 5776 / 111
34775 **/
34776 "mul": function (a, b) {
34777
34778 parse(a, b);
34779 return new Fraction(
34780 this["s"] * P["s"] * this["n"] * P["n"],
34781 this["d"] * P["d"]
34782 );
34783 },
34784
34785 /**
34786 * Divides two rational numbers
34787 *
34788 * Ex: new Fraction("-17.(345)").inverse().div(3)
34789 **/
34790 "div": function (a, b) {
34791
34792 parse(a, b);
34793 return new Fraction(
34794 this["s"] * P["s"] * this["n"] * P["d"],
34795 this["d"] * P["n"]
34796 );
34797 },
34798
34799 /**
34800 * Clones the actual object
34801 *
34802 * Ex: new Fraction("-17.(345)").clone()
34803 **/
34804 "clone": function () {
34805 return new Fraction(this);
34806 },
34807
34808 /**
34809 * Calculates the modulo of two rational numbers - a more precise fmod
34810 *
34811 * Ex: new Fraction('4.(3)').mod([7, 8]) => (13/3) % (7/8) = (5/6)
34812 **/
34813 "mod": function (a, b) {
34814
34815 if (isNaN(this['n']) || isNaN(this['d'])) {
34816 return new Fraction(NaN);
34817 }
34818
34819 if (a === undefined) {
34820 return new Fraction(this["s"] * this["n"] % this["d"], 1);
34821 }
34822
34823 parse(a, b);
34824 if (0 === P["n"] && 0 === this["d"]) {
34825 Fraction(0, 0); // Throw DivisionByZero
34826 }
34827
34828 /*
34829 * First silly attempt, kinda slow
34830 *
34831 return that["sub"]({
34832 "n": num["n"] * Math.floor((this.n / this.d) / (num.n / num.d)),
34833 "d": num["d"],
34834 "s": this["s"]
34835 });*/
34836
34837 /*
34838 * New attempt: a1 / b1 = a2 / b2 * q + r
34839 * => b2 * a1 = a2 * b1 * q + b1 * b2 * r
34840 * => (b2 * a1 % a2 * b1) / (b1 * b2)
34841 */
34842 return new Fraction(
34843 (this["s"] * P["d"] * this["n"]) % (P["n"] * this["d"]),
34844 P["d"] * this["d"]
34845 );
34846 },
34847
34848 /**
34849 * Calculates the fractional gcd of two rational numbers
34850 *
34851 * Ex: new Fraction(5,8).gcd(3,7) => 1/56
34852 */
34853 "gcd": function (a, b) {
34854
34855 parse(a, b);
34856
34857 // gcd(a / b, c / d) = gcd(a, c) / lcm(b, d)
34858
34859 return new Fraction(gcd(P["n"], this["n"]), P["d"] * this["d"] / gcd(P["d"], this["d"]));
34860 },
34861
34862 /**
34863 * Calculates the fractional lcm of two rational numbers
34864 *
34865 * Ex: new Fraction(5,8).lcm(3,7) => 15
34866 */
34867 "lcm": function (a, b) {
34868
34869 parse(a, b);
34870
34871 // lcm(a / b, c / d) = lcm(a, c) / gcd(b, d)
34872
34873 if (P["n"] === 0 && this["n"] === 0) {
34874 return new Fraction;
34875 }
34876 return new Fraction(P["n"] * this["n"] / gcd(P["n"], this["n"]), gcd(P["d"], this["d"]));
34877 },
34878
34879 /**
34880 * Calculates the ceil of a rational number
34881 *
34882 * Ex: new Fraction('4.(3)').ceil() => (5 / 1)
34883 **/
34884 "ceil": function (places) {
34885
34886 places = Math.pow(10, places || 0);
34887
34888 if (isNaN(this["n"]) || isNaN(this["d"])) {
34889 return new Fraction(NaN);
34890 }
34891 return new Fraction(Math.ceil(places * this["s"] * this["n"] / this["d"]), places);
34892 },
34893
34894 /**
34895 * Calculates the floor of a rational number
34896 *
34897 * Ex: new Fraction('4.(3)').floor() => (4 / 1)
34898 **/
34899 "floor": function (places) {
34900
34901 places = Math.pow(10, places || 0);
34902
34903 if (isNaN(this["n"]) || isNaN(this["d"])) {
34904 return new Fraction(NaN);
34905 }
34906 return new Fraction(Math.floor(places * this["s"] * this["n"] / this["d"]), places);
34907 },
34908
34909 /**
34910 * Rounds a rational numbers
34911 *
34912 * Ex: new Fraction('4.(3)').round() => (4 / 1)
34913 **/
34914 "round": function (places) {
34915
34916 places = Math.pow(10, places || 0);
34917
34918 if (isNaN(this["n"]) || isNaN(this["d"])) {
34919 return new Fraction(NaN);
34920 }
34921 return new Fraction(Math.round(places * this["s"] * this["n"] / this["d"]), places);
34922 },
34923
34924 /**
34925 * Gets the inverse of the fraction, means numerator and denumerator are exchanged
34926 *
34927 * Ex: new Fraction([-3, 4]).inverse() => -4 / 3
34928 **/
34929 "inverse": function () {
34930
34931 return new Fraction(this["s"] * this["d"], this["n"]);
34932 },
34933
34934 /**
34935 * Calculates the fraction to some integer exponent
34936 *
34937 * Ex: new Fraction(-1,2).pow(-3) => -8
34938 */
34939 "pow": function (m) {
34940
34941 if (m < 0) {
34942 return new Fraction(Math.pow(this['s'] * this["d"], -m), Math.pow(this["n"], -m));
34943 } else {
34944 return new Fraction(Math.pow(this['s'] * this["n"], m), Math.pow(this["d"], m));
34945 }
34946 },
34947
34948 /**
34949 * Check if two rational numbers are the same
34950 *
34951 * Ex: new Fraction(19.6).equals([98, 5]);
34952 **/
34953 "equals": function (a, b) {
34954
34955 parse(a, b);
34956 return this["s"] * this["n"] * P["d"] === P["s"] * P["n"] * this["d"]; // Same as compare() === 0
34957 },
34958
34959 /**
34960 * Check if two rational numbers are the same
34961 *
34962 * Ex: new Fraction(19.6).equals([98, 5]);
34963 **/
34964 "compare": function (a, b) {
34965
34966 parse(a, b);
34967 var t = (this["s"] * this["n"] * P["d"] - P["s"] * P["n"] * this["d"]);
34968 return (0 < t) - (t < 0);
34969 },
34970
34971 /**
34972 * Check if two rational numbers are divisible
34973 *
34974 * Ex: new Fraction(19.6).divisible(1.5);
34975 */
34976 "divisible": function (a, b) {
34977
34978 parse(a, b);
34979 return !(!(P["n"] * this["d"]) || ((this["n"] * P["d"]) % (P["n"] * this["d"])));
34980 },
34981
34982 /**
34983 * Returns a decimal representation of the fraction
34984 *
34985 * Ex: new Fraction("100.'91823'").valueOf() => 100.91823918239183
34986 **/
34987 'valueOf': function () {
34988
34989 return this["s"] * this["n"] / this["d"];
34990 },
34991
34992 /**
34993 * Returns a string-fraction representation of a Fraction object
34994 *
34995 * Ex: new Fraction("1.'3'").toFraction() => "4 1/3"
34996 **/
34997 'toFraction': function (excludeWhole) {
34998
34999 var whole, str = "";
35000 var n = this["n"];
35001 var d = this["d"];
35002 if (this["s"] < 0) {
35003 str+= '-';
35004 }
35005
35006 if (d === 1) {
35007 str+= n;
35008 } else {
35009
35010 if (excludeWhole && (whole = Math.floor(n / d)) > 0) {
35011 str+= whole;
35012 str+= " ";
35013 n%= d;
35014 }
35015
35016 str+= n;
35017 str+= '/';
35018 str+= d;
35019 }
35020 return str;
35021 },
35022
35023 /**
35024 * Returns a latex representation of a Fraction object
35025 *
35026 * Ex: new Fraction("1.'3'").toLatex() => "\frac{4}{3}"
35027 **/
35028 'toLatex': function (excludeWhole) {
35029
35030 var whole, str = "";
35031 var n = this["n"];
35032 var d = this["d"];
35033 if (this["s"] < 0) {
35034 str+= '-';
35035 }
35036
35037 if (d === 1) {
35038 str+= n;
35039 } else {
35040
35041 if (excludeWhole && (whole = Math.floor(n / d)) > 0) {
35042 str+= whole;
35043 n%= d;
35044 }
35045
35046 str+= "\\frac{";
35047 str+= n;
35048 str+= '}{';
35049 str+= d;
35050 str+= '}';
35051 }
35052 return str;
35053 },
35054
35055 /**
35056 * Returns an array of continued fraction elements
35057 *
35058 * Ex: new Fraction("7/8").toContinued() => [0,1,7]
35059 */
35060 'toContinued': function () {
35061
35062 var t;
35063 var a = this['n'];
35064 var b = this['d'];
35065 var res = [];
35066
35067 do {
35068 res.push(Math.floor(a / b));
35069 t = a % b;
35070 a = b;
35071 b = t;
35072 } while (a !== 1);
35073
35074 return res;
35075 },
35076
35077 /**
35078 * Creates a string representation of a fraction with all digits
35079 *
35080 * Ex: new Fraction("100.'91823'").toString() => "100.(91823)"
35081 **/
35082 'toString': function () {
35083
35084 var g;
35085 var N = this["n"];
35086 var D = this["d"];
35087
35088 if (isNaN(N) || isNaN(D)) {
35089 return "NaN";
35090 }
35091
35092 if (!Fraction['REDUCE']) {
35093 g = gcd(N, D);
35094 N/= g;
35095 D/= g;
35096 }
35097
35098 var dec = 15; // 15 = decimal places when no repitation
35099
35100 var cycLen = cycleLen(N, D); // Cycle length
35101 var cycOff = cycleStart(N, D, cycLen); // Cycle start
35102
35103 var str = this['s'] === -1 ? "-" : "";
35104
35105 str+= N / D | 0;
35106
35107 N%= D;
35108 N*= 10;
35109
35110 if (N)
35111 str+= ".";
35112
35113 if (cycLen) {
35114
35115 for (var i = cycOff; i--; ) {
35116 str+= N / D | 0;
35117 N%= D;
35118 N*= 10;
35119 }
35120 str+= "(";
35121 for (var i = cycLen; i--; ) {
35122 str+= N / D | 0;
35123 N%= D;
35124 N*= 10;
35125 }
35126 str+= ")";
35127 } else {
35128 for (var i = dec; N && i--; ) {
35129 str+= N / D | 0;
35130 N%= D;
35131 N*= 10;
35132 }
35133 }
35134 return str;
35135 }
35136 };
35137
35138 if (true) {
35139 !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
35140 return Fraction;
35141 }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
35142 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
35143 } else if (typeof exports === "object") {
35144 module["exports"] = Fraction;
35145 } else {
35146 root['Fraction'] = Fraction;
35147 }
35148
35149})(this);
35150
35151
35152/***/ }),
35153/* 177 */
35154/***/ (function(module, exports, __webpack_require__) {
35155
35156module.exports = [
35157 // types
35158 __webpack_require__(72),
35159 __webpack_require__(45),
35160 __webpack_require__(179),
35161 __webpack_require__(180),
35162 __webpack_require__(181),
35163 __webpack_require__(182),
35164 __webpack_require__(27),
35165 __webpack_require__(94),
35166
35167 // construction functions
35168 __webpack_require__(183),
35169 __webpack_require__(0),
35170 __webpack_require__(184)
35171];
35172
35173
35174/***/ }),
35175/* 178 */
35176/***/ (function(module, exports, __webpack_require__) {
35177
35178"use strict";
35179
35180
35181/**
35182 * Test whether value is a boolean
35183 * @param {*} value
35184 * @return {boolean} isBoolean
35185 */
35186exports.isBoolean = function(value) {
35187 return typeof value == 'boolean';
35188};
35189
35190
35191/***/ }),
35192/* 179 */
35193/***/ (function(module, exports, __webpack_require__) {
35194
35195"use strict";
35196
35197
35198var util = __webpack_require__(25);
35199var DimensionError = __webpack_require__(11);
35200
35201var array = util.array;
35202var object = util.object;
35203var string = util.string;
35204var number = util.number;
35205
35206var isArray = Array.isArray;
35207var isNumber = number.isNumber;
35208var isInteger = number.isInteger;
35209var isString = string.isString;
35210
35211var validateIndex = array.validateIndex;
35212
35213function factory (type, config, load, typed) {
35214 var Matrix = load(__webpack_require__(72)); // force loading Matrix (do not use via type.Matrix)
35215 var equalScalar = load(__webpack_require__(10));
35216
35217 /**
35218 * Sparse Matrix implementation. This type implements a Compressed Column Storage format
35219 * for sparse matrices.
35220 * @class SparseMatrix
35221 */
35222 function SparseMatrix(data, datatype) {
35223 if (!(this instanceof SparseMatrix))
35224 throw new SyntaxError('Constructor must be called with the new operator');
35225 if (datatype && !isString(datatype))
35226 throw new Error('Invalid datatype: ' + datatype);
35227
35228 if (type.isMatrix(data)) {
35229 // create from matrix
35230 _createFromMatrix(this, data, datatype);
35231 }
35232 else if (data && isArray(data.index) && isArray(data.ptr) && isArray(data.size)) {
35233 // initialize fields
35234 this._values = data.values;
35235 this._index = data.index;
35236 this._ptr = data.ptr;
35237 this._size = data.size;
35238 this._datatype = datatype || data.datatype;
35239 }
35240 else if (isArray(data)) {
35241 // create from array
35242 _createFromArray(this, data, datatype);
35243 }
35244 else if (data) {
35245 // unsupported type
35246 throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')');
35247 }
35248 else {
35249 // nothing provided
35250 this._values = [];
35251 this._index = [];
35252 this._ptr = [0];
35253 this._size = [0, 0];
35254 this._datatype = datatype;
35255 }
35256 }
35257
35258 var _createFromMatrix = function (matrix, source, datatype) {
35259 // check matrix type
35260 if (source.type === 'SparseMatrix') {
35261 // clone arrays
35262 matrix._values = source._values ? object.clone(source._values) : undefined;
35263 matrix._index = object.clone(source._index);
35264 matrix._ptr = object.clone(source._ptr);
35265 matrix._size = object.clone(source._size);
35266 matrix._datatype = datatype || source._datatype;
35267 }
35268 else {
35269 // build from matrix data
35270 _createFromArray(matrix, source.valueOf(), datatype || source._datatype);
35271 }
35272 };
35273
35274 var _createFromArray = function (matrix, data, datatype) {
35275 // initialize fields
35276 matrix._values = [];
35277 matrix._index = [];
35278 matrix._ptr = [];
35279 matrix._datatype = datatype;
35280 // discover rows & columns, do not use math.size() to avoid looping array twice
35281 var rows = data.length;
35282 var columns = 0;
35283
35284 // equal signature to use
35285 var eq = equalScalar;
35286 // zero value
35287 var zero = 0;
35288
35289 if (isString(datatype)) {
35290 // find signature that matches (datatype, datatype)
35291 eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar;
35292 // convert 0 to the same datatype
35293 zero = typed.convert(0, datatype);
35294 }
35295
35296 // check we have rows (empty array)
35297 if (rows > 0) {
35298 // column index
35299 var j = 0;
35300 do {
35301 // store pointer to values index
35302 matrix._ptr.push(matrix._index.length);
35303 // loop rows
35304 for (var i = 0; i < rows; i++) {
35305 // current row
35306 var row = data[i];
35307 // check row is an array
35308 if (isArray(row)) {
35309 // update columns if needed (only on first column)
35310 if (j === 0 && columns < row.length)
35311 columns = row.length;
35312 // check row has column
35313 if (j < row.length) {
35314 // value
35315 var v = row[j];
35316 // check value != 0
35317 if (!eq(v, zero)) {
35318 // store value
35319 matrix._values.push(v);
35320 // index
35321 matrix._index.push(i);
35322 }
35323 }
35324 }
35325 else {
35326 // update columns if needed (only on first column)
35327 if (j === 0 && columns < 1)
35328 columns = 1;
35329 // check value != 0 (row is a scalar)
35330 if (!eq(row, zero)) {
35331 // store value
35332 matrix._values.push(row);
35333 // index
35334 matrix._index.push(i);
35335 }
35336 }
35337 }
35338 // increment index
35339 j++;
35340 }
35341 while (j < columns);
35342 }
35343 // store number of values in ptr
35344 matrix._ptr.push(matrix._index.length);
35345 // size
35346 matrix._size = [rows, columns];
35347 };
35348
35349 SparseMatrix.prototype = new Matrix();
35350
35351 /**
35352 * Attach type information
35353 */
35354 SparseMatrix.prototype.type = 'SparseMatrix';
35355 SparseMatrix.prototype.isSparseMatrix = true;
35356
35357 /**
35358 * Get the storage format used by the matrix.
35359 *
35360 * Usage:
35361 * var format = matrix.storage() // retrieve storage format
35362 *
35363 * @memberof SparseMatrix
35364 * @return {string} The storage format.
35365 */
35366 SparseMatrix.prototype.storage = function () {
35367 return 'sparse';
35368 };
35369
35370 /**
35371 * Get the datatype of the data stored in the matrix.
35372 *
35373 * Usage:
35374 * var format = matrix.datatype() // retrieve matrix datatype
35375 *
35376 * @memberof SparseMatrix
35377 * @return {string} The datatype.
35378 */
35379 SparseMatrix.prototype.datatype = function () {
35380 return this._datatype;
35381 };
35382
35383 /**
35384 * Create a new SparseMatrix
35385 * @memberof SparseMatrix
35386 * @param {Array} data
35387 * @param {string} [datatype]
35388 */
35389 SparseMatrix.prototype.create = function (data, datatype) {
35390 return new SparseMatrix(data, datatype);
35391 };
35392
35393 /**
35394 * Get the matrix density.
35395 *
35396 * Usage:
35397 * var density = matrix.density() // retrieve matrix density
35398 *
35399 * @memberof SparseMatrix
35400 * @return {number} The matrix density.
35401 */
35402 SparseMatrix.prototype.density = function () {
35403 // rows & columns
35404 var rows = this._size[0];
35405 var columns = this._size[1];
35406 // calculate density
35407 return rows !== 0 && columns !== 0 ? (this._index.length / (rows * columns)) : 0;
35408 };
35409
35410 /**
35411 * Get a subset of the matrix, or replace a subset of the matrix.
35412 *
35413 * Usage:
35414 * var subset = matrix.subset(index) // retrieve subset
35415 * var value = matrix.subset(index, replacement) // replace subset
35416 *
35417 * @memberof SparseMatrix
35418 * @param {Index} index
35419 * @param {Array | Maytrix | *} [replacement]
35420 * @param {*} [defaultValue=0] Default value, filled in on new entries when
35421 * the matrix is resized. If not provided,
35422 * new matrix elements will be filled with zeros.
35423 */
35424 SparseMatrix.prototype.subset = function (index, replacement, defaultValue) { // check it is a pattern matrix
35425 if (!this._values)
35426 throw new Error('Cannot invoke subset on a Pattern only matrix');
35427
35428 // check arguments
35429 switch (arguments.length) {
35430 case 1:
35431 return _getsubset(this, index);
35432
35433 // intentional fall through
35434 case 2:
35435 case 3:
35436 return _setsubset(this, index, replacement, defaultValue);
35437
35438 default:
35439 throw new SyntaxError('Wrong number of arguments');
35440 }
35441 };
35442
35443 var _getsubset = function (matrix, idx) {
35444 // check idx
35445 if (!type.isIndex(idx)) {
35446 throw new TypeError('Invalid index');
35447 }
35448
35449 var isScalar = idx.isScalar();
35450 if (isScalar) {
35451 // return a scalar
35452 return matrix.get(idx.min());
35453 }
35454 // validate dimensions
35455 var size = idx.size();
35456 if (size.length != matrix._size.length) {
35457 throw new DimensionError(size.length, matrix._size.length);
35458 }
35459
35460 // vars
35461 var i, ii, k, kk;
35462
35463 // validate if any of the ranges in the index is out of range
35464 var min = idx.min();
35465 var max = idx.max();
35466 for (i = 0, ii = matrix._size.length; i < ii; i++) {
35467 validateIndex(min[i], matrix._size[i]);
35468 validateIndex(max[i], matrix._size[i]);
35469 }
35470
35471 // matrix arrays
35472 var mvalues = matrix._values;
35473 var mindex = matrix._index;
35474 var mptr = matrix._ptr;
35475
35476 // rows & columns dimensions for result matrix
35477 var rows = idx.dimension(0);
35478 var columns = idx.dimension(1);
35479
35480 // workspace & permutation vector
35481 var w = [];
35482 var pv = [];
35483
35484 // loop rows in resulting matrix
35485 rows.forEach(function (i, r) {
35486 // update permutation vector
35487 pv[i] = r[0];
35488 // mark i in workspace
35489 w[i] = true;
35490 });
35491
35492 // result matrix arrays
35493 var values = mvalues ? [] : undefined;
35494 var index = [];
35495 var ptr = [];
35496
35497 // loop columns in result matrix
35498 columns.forEach(function (j) {
35499 // update ptr
35500 ptr.push(index.length);
35501 // loop values in column j
35502 for (k = mptr[j], kk = mptr[j + 1]; k < kk; k++) {
35503 // row
35504 i = mindex[k];
35505 // check row is in result matrix
35506 if (w[i] === true) {
35507 // push index
35508 index.push(pv[i]);
35509 // check we need to process values
35510 if (values)
35511 values.push(mvalues[k]);
35512 }
35513 }
35514 });
35515 // update ptr
35516 ptr.push(index.length);
35517
35518 // return matrix
35519 return new SparseMatrix({
35520 values: values,
35521 index: index,
35522 ptr: ptr,
35523 size: size,
35524 datatype: matrix._datatype
35525 });
35526 };
35527
35528 var _setsubset = function (matrix, index, submatrix, defaultValue) {
35529 // check index
35530 if (!index || index.isIndex !== true) {
35531 throw new TypeError('Invalid index');
35532 }
35533
35534 // get index size and check whether the index contains a single value
35535 var iSize = index.size(),
35536 isScalar = index.isScalar();
35537
35538 // calculate the size of the submatrix, and convert it into an Array if needed
35539 var sSize;
35540 if (type.isMatrix(submatrix)) {
35541 // submatrix size
35542 sSize = submatrix.size();
35543 // use array representation
35544 submatrix = submatrix.toArray();
35545 }
35546 else {
35547 // get submatrix size (array, scalar)
35548 sSize = array.size(submatrix);
35549 }
35550
35551 // check index is a scalar
35552 if (isScalar) {
35553 // verify submatrix is a scalar
35554 if (sSize.length !== 0) {
35555 throw new TypeError('Scalar expected');
35556 }
35557 // set value
35558 matrix.set(index.min(), submatrix, defaultValue);
35559 }
35560 else {
35561 // validate dimensions, index size must be one or two dimensions
35562 if (iSize.length !== 1 && iSize.length !== 2) {
35563 throw new DimensionError(iSize.length, matrix._size.length, '<');
35564 }
35565
35566 // check submatrix and index have the same dimensions
35567 if (sSize.length < iSize.length) {
35568 // calculate number of missing outer dimensions
35569 var i = 0;
35570 var outer = 0;
35571 while (iSize[i] === 1 && sSize[i] === 1) {
35572 i++;
35573 }
35574 while (iSize[i] === 1) {
35575 outer++;
35576 i++;
35577 }
35578 // unsqueeze both outer and inner dimensions
35579 submatrix = array.unsqueeze(submatrix, iSize.length, outer, sSize);
35580 }
35581
35582 // check whether the size of the submatrix matches the index size
35583 if (!object.deepEqual(iSize, sSize)) {
35584 throw new DimensionError(iSize, sSize, '>');
35585 }
35586
35587 // offsets
35588 var x0 = index.min()[0];
35589 var y0 = index.min()[1];
35590
35591 // submatrix rows and columns
35592 var m = sSize[0];
35593 var n = sSize[1];
35594
35595 // loop submatrix
35596 for (var x = 0; x < m; x++) {
35597 // loop columns
35598 for (var y = 0; y < n; y++) {
35599 // value at i, j
35600 var v = submatrix[x][y];
35601 // invoke set (zero value will remove entry from matrix)
35602 matrix.set([x + x0, y + y0], v, defaultValue);
35603 }
35604 }
35605 }
35606 return matrix;
35607 };
35608
35609 /**
35610 * Get a single element from the matrix.
35611 * @memberof SparseMatrix
35612 * @param {number[]} index Zero-based index
35613 * @return {*} value
35614 */
35615 SparseMatrix.prototype.get = function (index) {
35616 if (!isArray(index))
35617 throw new TypeError('Array expected');
35618 if (index.length != this._size.length)
35619 throw new DimensionError(index.length, this._size.length);
35620
35621 // check it is a pattern matrix
35622 if (!this._values)
35623 throw new Error('Cannot invoke get on a Pattern only matrix');
35624
35625 // row and column
35626 var i = index[0];
35627 var j = index[1];
35628
35629 // check i, j are valid
35630 validateIndex(i, this._size[0]);
35631 validateIndex(j, this._size[1]);
35632
35633 // find value index
35634 var k = _getValueIndex(i, this._ptr[j], this._ptr[j + 1], this._index);
35635 // check k is prior to next column k and it is in the correct row
35636 if (k < this._ptr[j + 1] && this._index[k] === i)
35637 return this._values[k];
35638
35639 return 0;
35640 };
35641
35642 /**
35643 * Replace a single element in the matrix.
35644 * @memberof SparseMatrix
35645 * @param {number[]} index Zero-based index
35646 * @param {*} value
35647 * @param {*} [defaultValue] Default value, filled in on new entries when
35648 * the matrix is resized. If not provided,
35649 * new matrix elements will be set to zero.
35650 * @return {SparseMatrix} self
35651 */
35652 SparseMatrix.prototype.set = function (index, v, defaultValue) {
35653 if (!isArray(index))
35654 throw new TypeError('Array expected');
35655 if (index.length != this._size.length)
35656 throw new DimensionError(index.length, this._size.length);
35657
35658 // check it is a pattern matrix
35659 if (!this._values)
35660 throw new Error('Cannot invoke set on a Pattern only matrix');
35661
35662 // row and column
35663 var i = index[0];
35664 var j = index[1];
35665
35666 // rows & columns
35667 var rows = this._size[0];
35668 var columns = this._size[1];
35669
35670 // equal signature to use
35671 var eq = equalScalar;
35672 // zero value
35673 var zero = 0;
35674
35675 if (isString(this._datatype)) {
35676 // find signature that matches (datatype, datatype)
35677 eq = typed.find(equalScalar, [this._datatype, this._datatype]) || equalScalar;
35678 // convert 0 to the same datatype
35679 zero = typed.convert(0, this._datatype);
35680 }
35681
35682 // check we need to resize matrix
35683 if (i > rows - 1 || j > columns - 1) {
35684 // resize matrix
35685 _resize(this, Math.max(i + 1, rows), Math.max(j + 1, columns), defaultValue);
35686 // update rows & columns
35687 rows = this._size[0];
35688 columns = this._size[1];
35689 }
35690
35691 // check i, j are valid
35692 validateIndex(i, rows);
35693 validateIndex(j, columns);
35694
35695 // find value index
35696 var k = _getValueIndex(i, this._ptr[j], this._ptr[j + 1], this._index);
35697 // check k is prior to next column k and it is in the correct row
35698 if (k < this._ptr[j + 1] && this._index[k] === i) {
35699 // check value != 0
35700 if (!eq(v, zero)) {
35701 // update value
35702 this._values[k] = v;
35703 }
35704 else {
35705 // remove value from matrix
35706 _remove(k, j, this._values, this._index, this._ptr);
35707 }
35708 }
35709 else {
35710 // insert value @ (i, j)
35711 _insert(k, i, j, v, this._values, this._index, this._ptr);
35712 }
35713
35714 return this;
35715 };
35716
35717 var _getValueIndex = function(i, top, bottom, index) {
35718 // check row is on the bottom side
35719 if (bottom - top === 0)
35720 return bottom;
35721 // loop rows [top, bottom[
35722 for (var r = top; r < bottom; r++) {
35723 // check we found value index
35724 if (index[r] === i)
35725 return r;
35726 }
35727 // we did not find row
35728 return top;
35729 };
35730
35731 var _remove = function (k, j, values, index, ptr) {
35732 // remove value @ k
35733 values.splice(k, 1);
35734 index.splice(k, 1);
35735 // update pointers
35736 for (var x = j + 1; x < ptr.length; x++)
35737 ptr[x]--;
35738 };
35739
35740 var _insert = function (k, i, j, v, values, index, ptr) {
35741 // insert value
35742 values.splice(k, 0, v);
35743 // update row for k
35744 index.splice(k, 0, i);
35745 // update column pointers
35746 for (var x = j + 1; x < ptr.length; x++)
35747 ptr[x]++;
35748 };
35749
35750 /**
35751 * Resize the matrix to the given size. Returns a copy of the matrix when
35752 * `copy=true`, otherwise return the matrix itself (resize in place).
35753 *
35754 * @memberof SparseMatrix
35755 * @param {number[]} size The new size the matrix should have.
35756 * @param {*} [defaultValue=0] Default value, filled in on new entries.
35757 * If not provided, the matrix elements will
35758 * be filled with zeros.
35759 * @param {boolean} [copy] Return a resized copy of the matrix
35760 *
35761 * @return {Matrix} The resized matrix
35762 */
35763 SparseMatrix.prototype.resize = function (size, defaultValue, copy) {
35764 // validate arguments
35765 if (!isArray(size))
35766 throw new TypeError('Array expected');
35767 if (size.length !== 2)
35768 throw new Error('Only two dimensions matrix are supported');
35769
35770 // check sizes
35771 size.forEach(function (value) {
35772 if (!number.isNumber(value) || !number.isInteger(value) || value < 0) {
35773 throw new TypeError('Invalid size, must contain positive integers ' +
35774 '(size: ' + string.format(size) + ')');
35775 }
35776 });
35777
35778 // matrix to resize
35779 var m = copy ? this.clone() : this;
35780 // resize matrix
35781 return _resize(m, size[0], size[1], defaultValue);
35782 };
35783
35784 var _resize = function (matrix, rows, columns, defaultValue) {
35785 // value to insert at the time of growing matrix
35786 var value = defaultValue || 0;
35787
35788 // equal signature to use
35789 var eq = equalScalar;
35790 // zero value
35791 var zero = 0;
35792
35793 if (isString(matrix._datatype)) {
35794 // find signature that matches (datatype, datatype)
35795 eq = typed.find(equalScalar, [matrix._datatype, matrix._datatype]) || equalScalar;
35796 // convert 0 to the same datatype
35797 zero = typed.convert(0, matrix._datatype);
35798 // convert value to the same datatype
35799 value = typed.convert(value, matrix._datatype);
35800 }
35801
35802 // should we insert the value?
35803 var ins = !eq(value, zero);
35804
35805 // old columns and rows
35806 var r = matrix._size[0];
35807 var c = matrix._size[1];
35808
35809 var i, j, k;
35810
35811 // check we need to increase columns
35812 if (columns > c) {
35813 // loop new columns
35814 for (j = c; j < columns; j++) {
35815 // update matrix._ptr for current column
35816 matrix._ptr[j] = matrix._values.length;
35817 // check we need to insert matrix._values
35818 if (ins) {
35819 // loop rows
35820 for (i = 0; i < r; i++) {
35821 // add new matrix._values
35822 matrix._values.push(value);
35823 // update matrix._index
35824 matrix._index.push(i);
35825 }
35826 }
35827 }
35828 // store number of matrix._values in matrix._ptr
35829 matrix._ptr[columns] = matrix._values.length;
35830 }
35831 else if (columns < c) {
35832 // truncate matrix._ptr
35833 matrix._ptr.splice(columns + 1, c - columns);
35834 // truncate matrix._values and matrix._index
35835 matrix._values.splice(matrix._ptr[columns], matrix._values.length);
35836 matrix._index.splice(matrix._ptr[columns], matrix._index.length);
35837 }
35838 // update columns
35839 c = columns;
35840
35841 // check we need to increase rows
35842 if (rows > r) {
35843 // check we have to insert values
35844 if (ins) {
35845 // inserts
35846 var n = 0;
35847 // loop columns
35848 for (j = 0; j < c; j++) {
35849 // update matrix._ptr for current column
35850 matrix._ptr[j] = matrix._ptr[j] + n;
35851 // where to insert matrix._values
35852 k = matrix._ptr[j + 1] + n;
35853 // pointer
35854 var p = 0;
35855 // loop new rows, initialize pointer
35856 for (i = r; i < rows; i++, p++) {
35857 // add value
35858 matrix._values.splice(k + p, 0, value);
35859 // update matrix._index
35860 matrix._index.splice(k + p, 0, i);
35861 // increment inserts
35862 n++;
35863 }
35864 }
35865 // store number of matrix._values in matrix._ptr
35866 matrix._ptr[c] = matrix._values.length;
35867 }
35868 }
35869 else if (rows < r) {
35870 // deletes
35871 var d = 0;
35872 // loop columns
35873 for (j = 0; j < c; j++) {
35874 // update matrix._ptr for current column
35875 matrix._ptr[j] = matrix._ptr[j] - d;
35876 // where matrix._values start for next column
35877 var k0 = matrix._ptr[j];
35878 var k1 = matrix._ptr[j + 1] - d;
35879 // loop matrix._index
35880 for (k = k0; k < k1; k++) {
35881 // row
35882 i = matrix._index[k];
35883 // check we need to delete value and matrix._index
35884 if (i > rows - 1) {
35885 // remove value
35886 matrix._values.splice(k, 1);
35887 // remove item from matrix._index
35888 matrix._index.splice(k, 1);
35889 // increase deletes
35890 d++;
35891 }
35892 }
35893 }
35894 // update matrix._ptr for current column
35895 matrix._ptr[j] = matrix._values.length;
35896 }
35897 // update matrix._size
35898 matrix._size[0] = rows;
35899 matrix._size[1] = columns;
35900 // return matrix
35901 return matrix;
35902 };
35903
35904 /**
35905 * Reshape the matrix to the given size. Returns a copy of the matrix when
35906 * `copy=true`, otherwise return the matrix itself (reshape in place).
35907 *
35908 * NOTE: This might be better suited to copy by default, instead of modifying
35909 * in place. For now, it operates in place to remain consistent with
35910 * resize().
35911 *
35912 * @memberof SparseMatrix
35913 * @param {number[]} size The new size the matrix should have.
35914 * @param {boolean} [copy] Return a reshaped copy of the matrix
35915 *
35916 * @return {Matrix} The reshaped matrix
35917 */
35918 SparseMatrix.prototype.reshape = function (size, copy) {
35919
35920 // validate arguments
35921 if (!isArray(size))
35922 throw new TypeError('Array expected');
35923 if (size.length !== 2)
35924 throw new Error('Sparse matrices can only be reshaped in two dimensions');
35925
35926 // check sizes
35927 size.forEach(function (value) {
35928 if (!number.isNumber(value) || !number.isInteger(value) || value < 0) {
35929 throw new TypeError('Invalid size, must contain positive integers ' +
35930 '(size: ' + string.format(size) + ')');
35931 }
35932 });
35933
35934 // m * n must not change
35935 if(this._size[0] * this._size[1] !== size[0] * size[1]) {
35936 throw new Error('Reshaping sparse matrix will result in the wrong number of elements');
35937 }
35938
35939 // matrix to reshape
35940 var m = copy ? this.clone() : this;
35941
35942 // return unchanged if the same shape
35943 if(this._size[0] === size[0] && this._size[1] === size[1]) {
35944 return m;
35945 }
35946
35947 // Convert to COO format (generate a column index)
35948 var colIndex = [];
35949 for(var i=0; i<m._ptr.length; i++) {
35950 for(var j=0; j<m._ptr[i+1]-m._ptr[i]; j++) {
35951 colIndex.push(i);
35952 }
35953 }
35954
35955 // Clone the values array
35956 var values = m._values.slice();
35957
35958 // Clone the row index array
35959 var rowIndex = m._index.slice();
35960
35961 // Transform the (row, column) indices
35962 for(var i=0; i<m._index.length; i++) {
35963 var r1 = rowIndex[i];
35964 var c1 = colIndex[i];
35965 var flat = r1 * m._size[1] + c1;
35966 colIndex[i] = flat % size[1];
35967 rowIndex[i] = Math.floor(flat / size[1]);
35968 }
35969
35970 // Now reshaping is supposed to preserve the row-major order, BUT these sparse matrices are stored
35971 // in column-major order, so we have to reorder the value array now. One option is to use a multisort,
35972 // sorting several arrays based on some other array.
35973
35974 // OR, we could easily just:
35975
35976 // 1. Remove all values from the matrix
35977 m._values.length = 0;
35978 m._index.length = 0;
35979 m._ptr.length = size[1] + 1;
35980 m._size = size.slice();
35981 for(var i=0; i<m._ptr.length; i++) {
35982 m._ptr[i] = 0;
35983 }
35984
35985 // 2. Re-insert all elements in the proper order (simplified code from SparseMatrix.prototype.set)
35986 // This step is probably the most time-consuming
35987 for(var h=0; h<values.length; h++) {
35988 var i = rowIndex[h];
35989 var j = colIndex[h];
35990 var v = values[h];
35991 var k = _getValueIndex(i, m._ptr[j], m._ptr[j + 1], m._index);
35992 _insert(k, i, j, v, m._values, m._index, m._ptr);
35993 }
35994
35995 // The value indices are inserted out of order, but apparently that's... still OK?
35996
35997 return m;
35998 }
35999
36000 /**
36001 * Create a clone of the matrix
36002 * @memberof SparseMatrix
36003 * @return {SparseMatrix} clone
36004 */
36005 SparseMatrix.prototype.clone = function () {
36006 var m = new SparseMatrix({
36007 values: this._values ? object.clone(this._values) : undefined,
36008 index: object.clone(this._index),
36009 ptr: object.clone(this._ptr),
36010 size: object.clone(this._size),
36011 datatype: this._datatype
36012 });
36013 return m;
36014 };
36015
36016 /**
36017 * Retrieve the size of the matrix.
36018 * @memberof SparseMatrix
36019 * @returns {number[]} size
36020 */
36021 SparseMatrix.prototype.size = function() {
36022 return this._size.slice(0); // copy the Array
36023 };
36024
36025 /**
36026 * Create a new matrix with the results of the callback function executed on
36027 * each entry of the matrix.
36028 * @memberof SparseMatrix
36029 * @param {Function} callback The callback function is invoked with three
36030 * parameters: the value of the element, the index
36031 * of the element, and the Matrix being traversed.
36032 * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.
36033 *
36034 * @return {SparseMatrix} matrix
36035 */
36036 SparseMatrix.prototype.map = function (callback, skipZeros) {
36037 // check it is a pattern matrix
36038 if (!this._values)
36039 throw new Error('Cannot invoke map on a Pattern only matrix');
36040 // matrix instance
36041 var me = this;
36042 // rows and columns
36043 var rows = this._size[0];
36044 var columns = this._size[1];
36045 // invoke callback
36046 var invoke = function (v, i, j) {
36047 // invoke callback
36048 return callback(v, [i, j], me);
36049 };
36050 // invoke _map
36051 return _map(this, 0, rows - 1, 0, columns - 1, invoke, skipZeros);
36052 };
36053
36054 /**
36055 * Create a new matrix with the results of the callback function executed on the interval
36056 * [minRow..maxRow, minColumn..maxColumn].
36057 */
36058 var _map = function (matrix, minRow, maxRow, minColumn, maxColumn, callback, skipZeros) {
36059 // result arrays
36060 var values = [];
36061 var index = [];
36062 var ptr = [];
36063
36064 // equal signature to use
36065 var eq = equalScalar;
36066 // zero value
36067 var zero = 0;
36068
36069 if (isString(matrix._datatype)) {
36070 // find signature that matches (datatype, datatype)
36071 eq = typed.find(equalScalar, [matrix._datatype, matrix._datatype]) || equalScalar;
36072 // convert 0 to the same datatype
36073 zero = typed.convert(0, matrix._datatype);
36074 }
36075
36076 // invoke callback
36077 var invoke = function (v, x, y) {
36078 // invoke callback
36079 v = callback(v, x, y);
36080 // check value != 0
36081 if (!eq(v, zero)) {
36082 // store value
36083 values.push(v);
36084 // index
36085 index.push(x);
36086 }
36087 };
36088 // loop columns
36089 for (var j = minColumn; j <= maxColumn; j++) {
36090 // store pointer to values index
36091 ptr.push(values.length);
36092 // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
36093 var k0 = matrix._ptr[j];
36094 var k1 = matrix._ptr[j + 1];
36095 // row pointer
36096 var p = minRow;
36097 // loop k within [k0, k1[
36098 for (var k = k0; k < k1; k++) {
36099 // row index
36100 var i = matrix._index[k];
36101 // check i is in range
36102 if (i >= minRow && i <= maxRow) {
36103 // zero values
36104 if (!skipZeros) {
36105 for (var x = p; x < i; x++)
36106 invoke(0, x - minRow, j - minColumn);
36107 }
36108 // value @ k
36109 invoke(matrix._values[k], i - minRow, j - minColumn);
36110 }
36111 // update pointer
36112 p = i + 1;
36113 }
36114 // zero values
36115 if (!skipZeros) {
36116 for (var y = p; y <= maxRow; y++)
36117 invoke(0, y - minRow, j - minColumn);
36118 }
36119 }
36120 // store number of values in ptr
36121 ptr.push(values.length);
36122 // return sparse matrix
36123 return new SparseMatrix({
36124 values: values,
36125 index: index,
36126 ptr: ptr,
36127 size: [maxRow - minRow + 1, maxColumn - minColumn + 1]
36128 });
36129 };
36130
36131 /**
36132 * Execute a callback function on each entry of the matrix.
36133 * @memberof SparseMatrix
36134 * @param {Function} callback The callback function is invoked with three
36135 * parameters: the value of the element, the index
36136 * of the element, and the Matrix being traversed.
36137 * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.
36138 */
36139 SparseMatrix.prototype.forEach = function (callback, skipZeros) {
36140 // check it is a pattern matrix
36141 if (!this._values)
36142 throw new Error('Cannot invoke forEach on a Pattern only matrix');
36143 // matrix instance
36144 var me = this;
36145 // rows and columns
36146 var rows = this._size[0];
36147 var columns = this._size[1];
36148 // loop columns
36149 for (var j = 0; j < columns; j++) {
36150 // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
36151 var k0 = this._ptr[j];
36152 var k1 = this._ptr[j + 1];
36153 // column pointer
36154 var p = 0;
36155 // loop k within [k0, k1[
36156 for (var k = k0; k < k1; k++) {
36157 // row index
36158 var i = this._index[k];
36159 // check we need to process zeros
36160 if (!skipZeros) {
36161 // zero values
36162 for (var x = p; x < i; x++)
36163 callback(0, [x, j], me);
36164 }
36165 // value @ k
36166 callback(this._values[k], [i, j], me);
36167 // update pointer
36168 p = i + 1;
36169 }
36170 // check we need to process zeros
36171 if (!skipZeros) {
36172 // zero values
36173 for (var y = p; y < rows; y++)
36174 callback(0, [y, j], me);
36175 }
36176 }
36177 };
36178
36179 /**
36180 * Create an Array with a copy of the data of the SparseMatrix
36181 * @memberof SparseMatrix
36182 * @returns {Array} array
36183 */
36184 SparseMatrix.prototype.toArray = function () {
36185 return _toArray(this._values, this._index, this._ptr, this._size, true);
36186 };
36187
36188 /**
36189 * Get the primitive value of the SparseMatrix: a two dimensions array
36190 * @memberof SparseMatrix
36191 * @returns {Array} array
36192 */
36193 SparseMatrix.prototype.valueOf = function () {
36194 return _toArray(this._values, this._index, this._ptr, this._size, false);
36195 };
36196
36197 var _toArray = function (values, index, ptr, size, copy) {
36198 // rows and columns
36199 var rows = size[0];
36200 var columns = size[1];
36201 // result
36202 var a = [];
36203 // vars
36204 var i, j;
36205 // initialize array
36206 for (i = 0; i < rows; i++) {
36207 a[i] = [];
36208 for (j = 0; j < columns; j++)
36209 a[i][j] = 0;
36210 }
36211
36212 // loop columns
36213 for (j = 0; j < columns; j++) {
36214 // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
36215 var k0 = ptr[j];
36216 var k1 = ptr[j + 1];
36217 // loop k within [k0, k1[
36218 for (var k = k0; k < k1; k++) {
36219 // row index
36220 i = index[k];
36221 // set value (use one for pattern matrix)
36222 a[i][j] = values ? (copy ? object.clone(values[k]) : values[k]) : 1;
36223 }
36224 }
36225 return a;
36226 };
36227
36228 /**
36229 * Get a string representation of the matrix, with optional formatting options.
36230 * @memberof SparseMatrix
36231 * @param {Object | number | Function} [options] Formatting options. See
36232 * lib/utils/number:format for a
36233 * description of the available
36234 * options.
36235 * @returns {string} str
36236 */
36237 SparseMatrix.prototype.format = function (options) {
36238 // rows and columns
36239 var rows = this._size[0];
36240 var columns = this._size[1];
36241 // density
36242 var density = this.density();
36243 // rows & columns
36244 var str = 'Sparse Matrix [' + string.format(rows, options) + ' x ' + string.format(columns, options) + '] density: ' + string.format(density, options) + '\n';
36245 // loop columns
36246 for (var j = 0; j < columns; j++) {
36247 // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
36248 var k0 = this._ptr[j];
36249 var k1 = this._ptr[j + 1];
36250 // loop k within [k0, k1[
36251 for (var k = k0; k < k1; k++) {
36252 // row index
36253 var i = this._index[k];
36254 // append value
36255 str += '\n (' + string.format(i, options) + ', ' + string.format(j, options) + ') ==> ' + (this._values ? string.format(this._values[k], options) : 'X');
36256 }
36257 }
36258 return str;
36259 };
36260
36261 /**
36262 * Get a string representation of the matrix
36263 * @memberof SparseMatrix
36264 * @returns {string} str
36265 */
36266 SparseMatrix.prototype.toString = function () {
36267 return string.format(this.toArray());
36268 };
36269
36270 /**
36271 * Get a JSON representation of the matrix
36272 * @memberof SparseMatrix
36273 * @returns {Object}
36274 */
36275 SparseMatrix.prototype.toJSON = function () {
36276 return {
36277 mathjs: 'SparseMatrix',
36278 values: this._values,
36279 index: this._index,
36280 ptr: this._ptr,
36281 size: this._size,
36282 datatype: this._datatype
36283 };
36284 };
36285
36286 /**
36287 * Get the kth Matrix diagonal.
36288 *
36289 * @memberof SparseMatrix
36290 * @param {number | BigNumber} [k=0] The kth diagonal where the vector will retrieved.
36291 *
36292 * @returns {Matrix} The matrix vector with the diagonal values.
36293 */
36294 SparseMatrix.prototype.diagonal = function(k) {
36295 // validate k if any
36296 if (k) {
36297 // convert BigNumber to a number
36298 if (type.isBigNumber(k))
36299 k = k.toNumber();
36300 // is must be an integer
36301 if (!isNumber(k) || !isInteger(k)) {
36302 throw new TypeError ('The parameter k must be an integer number');
36303 }
36304 }
36305 else {
36306 // default value
36307 k = 0;
36308 }
36309
36310 var kSuper = k > 0 ? k : 0;
36311 var kSub = k < 0 ? -k : 0;
36312
36313 // rows & columns
36314 var rows = this._size[0];
36315 var columns = this._size[1];
36316
36317 // number diagonal values
36318 var n = Math.min(rows - kSub, columns - kSuper);
36319
36320 // diagonal arrays
36321 var values = [];
36322 var index = [];
36323 var ptr = [];
36324 // initial ptr value
36325 ptr[0] = 0;
36326 // loop columns
36327 for (var j = kSuper; j < columns && values.length < n; j++) {
36328 // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
36329 var k0 = this._ptr[j];
36330 var k1 = this._ptr[j + 1];
36331 // loop x within [k0, k1[
36332 for (var x = k0; x < k1; x++) {
36333 // row index
36334 var i = this._index[x];
36335 // check row
36336 if (i === j - kSuper + kSub) {
36337 // value on this column
36338 values.push(this._values[x]);
36339 // store row
36340 index[values.length - 1] = i - kSub;
36341 // exit loop
36342 break;
36343 }
36344 }
36345 }
36346 // close ptr
36347 ptr.push(values.length);
36348 // return matrix
36349 return new SparseMatrix({
36350 values: values,
36351 index: index,
36352 ptr: ptr,
36353 size: [n, 1]
36354 });
36355 };
36356
36357 /**
36358 * Generate a matrix from a JSON object
36359 * @memberof SparseMatrix
36360 * @param {Object} json An object structured like
36361 * `{"mathjs": "SparseMatrix", "values": [], "index": [], "ptr": [], "size": []}`,
36362 * where mathjs is optional
36363 * @returns {SparseMatrix}
36364 */
36365 SparseMatrix.fromJSON = function (json) {
36366 return new SparseMatrix(json);
36367 };
36368
36369 /**
36370 * Create a diagonal matrix.
36371 *
36372 * @memberof SparseMatrix
36373 * @param {Array} size The matrix size.
36374 * @param {number | Array | Matrix } value The values for the diagonal.
36375 * @param {number | BigNumber} [k=0] The kth diagonal where the vector will be filled in.
36376 * @param {string} [datatype] The Matrix datatype, values must be of this datatype.
36377 *
36378 * @returns {SparseMatrix}
36379 */
36380 SparseMatrix.diagonal = function (size, value, k, defaultValue, datatype) {
36381 if (!isArray(size))
36382 throw new TypeError('Array expected, size parameter');
36383 if (size.length !== 2)
36384 throw new Error('Only two dimensions matrix are supported');
36385
36386 // map size & validate
36387 size = size.map(function (s) {
36388 // check it is a big number
36389 if (type.isBigNumber(s)) {
36390 // convert it
36391 s = s.toNumber();
36392 }
36393 // validate arguments
36394 if (!isNumber(s) || !isInteger(s) || s < 1) {
36395 throw new Error('Size values must be positive integers');
36396 }
36397 return s;
36398 });
36399
36400 // validate k if any
36401 if (k) {
36402 // convert BigNumber to a number
36403 if (type.isBigNumber(k))
36404 k = k.toNumber();
36405 // is must be an integer
36406 if (!isNumber(k) || !isInteger(k)) {
36407 throw new TypeError ('The parameter k must be an integer number');
36408 }
36409 }
36410 else {
36411 // default value
36412 k = 0;
36413 }
36414
36415 // equal signature to use
36416 var eq = equalScalar;
36417 // zero value
36418 var zero = 0;
36419
36420 if (isString(datatype)) {
36421 // find signature that matches (datatype, datatype)
36422 eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar;
36423 // convert 0 to the same datatype
36424 zero = typed.convert(0, datatype);
36425 }
36426
36427 var kSuper = k > 0 ? k : 0;
36428 var kSub = k < 0 ? -k : 0;
36429
36430 // rows and columns
36431 var rows = size[0];
36432 var columns = size[1];
36433
36434 // number of non-zero items
36435 var n = Math.min(rows - kSub, columns - kSuper);
36436
36437 // value extraction function
36438 var _value;
36439
36440 // check value
36441 if (isArray(value)) {
36442 // validate array
36443 if (value.length !== n) {
36444 // number of values in array must be n
36445 throw new Error('Invalid value array length');
36446 }
36447 // define function
36448 _value = function (i) {
36449 // return value @ i
36450 return value[i];
36451 };
36452 }
36453 else if (type.isMatrix(value)) {
36454 // matrix size
36455 var ms = value.size();
36456 // validate matrix
36457 if (ms.length !== 1 || ms[0] !== n) {
36458 // number of values in array must be n
36459 throw new Error('Invalid matrix length');
36460 }
36461 // define function
36462 _value = function (i) {
36463 // return value @ i
36464 return value.get([i]);
36465 };
36466 }
36467 else {
36468 // define function
36469 _value = function () {
36470 // return value
36471 return value;
36472 };
36473 }
36474
36475 // create arrays
36476 var values = [];
36477 var index = [];
36478 var ptr = [];
36479
36480 // loop items
36481 for (var j = 0; j < columns; j++) {
36482 // number of rows with value
36483 ptr.push(values.length);
36484 // diagonal index
36485 var i = j - kSuper;
36486 // check we need to set diagonal value
36487 if (i >= 0 && i < n) {
36488 // get value @ i
36489 var v = _value(i);
36490 // check for zero
36491 if (!eq(v, zero)) {
36492 // column
36493 index.push(i + kSub);
36494 // add value
36495 values.push(v);
36496 }
36497 }
36498 }
36499 // last value should be number of values
36500 ptr.push(values.length);
36501 // create SparseMatrix
36502 return new SparseMatrix({
36503 values: values,
36504 index: index,
36505 ptr: ptr,
36506 size: [rows, columns]
36507 });
36508 };
36509
36510 /**
36511 * Swap rows i and j in Matrix.
36512 *
36513 * @memberof SparseMatrix
36514 * @param {number} i Matrix row index 1
36515 * @param {number} j Matrix row index 2
36516 *
36517 * @return {Matrix} The matrix reference
36518 */
36519 SparseMatrix.prototype.swapRows = function (i, j) {
36520 // check index
36521 if (!isNumber(i) || !isInteger(i) || !isNumber(j) || !isInteger(j)) {
36522 throw new Error('Row index must be positive integers');
36523 }
36524 // check dimensions
36525 if (this._size.length !== 2) {
36526 throw new Error('Only two dimensional matrix is supported');
36527 }
36528 // validate index
36529 validateIndex(i, this._size[0]);
36530 validateIndex(j, this._size[0]);
36531
36532 // swap rows
36533 SparseMatrix._swapRows(i, j, this._size[1], this._values, this._index, this._ptr);
36534 // return current instance
36535 return this;
36536 };
36537
36538 /**
36539 * Loop rows with data in column j.
36540 *
36541 * @param {number} j Column
36542 * @param {Array} values Matrix values
36543 * @param {Array} index Matrix row indeces
36544 * @param {Array} ptr Matrix column pointers
36545 * @param {Function} callback Callback function invoked for every row in column j
36546 */
36547 SparseMatrix._forEachRow = function (j, values, index, ptr, callback) {
36548 // indeces for column j
36549 var k0 = ptr[j];
36550 var k1 = ptr[j + 1];
36551 // loop
36552 for (var k = k0; k < k1; k++) {
36553 // invoke callback
36554 callback(index[k], values[k]);
36555 }
36556 };
36557
36558 /**
36559 * Swap rows x and y in Sparse Matrix data structures.
36560 *
36561 * @param {number} x Matrix row index 1
36562 * @param {number} y Matrix row index 2
36563 * @param {number} columns Number of columns in matrix
36564 * @param {Array} values Matrix values
36565 * @param {Array} index Matrix row indeces
36566 * @param {Array} ptr Matrix column pointers
36567 */
36568 SparseMatrix._swapRows = function (x, y, columns, values, index, ptr) {
36569 // loop columns
36570 for (var j = 0; j < columns; j++) {
36571 // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
36572 var k0 = ptr[j];
36573 var k1 = ptr[j + 1];
36574 // find value index @ x
36575 var kx = _getValueIndex(x, k0, k1, index);
36576 // find value index @ x
36577 var ky = _getValueIndex(y, k0, k1, index);
36578 // check both rows exist in matrix
36579 if (kx < k1 && ky < k1 && index[kx] === x && index[ky] === y) {
36580 // swap values (check for pattern matrix)
36581 if (values) {
36582 var v = values[kx];
36583 values[kx] = values[ky];
36584 values[ky] = v;
36585 }
36586 // next column
36587 continue;
36588 }
36589 // check x row exist & no y row
36590 if (kx < k1 && index[kx] === x && (ky >= k1 || index[ky] !== y)) {
36591 // value @ x (check for pattern matrix)
36592 var vx = values ? values[kx] : undefined;
36593 // insert value @ y
36594 index.splice(ky, 0, y);
36595 if (values)
36596 values.splice(ky, 0, vx);
36597 // remove value @ x (adjust array index if needed)
36598 index.splice(ky <= kx ? kx + 1 : kx, 1);
36599 if (values)
36600 values.splice(ky <= kx ? kx + 1 : kx, 1);
36601 // next column
36602 continue;
36603 }
36604 // check y row exist & no x row
36605 if (ky < k1 && index[ky] === y && (kx >= k1 || index[kx] !== x)) {
36606 // value @ y (check for pattern matrix)
36607 var vy = values ? values[ky] : undefined;
36608 // insert value @ x
36609 index.splice(kx, 0, x);
36610 if (values)
36611 values.splice(kx, 0, vy);
36612 // remove value @ y (adjust array index if needed)
36613 index.splice(kx <= ky ? ky + 1 : ky, 1);
36614 if (values)
36615 values.splice(kx <= ky ? ky + 1 : ky, 1);
36616 }
36617 }
36618 };
36619
36620 // register this type in the base class Matrix
36621 type.Matrix._storage.sparse = SparseMatrix;
36622
36623 return SparseMatrix;
36624}
36625
36626exports.name = 'SparseMatrix';
36627exports.path = 'type';
36628exports.factory = factory;
36629exports.lazy = false; // no lazy loading, as we alter type.Matrix._storage
36630
36631
36632/***/ }),
36633/* 180 */
36634/***/ (function(module, exports, __webpack_require__) {
36635
36636"use strict";
36637
36638
36639function factory (type, config, load) {
36640
36641 var add = load(__webpack_require__(20));
36642 var equalScalar = load(__webpack_require__(10));
36643
36644 /**
36645 * An ordered Sparse Accumulator is a representation for a sparse vector that includes a dense array
36646 * of the vector elements and an ordered list of non-zero elements.
36647 */
36648 function Spa() {
36649 if (!(this instanceof Spa))
36650 throw new SyntaxError('Constructor must be called with the new operator');
36651
36652 // allocate vector, TODO use typed arrays
36653 this._values = [];
36654 this._heap = new type.FibonacciHeap();
36655 }
36656
36657 /**
36658 * Attach type information
36659 */
36660 Spa.prototype.type = 'Spa';
36661 Spa.prototype.isSpa = true;
36662
36663 /**
36664 * Set the value for index i.
36665 *
36666 * @param {number} i The index
36667 * @param {number | BigNumber | Complex} The value at index i
36668 */
36669 Spa.prototype.set = function (i, v) {
36670 // check we have a value @ i
36671 if (!this._values[i]) {
36672 // insert in heap
36673 var node = this._heap.insert(i, v);
36674 // set the value @ i
36675 this._values[i] = node;
36676 }
36677 else {
36678 // update the value @ i
36679 this._values[i].value = v;
36680 }
36681 };
36682
36683 Spa.prototype.get = function (i) {
36684 var node = this._values[i];
36685 if (node)
36686 return node.value;
36687 return 0;
36688 };
36689
36690 Spa.prototype.accumulate = function (i, v) {
36691 // node @ i
36692 var node = this._values[i];
36693 if (!node) {
36694 // insert in heap
36695 node = this._heap.insert(i, v);
36696 // initialize value
36697 this._values[i] = node;
36698 }
36699 else {
36700 // accumulate value
36701 node.value = add(node.value, v);
36702 }
36703 };
36704
36705 Spa.prototype.forEach = function (from, to, callback) {
36706 // references
36707 var heap = this._heap;
36708 var values = this._values;
36709 // nodes
36710 var nodes = [];
36711 // node with minimum key, save it
36712 var node = heap.extractMinimum();
36713 if (node)
36714 nodes.push(node);
36715 // extract nodes from heap (ordered)
36716 while (node && node.key <= to) {
36717 // check it is in range
36718 if (node.key >= from) {
36719 // check value is not zero
36720 if (!equalScalar(node.value, 0)) {
36721 // invoke callback
36722 callback(node.key, node.value, this);
36723 }
36724 }
36725 // extract next node, save it
36726 node = heap.extractMinimum();
36727 if (node)
36728 nodes.push(node);
36729 }
36730 // reinsert all nodes in heap
36731 for (var i = 0; i < nodes.length; i++) {
36732 // current node
36733 var n = nodes[i];
36734 // insert node in heap
36735 node = heap.insert(n.key, n.value);
36736 // update values
36737 values[node.key] = node;
36738 }
36739 };
36740
36741 Spa.prototype.swap = function (i, j) {
36742 // node @ i and j
36743 var nodei = this._values[i];
36744 var nodej = this._values[j];
36745 // check we need to insert indeces
36746 if (!nodei && nodej) {
36747 // insert in heap
36748 nodei = this._heap.insert(i, nodej.value);
36749 // remove from heap
36750 this._heap.remove(nodej);
36751 // set values
36752 this._values[i] = nodei;
36753 this._values[j] = undefined;
36754 }
36755 else if (nodei && !nodej) {
36756 // insert in heap
36757 nodej = this._heap.insert(j, nodei.value);
36758 // remove from heap
36759 this._heap.remove(nodei);
36760 // set values
36761 this._values[j] = nodej;
36762 this._values[i] = undefined;
36763 }
36764 else if (nodei && nodej) {
36765 // swap values
36766 var v = nodei.value;
36767 nodei.value = nodej.value;
36768 nodej.value = v;
36769 }
36770 };
36771
36772 return Spa;
36773}
36774
36775exports.name = 'Spa';
36776exports.path = 'type';
36777exports.factory = factory;
36778
36779
36780/***/ }),
36781/* 181 */
36782/***/ (function(module, exports, __webpack_require__) {
36783
36784"use strict";
36785
36786
36787function factory (type, config, load, typed) {
36788
36789 var smaller = load(__webpack_require__(39));
36790 var larger = load(__webpack_require__(34));
36791
36792 var oneOverLogPhi = 1.0 / Math.log((1.0 + Math.sqrt(5.0)) / 2.0);
36793
36794 /**
36795 * Fibonacci Heap implementation, used interally for Matrix math.
36796 * @class FibonacciHeap
36797 * @constructor FibonacciHeap
36798 */
36799 function FibonacciHeap() {
36800 if (!(this instanceof FibonacciHeap))
36801 throw new SyntaxError('Constructor must be called with the new operator');
36802
36803 // initialize fields
36804 this._minimum = null;
36805 this._size = 0;
36806 }
36807
36808 /**
36809 * Attach type information
36810 */
36811 FibonacciHeap.prototype.type = 'FibonacciHeap';
36812 FibonacciHeap.prototype.isFibonacciHeap = true;
36813
36814 /**
36815 * Inserts a new data element into the heap. No heap consolidation is
36816 * performed at this time, the new node is simply inserted into the root
36817 * list of this heap. Running time: O(1) actual.
36818 * @memberof FibonacciHeap
36819 */
36820 FibonacciHeap.prototype.insert = function (key, value) {
36821 // create node
36822 var node = {
36823 key: key,
36824 value: value,
36825 degree: 0
36826 };
36827 // check we have a node in the minimum
36828 if (this._minimum) {
36829 // minimum node
36830 var minimum = this._minimum;
36831 // update left & right of node
36832 node.left = minimum;
36833 node.right = minimum.right;
36834 minimum.right = node;
36835 node.right.left = node;
36836 // update minimum node in heap if needed
36837 if (smaller(key, minimum.key)) {
36838 // node has a smaller key, use it as minimum
36839 this._minimum = node;
36840 }
36841 }
36842 else {
36843 // set left & right
36844 node.left = node;
36845 node.right = node;
36846 // this is the first node
36847 this._minimum = node;
36848 }
36849 // increment number of nodes in heap
36850 this._size++;
36851 // return node
36852 return node;
36853 };
36854
36855 /**
36856 * Returns the number of nodes in heap. Running time: O(1) actual.
36857 * @memberof FibonacciHeap
36858 */
36859 FibonacciHeap.prototype.size = function () {
36860 return this._size;
36861 };
36862
36863 /**
36864 * Removes all elements from this heap.
36865 * @memberof FibonacciHeap
36866 */
36867 FibonacciHeap.prototype.clear = function () {
36868 this._minimum = null;
36869 this._size = 0;
36870 };
36871
36872 /**
36873 * Returns true if the heap is empty, otherwise false.
36874 * @memberof FibonacciHeap
36875 */
36876 FibonacciHeap.prototype.isEmpty = function () {
36877 return this._size === 0;
36878 };
36879
36880 /**
36881 * Extracts the node with minimum key from heap. Amortized running
36882 * time: O(log n).
36883 * @memberof FibonacciHeap
36884 */
36885 FibonacciHeap.prototype.extractMinimum = function () {
36886 // node to remove
36887 var node = this._minimum;
36888 // check we have a minimum
36889 if (node === null)
36890 return node;
36891 // current minimum
36892 var minimum = this._minimum;
36893 // get number of children
36894 var numberOfChildren = node.degree;
36895 // pointer to the first child
36896 var x = node.child;
36897 // for each child of node do...
36898 while (numberOfChildren > 0) {
36899 // store node in right side
36900 var tempRight = x.right;
36901 // remove x from child list
36902 x.left.right = x.right;
36903 x.right.left = x.left;
36904 // add x to root list of heap
36905 x.left = minimum;
36906 x.right = minimum.right;
36907 minimum.right = x;
36908 x.right.left = x;
36909 // set Parent[x] to null
36910 x.parent = null;
36911 x = tempRight;
36912 numberOfChildren--;
36913 }
36914 // remove node from root list of heap
36915 node.left.right = node.right;
36916 node.right.left = node.left;
36917 // update minimum
36918 if (node == node.right) {
36919 // empty
36920 minimum = null;
36921 }
36922 else {
36923 // update minimum
36924 minimum = node.right;
36925 // we need to update the pointer to the root with minimum key
36926 minimum = _findMinimumNode(minimum, this._size);
36927 }
36928 // decrement size of heap
36929 this._size--;
36930 // update minimum
36931 this._minimum = minimum;
36932 // return node
36933 return node;
36934 };
36935
36936 /**
36937 * Removes a node from the heap given the reference to the node. The trees
36938 * in the heap will be consolidated, if necessary. This operation may fail
36939 * to remove the correct element if there are nodes with key value -Infinity.
36940 * Running time: O(log n) amortized.
36941 * @memberof FibonacciHeap
36942 */
36943 FibonacciHeap.prototype.remove = function (node) {
36944 // decrease key value
36945 this._minimum = _decreaseKey(this._minimum, node, -1);
36946 // remove the smallest
36947 this.extractMinimum();
36948 };
36949
36950 /**
36951 * Decreases the key value for a heap node, given the new value to take on.
36952 * The structure of the heap may be changed and will not be consolidated.
36953 * Running time: O(1) amortized.
36954 * @memberof FibonacciHeap
36955 */
36956 var _decreaseKey = function (minimum, node, key) {
36957 // set node key
36958 node.key = key;
36959 // get parent node
36960 var parent = node.parent;
36961 if (parent && smaller(node.key, parent.key)) {
36962 // remove node from parent
36963 _cut(minimum, node, parent);
36964 // remove all nodes from parent to the root parent
36965 _cascadingCut(minimum, parent);
36966 }
36967 // update minimum node if needed
36968 if (smaller(node.key, minimum.key))
36969 minimum = node;
36970 // return minimum
36971 return minimum;
36972 };
36973
36974 /**
36975 * The reverse of the link operation: removes node from the child list of parent.
36976 * This method assumes that min is non-null. Running time: O(1).
36977 * @memberof FibonacciHeap
36978 */
36979 var _cut = function (minimum, node, parent) {
36980 // remove node from parent children and decrement Degree[parent]
36981 node.left.right = node.right;
36982 node.right.left = node.left;
36983 parent.degree--;
36984 // reset y.child if necessary
36985 if (parent.child == node)
36986 parent.child = node.right;
36987 // remove child if degree is 0
36988 if (parent.degree === 0)
36989 parent.child = null;
36990 // add node to root list of heap
36991 node.left = minimum;
36992 node.right = minimum.right;
36993 minimum.right = node;
36994 node.right.left = node;
36995 // set parent[node] to null
36996 node.parent = null;
36997 // set mark[node] to false
36998 node.mark = false;
36999 };
37000
37001 /**
37002 * Performs a cascading cut operation. This cuts node from its parent and then
37003 * does the same for its parent, and so on up the tree.
37004 * Running time: O(log n); O(1) excluding the recursion.
37005 * @memberof FibonacciHeap
37006 */
37007 var _cascadingCut= function (minimum, node) {
37008 // store parent node
37009 var parent = node.parent;
37010 // if there's a parent...
37011 if (!parent)
37012 return;
37013 // if node is unmarked, set it marked
37014 if (!node.mark) {
37015 node.mark = true;
37016 }
37017 else {
37018 // it's marked, cut it from parent
37019 _cut(minimum, node, parent);
37020 // cut its parent as well
37021 _cascadingCut(parent);
37022 }
37023 };
37024
37025 /**
37026 * Make the first node a child of the second one. Running time: O(1) actual.
37027 * @memberof FibonacciHeap
37028 */
37029 var _linkNodes = function (node, parent) {
37030 // remove node from root list of heap
37031 node.left.right = node.right;
37032 node.right.left = node.left;
37033 // make node a Child of parent
37034 node.parent = parent;
37035 if (!parent.child) {
37036 parent.child = node;
37037 node.right = node;
37038 node.left = node;
37039 }
37040 else {
37041 node.left = parent.child;
37042 node.right = parent.child.right;
37043 parent.child.right = node;
37044 node.right.left = node;
37045 }
37046 // increase degree[parent]
37047 parent.degree++;
37048 // set mark[node] false
37049 node.mark = false;
37050 };
37051
37052 var _findMinimumNode = function (minimum, size) {
37053 // 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
37054 var arraySize = Math.floor(Math.log(size) * oneOverLogPhi) + 1;
37055 // create list with initial capacity
37056 var array = new Array(arraySize);
37057 // find the number of root nodes.
37058 var numRoots = 0;
37059 var x = minimum;
37060 if (x) {
37061 numRoots++;
37062 x = x.right;
37063 while (x !== minimum) {
37064 numRoots++;
37065 x = x.right;
37066 }
37067 }
37068 // vars
37069 var y;
37070 // For each node in root list do...
37071 while (numRoots > 0) {
37072 // access this node's degree..
37073 var d = x.degree;
37074 // get next node
37075 var next = x.right;
37076 // check if there is a node already in array with the same degree
37077 while (true) {
37078 // get node with the same degree is any
37079 y = array[d];
37080 if (!y)
37081 break;
37082 // make one node with the same degree a child of the other, do this based on the key value.
37083 if (larger(x.key, y.key)) {
37084 var temp = y;
37085 y = x;
37086 x = temp;
37087 }
37088 // make y a child of x
37089 _linkNodes(y, x);
37090 // we have handled this degree, go to next one.
37091 array[d] = null;
37092 d++;
37093 }
37094 // save this node for later when we might encounter another of the same degree.
37095 array[d] = x;
37096 // move forward through list.
37097 x = next;
37098 numRoots--;
37099 }
37100 // Set min to null (effectively losing the root list) and reconstruct the root list from the array entries in array[].
37101 minimum = null;
37102 // loop nodes in array
37103 for (var i = 0; i < arraySize; i++) {
37104 // get current node
37105 y = array[i];
37106 if (!y)
37107 continue;
37108 // check if we have a linked list
37109 if (minimum) {
37110 // First remove node from root list.
37111 y.left.right = y.right;
37112 y.right.left = y.left;
37113 // now add to root list, again.
37114 y.left = minimum;
37115 y.right = minimum.right;
37116 minimum.right = y;
37117 y.right.left = y;
37118 // check if this is a new min.
37119 if (smaller(y.key, minimum.key))
37120 minimum = y;
37121 }
37122 else
37123 minimum = y;
37124 }
37125 return minimum;
37126 };
37127
37128 return FibonacciHeap;
37129}
37130
37131exports.name = 'FibonacciHeap';
37132exports.path = 'type';
37133exports.factory = factory;
37134
37135
37136/***/ }),
37137/* 182 */
37138/***/ (function(module, exports, __webpack_require__) {
37139
37140"use strict";
37141
37142
37143var util = __webpack_require__(25);
37144
37145var string = util.string;
37146var object = util.object;
37147
37148var isArray = Array.isArray;
37149var isString = string.isString;
37150
37151function factory (type, config, load) {
37152
37153 var DenseMatrix = load(__webpack_require__(45));
37154
37155 var smaller = load(__webpack_require__(39));
37156
37157 function ImmutableDenseMatrix(data, datatype) {
37158 if (!(this instanceof ImmutableDenseMatrix))
37159 throw new SyntaxError('Constructor must be called with the new operator');
37160 if (datatype && !isString(datatype))
37161 throw new Error('Invalid datatype: ' + datatype);
37162
37163 if (type.isMatrix(data) || isArray(data)) {
37164 // use DenseMatrix implementation
37165 var matrix = new DenseMatrix(data, datatype);
37166 // internal structures
37167 this._data = matrix._data;
37168 this._size = matrix._size;
37169 this._datatype = matrix._datatype;
37170 this._min = null;
37171 this._max = null;
37172 }
37173 else if (data && isArray(data.data) && isArray(data.size)) {
37174 // initialize fields from JSON representation
37175 this._data = data.data;
37176 this._size = data.size;
37177 this._datatype = data.datatype;
37178 this._min = typeof data.min !== 'undefined' ? data.min : null;
37179 this._max = typeof data.max !== 'undefined' ? data.max : null;
37180 }
37181 else if (data) {
37182 // unsupported type
37183 throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')');
37184 }
37185 else {
37186 // nothing provided
37187 this._data = [];
37188 this._size = [0];
37189 this._datatype = datatype;
37190 this._min = null;
37191 this._max = null;
37192 }
37193 }
37194
37195 ImmutableDenseMatrix.prototype = new DenseMatrix();
37196
37197 /**
37198 * Attach type information
37199 */
37200 ImmutableDenseMatrix.prototype.type = 'ImmutableDenseMatrix';
37201 ImmutableDenseMatrix.prototype.isImmutableDenseMatrix = true;
37202
37203 /**
37204 * Get a subset of the matrix, or replace a subset of the matrix.
37205 *
37206 * Usage:
37207 * var subset = matrix.subset(index) // retrieve subset
37208 * var value = matrix.subset(index, replacement) // replace subset
37209 *
37210 * @param {Index} index
37211 * @param {Array | ImmutableDenseMatrix | *} [replacement]
37212 * @param {*} [defaultValue=0] Default value, filled in on new entries when
37213 * the matrix is resized. If not provided,
37214 * new matrix elements will be filled with zeros.
37215 */
37216 ImmutableDenseMatrix.prototype.subset = function (index) {
37217 switch (arguments.length) {
37218 case 1:
37219 // use base implementation
37220 var m = DenseMatrix.prototype.subset.call(this, index);
37221 // check result is a matrix
37222 if (type.isMatrix(m)) {
37223 // return immutable matrix
37224 return new ImmutableDenseMatrix({
37225 data: m._data,
37226 size: m._size,
37227 datatype: m._datatype
37228 });
37229 }
37230 return m;
37231
37232 // intentional fall through
37233 case 2:
37234 case 3:
37235 throw new Error('Cannot invoke set subset on an Immutable Matrix instance');
37236
37237 default:
37238 throw new SyntaxError('Wrong number of arguments');
37239 }
37240 };
37241
37242 /**
37243 * Replace a single element in the matrix.
37244 * @param {Number[]} index Zero-based index
37245 * @param {*} value
37246 * @param {*} [defaultValue] Default value, filled in on new entries when
37247 * the matrix is resized. If not provided,
37248 * new matrix elements will be left undefined.
37249 * @return {ImmutableDenseMatrix} self
37250 */
37251 ImmutableDenseMatrix.prototype.set = function () {
37252 throw new Error('Cannot invoke set on an Immutable Matrix instance');
37253 };
37254
37255 /**
37256 * Resize the matrix to the given size. Returns a copy of the matrix when
37257 * `copy=true`, otherwise return the matrix itself (resize in place).
37258 *
37259 * @param {Number[]} size The new size the matrix should have.
37260 * @param {*} [defaultValue=0] Default value, filled in on new entries.
37261 * If not provided, the matrix elements will
37262 * be filled with zeros.
37263 * @param {boolean} [copy] Return a resized copy of the matrix
37264 *
37265 * @return {Matrix} The resized matrix
37266 */
37267 ImmutableDenseMatrix.prototype.resize = function () {
37268 throw new Error('Cannot invoke resize on an Immutable Matrix instance');
37269 };
37270
37271 /**
37272 * Disallows reshaping in favor of immutability.
37273 *
37274 * @throws {Error} Operation not allowed
37275 */
37276 ImmutableDenseMatrix.prototype.reshape = function () {
37277 throw new Error('Cannot invoke reshape on an Immutable Matrix instance');
37278 };
37279
37280 /**
37281 * Create a clone of the matrix
37282 * @return {ImmutableDenseMatrix} clone
37283 */
37284 ImmutableDenseMatrix.prototype.clone = function () {
37285 var m = new ImmutableDenseMatrix({
37286 data: object.clone(this._data),
37287 size: object.clone(this._size),
37288 datatype: this._datatype
37289 });
37290 return m;
37291 };
37292
37293 /**
37294 * Get a JSON representation of the matrix
37295 * @returns {Object}
37296 */
37297 ImmutableDenseMatrix.prototype.toJSON = function () {
37298 return {
37299 mathjs: 'ImmutableDenseMatrix',
37300 data: this._data,
37301 size: this._size,
37302 datatype: this._datatype
37303 };
37304 };
37305
37306 /**
37307 * Generate a matrix from a JSON object
37308 * @param {Object} json An object structured like
37309 * `{"mathjs": "ImmutableDenseMatrix", data: [], size: []}`,
37310 * where mathjs is optional
37311 * @returns {ImmutableDenseMatrix}
37312 */
37313 ImmutableDenseMatrix.fromJSON = function (json) {
37314 return new ImmutableDenseMatrix(json);
37315 };
37316
37317 /**
37318 * Swap rows i and j in Matrix.
37319 *
37320 * @param {Number} i Matrix row index 1
37321 * @param {Number} j Matrix row index 2
37322 *
37323 * @return {Matrix} The matrix reference
37324 */
37325 ImmutableDenseMatrix.prototype.swapRows = function () {
37326 throw new Error('Cannot invoke swapRows on an Immutable Matrix instance');
37327 };
37328
37329 /**
37330 * Calculate the minimum value in the set
37331 * @return {Number | undefined} min
37332 */
37333 ImmutableDenseMatrix.prototype.min = function () {
37334 // check min has been calculated before
37335 if (this._min === null) {
37336 // minimum
37337 var m = null;
37338 // compute min
37339 this.forEach(function (v) {
37340 if (m === null || smaller(v, m))
37341 m = v;
37342 });
37343 this._min = m !== null ? m : undefined;
37344 }
37345 return this._min;
37346 };
37347
37348 /**
37349 * Calculate the maximum value in the set
37350 * @return {Number | undefined} max
37351 */
37352 ImmutableDenseMatrix.prototype.max = function () {
37353 // check max has been calculated before
37354 if (this._max === null) {
37355 // maximum
37356 var m = null;
37357 // compute max
37358 this.forEach(function (v) {
37359 if (m === null || smaller(m, v))
37360 m = v;
37361 });
37362 this._max = m !== null ? m : undefined;
37363 }
37364 return this._max;
37365 };
37366
37367 // exports
37368 return ImmutableDenseMatrix;
37369}
37370
37371exports.name = 'ImmutableDenseMatrix';
37372exports.path = 'type';
37373exports.factory = factory;
37374
37375
37376/***/ }),
37377/* 183 */
37378/***/ (function(module, exports, __webpack_require__) {
37379
37380"use strict";
37381
37382
37383function factory (type, config, load, typed) {
37384 /**
37385 * Create an index. An Index can store ranges having start, step, and end
37386 * for multiple dimensions.
37387 * Matrix.get, Matrix.set, and math.subset accept an Index as input.
37388 *
37389 * Syntax:
37390 *
37391 * math.index(range1, range2, ...)
37392 *
37393 * Where each range can be any of:
37394 *
37395 * - A number
37396 * - A string for getting/setting an object property
37397 * - An instance of `Range`
37398 * - A one-dimensional Array or a Matrix with numbers
37399 *
37400 * Indexes must be zero-based, integer numbers.
37401 *
37402 * Examples:
37403 *
37404 * var math = math.js
37405 *
37406 * var b = [1, 2, 3, 4, 5];
37407 * math.subset(b, math.index([1, 2, 3])); // returns [2, 3, 4]
37408 *
37409 * var a = math.matrix([[1, 2], [3, 4]]);
37410 * a.subset(math.index(0, 1)); // returns 2
37411 *
37412 * See also:
37413 *
37414 * bignumber, boolean, complex, matrix, number, string, unit
37415 *
37416 * @param {...*} ranges Zero or more ranges or numbers.
37417 * @return {Index} Returns the created index
37418 */
37419 return typed('index', {
37420 '...number | string | BigNumber | Range | Array | Matrix': function (args) {
37421 var ranges = args.map(function (arg) {
37422 if (type.isBigNumber(arg)) {
37423 return arg.toNumber(); // convert BigNumber to Number
37424 }
37425 else if (Array.isArray(arg) || type.isMatrix(arg)) {
37426 return arg.map(function (elem) {
37427 // convert BigNumber to Number
37428 return type.isBigNumber(elem) ? elem.toNumber() : elem;
37429 });
37430 }
37431 else {
37432 return arg;
37433 }
37434 });
37435
37436 var res = new type.Index();
37437 type.Index.apply(res, ranges);
37438 return res;
37439 }
37440 });
37441}
37442
37443exports.name = 'index';
37444exports.factory = factory;
37445
37446
37447/***/ }),
37448/* 184 */
37449/***/ (function(module, exports, __webpack_require__) {
37450
37451"use strict";
37452
37453
37454function factory (type, config, load, typed) {
37455
37456 var SparseMatrix = type.SparseMatrix;
37457
37458 /**
37459 * Create a Sparse Matrix. The function creates a new `math.type.Matrix` object from
37460 * an `Array`. A Matrix has utility functions to manipulate the data in the
37461 * matrix, like getting the size and getting or setting values in the matrix.
37462 *
37463 * Syntax:
37464 *
37465 * math.sparse() // creates an empty sparse matrix.
37466 * math.sparse(data) // creates a sparse matrix with initial data.
37467 * math.sparse(data, 'number') // creates a sparse matrix with initial data, number datatype.
37468 *
37469 * Examples:
37470 *
37471 * var m = math.sparse([[1, 2], [3, 4]]);
37472 * m.size(); // Array [2, 2]
37473 * m.resize([3, 2], 5);
37474 * m.valueOf(); // Array [[1, 2], [3, 4], [5, 5]]
37475 * m.get([1, 0]) // number 3
37476 *
37477 * See also:
37478 *
37479 * bignumber, boolean, complex, index, number, string, unit, matrix
37480 *
37481 * @param {Array | Matrix} [data] A two dimensional array
37482 *
37483 * @return {Matrix} The created matrix
37484 */
37485 var sparse = typed('sparse', {
37486 '': function () {
37487 return new SparseMatrix([]);
37488 },
37489
37490 'string': function (datatype) {
37491 return new SparseMatrix([], datatype);
37492 },
37493
37494 'Array | Matrix': function (data) {
37495 return new SparseMatrix(data);
37496 },
37497
37498 'Array | Matrix, string': function (data, datatype) {
37499 return new SparseMatrix(data, datatype);
37500 }
37501 });
37502
37503 sparse.toTex = {
37504 0: '\\begin{bsparse}\\end{bsparse}',
37505 1: '\\left(${args[0]}\\right)'
37506 };
37507
37508 return sparse;
37509}
37510
37511exports.name = 'sparse';
37512exports.factory = factory;
37513
37514
37515/***/ }),
37516/* 185 */
37517/***/ (function(module, exports, __webpack_require__) {
37518
37519module.exports = [
37520 // type
37521 __webpack_require__(95)
37522];
37523
37524
37525/***/ }),
37526/* 186 */
37527/***/ (function(module, exports, __webpack_require__) {
37528
37529"use strict";
37530
37531
37532var deepMap = __webpack_require__(1);
37533var number = __webpack_require__(3);
37534
37535function factory (type, config, load, typed) {
37536 /**
37537 * Create a string or convert any object into a string.
37538 * Elements of Arrays and Matrices are processed element wise.
37539 *
37540 * Syntax:
37541 *
37542 * math.string(value)
37543 *
37544 * Examples:
37545 *
37546 * math.string(4.2); // returns string '4.2'
37547 * math.string(math.complex(3, 2); // returns string '3 + 2i'
37548 *
37549 * var u = math.unit(5, 'km');
37550 * math.string(u.to('m')); // returns string '5000 m'
37551 *
37552 * math.string([true, false]); // returns ['true', 'false']
37553 *
37554 * See also:
37555 *
37556 * bignumber, boolean, complex, index, matrix, number, unit
37557 *
37558 * @param {* | Array | Matrix | null} [value] A value to convert to a string
37559 * @return {string | Array | Matrix} The created string
37560 */
37561 var string = typed('string', {
37562 '': function () {
37563 return '';
37564 },
37565
37566 'number': number.format,
37567
37568 'null': function (x) {
37569 return 'null';
37570 },
37571
37572 'boolean': function (x) {
37573 return x + '';
37574 },
37575
37576 'string': function (x) {
37577 return x;
37578 },
37579
37580 'Array | Matrix': function (x) {
37581 return deepMap(x, string);
37582 },
37583
37584 'any': function (x) {
37585 return String(x);
37586 }
37587 });
37588
37589 string.toTex = {
37590 0: '\\mathtt{""}',
37591 1: '\\mathrm{string}\\left(${args[0]}\\right)'
37592 };
37593
37594 return string;
37595}
37596
37597exports.name = 'string';
37598exports.factory = factory;
37599
37600
37601/***/ }),
37602/* 187 */
37603/***/ (function(module, exports, __webpack_require__) {
37604
37605module.exports = [
37606 // type
37607 __webpack_require__(188),
37608
37609 // construction function
37610 __webpack_require__(189),
37611
37612 // create new units
37613 __webpack_require__(190),
37614
37615 // split units
37616 __webpack_require__(191),
37617
37618 // physical constants
37619 __webpack_require__(192)
37620];
37621
37622
37623/***/ }),
37624/* 188 */
37625/***/ (function(module, exports, __webpack_require__) {
37626
37627"use strict";
37628
37629
37630var endsWith = __webpack_require__(9).endsWith;
37631var clone = __webpack_require__(5).clone;
37632var constants = __webpack_require__(96);
37633
37634function factory (type, config, load, typed, math) {
37635 var add = load(__webpack_require__(16));
37636 var subtract = load(__webpack_require__(21));
37637 var multiply = load(__webpack_require__(22));
37638 var divide = load(__webpack_require__(14));
37639 var pow = load(__webpack_require__(46));
37640 var abs = load(__webpack_require__(28));
37641 var fix = load(__webpack_require__(97));
37642 var round = load(__webpack_require__(98));
37643 var equal = load(__webpack_require__(30));
37644 var isNumeric = load(__webpack_require__(75));
37645 var format = load(__webpack_require__(99));
37646 var getTypeOf = load(__webpack_require__(76));
37647 var toNumber = load(__webpack_require__(74));
37648 var Complex = load(__webpack_require__(92));
37649
37650 /**
37651 * A unit can be constructed in the following ways:
37652 * var a = new Unit(value, name);
37653 * var b = new Unit(null, name);
37654 * var c = Unit.parse(str);
37655 *
37656 * Example usage:
37657 * var a = new Unit(5, 'cm'); // 50 mm
37658 * var b = Unit.parse('23 kg'); // 23 kg
37659 * var c = math.in(a, new Unit(null, 'm'); // 0.05 m
37660 * var d = new Unit(9.81, "m/s^2"); // 9.81 m/s^2
37661 *
37662 * @class Unit
37663 * @constructor Unit
37664 * @param {number | BigNumber | Fraction | Complex | boolean} [value] A value like 5.2
37665 * @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.
37666 */
37667 function Unit(value, name) {
37668 if (!(this instanceof Unit)) {
37669 throw new Error('Constructor must be called with the new operator');
37670 }
37671
37672 if (!(value == undefined || isNumeric(value) || type.isComplex(value))) {
37673 throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined');
37674 }
37675 if (name != undefined && (typeof name !== 'string' || name === '')) {
37676 throw new TypeError('Second parameter in Unit constructor must be a string');
37677 }
37678
37679 if (name != undefined) {
37680 var u = Unit.parse(name);
37681 this.units = u.units;
37682 this.dimensions = u.dimensions;
37683 }
37684 else {
37685 this.units = [
37686 {
37687 unit: UNIT_NONE,
37688 prefix: PREFIXES.NONE, // link to a list with supported prefixes
37689 power: 0
37690 }
37691 ];
37692 this.dimensions = [];
37693 for(var i=0; i<BASE_DIMENSIONS.length; i++) {
37694 this.dimensions[i] = 0;
37695 }
37696 }
37697
37698 this.value = (value != undefined) ? this._normalize(value) : null;
37699
37700 this.fixPrefix = false; // if true, function format will not search for the
37701 // best prefix but leave it as initially provided.
37702 // fixPrefix is set true by the method Unit.to
37703
37704 // The justification behind this is that if the constructor is explicitly called,
37705 // the caller wishes the units to be returned exactly as he supplied.
37706 this.isUnitListSimplified = true;
37707
37708 }
37709
37710 /**
37711 * Attach type information
37712 */
37713 Unit.prototype.type = 'Unit';
37714 Unit.prototype.isUnit = true;
37715
37716 // private variables and functions for the Unit parser
37717 var text, index, c;
37718
37719 function skipWhitespace() {
37720 while (c == ' ' || c == '\t') {
37721 next();
37722 }
37723 }
37724
37725 function isDigitDot(c) {
37726 return ((c >= '0' && c <= '9') || c == '.');
37727 }
37728
37729 function isDigit(c) {
37730 return ((c >= '0' && c <= '9'));
37731 }
37732
37733 function next() {
37734 index++;
37735 c = text.charAt(index);
37736 }
37737
37738 function revert(oldIndex) {
37739 index = oldIndex;
37740 c = text.charAt(index);
37741 }
37742
37743 function parseNumber() {
37744 var number = '';
37745 var oldIndex;
37746 oldIndex = index;
37747
37748 if (c == '+') {
37749 next();
37750 }
37751 else if (c == '-') {
37752 number += c;
37753 next();
37754 }
37755
37756 if (!isDigitDot(c)) {
37757 // a + or - must be followed by a digit
37758 revert(oldIndex);
37759 return null;
37760 }
37761
37762 // get number, can have a single dot
37763 if (c == '.') {
37764 number += c;
37765 next();
37766 if (!isDigit(c)) {
37767 // this is no legal number, it is just a dot
37768 revert(oldIndex);
37769 return null;
37770 }
37771 }
37772 else {
37773 while (isDigit(c)) {
37774 number += c;
37775 next();
37776 }
37777 if (c == '.') {
37778 number += c;
37779 next();
37780 }
37781 }
37782 while (isDigit(c)) {
37783 number += c;
37784 next();
37785 }
37786
37787 // check for exponential notation like "2.3e-4" or "1.23e50"
37788 if (c == 'E' || c == 'e') {
37789 // 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"
37790
37791 var tentativeNumber = '';
37792 var tentativeIndex = index;
37793
37794 tentativeNumber += c;
37795 next();
37796
37797 if (c == '+' || c == '-') {
37798 tentativeNumber += c;
37799 next();
37800 }
37801
37802 // Scientific notation MUST be followed by an exponent (otherwise we assume it is not scientific notation)
37803 if (!isDigit(c)) {
37804 // The e or E must belong to something else, so return the number without the e or E.
37805 revert(tentativeIndex);
37806 return number;
37807 }
37808
37809 // We can now safely say that this is scientific notation.
37810 number = number + tentativeNumber;
37811 while (isDigit(c)) {
37812 number += c;
37813 next();
37814 }
37815 }
37816
37817 return number;
37818 }
37819
37820 function parseUnit() {
37821 var unitName = '';
37822
37823 // Alphanumeric characters only; matches [a-zA-Z0-9]
37824 var code = text.charCodeAt(index);
37825 while ( (code >= 48 && code <= 57) ||
37826 (code >= 65 && code <= 90) ||
37827 (code >= 97 && code <= 122)) {
37828 unitName += c;
37829 next();
37830 code = text.charCodeAt(index);
37831 }
37832
37833 // Must begin with [a-zA-Z]
37834 code = unitName.charCodeAt(0);
37835 if ((code >= 65 && code <= 90) ||
37836 (code >= 97 && code <= 122)) {
37837 return unitName || null;
37838 }
37839 else {
37840 return null;
37841 }
37842 }
37843
37844 function parseCharacter(toFind) {
37845 if (c === toFind) {
37846 next();
37847 return toFind;
37848 }
37849 else {
37850 return null;
37851 }
37852 }
37853
37854 /**
37855 * Parse a string into a unit. The value of the unit is parsed as number,
37856 * BigNumber, or Fraction depending on the math.js config setting `number`.
37857 *
37858 * Throws an exception if the provided string does not contain a valid unit or
37859 * cannot be parsed.
37860 * @memberof Unit
37861 * @param {string} str A string like "5.2 inch", "4e2 cm/s^2"
37862 * @return {Unit} unit
37863 */
37864 Unit.parse = function (str, options) {
37865 options = options || {};
37866 text = str;
37867 index = -1;
37868 c = '';
37869
37870 if (typeof text !== 'string') {
37871 throw new TypeError('Invalid argument in Unit.parse, string expected');
37872 }
37873
37874 var unit = new Unit();
37875 unit.units = [];
37876
37877 // A unit should follow this pattern:
37878 // [number]unit[^number] [unit[^number]]...[/unit[^number] [unit[^number]]]
37879
37880 // Rules:
37881 // number is any floating point number.
37882 // 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!
37883 // The string may optionally begin with a number.
37884 // Each unit may optionally be followed by ^number.
37885 // Whitespace or a forward slash is recommended between consecutive units, although the following technically is parseable:
37886 // 2m^2kg/s^2
37887 // it is not good form. If a unit starts with e, then it could be confused as a floating point number:
37888 // 4erg
37889
37890 next();
37891 skipWhitespace();
37892 // Optional number at the start of the string
37893 var valueStr = parseNumber();
37894 var value = null;
37895 if(valueStr) {
37896 if (config.number === 'BigNumber') {
37897 value = new type.BigNumber(valueStr);
37898 }
37899 else if (config.number === 'Fraction') {
37900 value = new type.Fraction(valueStr);
37901 }
37902 else { // number
37903 value = parseFloat(valueStr);
37904 }
37905 }
37906 skipWhitespace(); // Whitespace is not required here
37907
37908 // Next, we read any number of unit[^number]
37909 var powerMultiplierCurrent = 1;
37910 var expectingUnit = false;
37911
37912 // Stack to keep track of powerMultipliers applied to each parentheses group
37913 var powerMultiplierStack = [];
37914
37915 // Running product of all elements in powerMultiplierStack
37916 var powerMultiplierStackProduct = 1;
37917
37918 while (true) {
37919 skipWhitespace();
37920
37921 // Check for and consume opening parentheses, pushing powerMultiplierCurrent to the stack
37922 // A '(' will always appear directly before a unit.
37923 while (c === '(') {
37924 powerMultiplierStack.push(powerMultiplierCurrent);
37925 powerMultiplierStackProduct *= powerMultiplierCurrent;
37926 powerMultiplierCurrent = 1;
37927 next();
37928 skipWhitespace();
37929 }
37930
37931 // Is there something here?
37932 if(c) {
37933 var oldC = c;
37934 var uStr = parseUnit();
37935 if(uStr == null) {
37936 throw new SyntaxError('Unexpected "' + oldC + '" in "' + text + '" at index ' + index.toString());
37937 }
37938 }
37939 else {
37940 // End of input.
37941 break;
37942 }
37943
37944 // Verify the unit exists and get the prefix (if any)
37945 var res = _findUnit(uStr);
37946 if(res == null) {
37947 // Unit not found.
37948 throw new SyntaxError('Unit "' + uStr + '" not found.');
37949 }
37950
37951 var power = powerMultiplierCurrent * powerMultiplierStackProduct;
37952 // Is there a "^ number"?
37953 skipWhitespace();
37954 if (parseCharacter('^')) {
37955 skipWhitespace();
37956 var p = parseNumber();
37957 if(p == null) {
37958 // No valid number found for the power!
37959 throw new SyntaxError('In "' + str + '", "^" must be followed by a floating-point number');
37960 }
37961 power *= p;
37962 }
37963
37964 // Add the unit to the list
37965 unit.units.push( {
37966 unit: res.unit,
37967 prefix: res.prefix,
37968 power: power
37969 });
37970 for(var i=0; i<BASE_DIMENSIONS.length; i++) {
37971 unit.dimensions[i] += (res.unit.dimensions[i] || 0) * power;
37972 }
37973
37974 // Check for and consume closing parentheses, popping from the stack.
37975 // A ')' will always follow a unit.
37976 skipWhitespace();
37977 while (c === ')') {
37978 if(powerMultiplierStack.length === 0) {
37979 throw new SyntaxError('Unmatched ")" in "' + text + '" at index ' + index.toString());
37980 }
37981 powerMultiplierStackProduct /= powerMultiplierStack.pop();
37982 next();
37983 skipWhitespace();
37984 }
37985
37986 // "*" and "/" should mean we are expecting something to come next.
37987 // Is there a forward slash? If so, negate powerMultiplierCurrent. The next unit or paren group is in the denominator.
37988 expectingUnit = false;
37989
37990 if (parseCharacter('*')) {
37991 // explicit multiplication
37992 powerMultiplierCurrent = 1;
37993 expectingUnit = true;
37994 }
37995 else if (parseCharacter('/')) {
37996 // division
37997 powerMultiplierCurrent = -1;
37998 expectingUnit = true;
37999 }
38000 else {
38001 // implicit multiplication
38002 powerMultiplierCurrent = 1;
38003 }
38004
38005 // Replace the unit into the auto unit system
38006 if(res.unit.base) {
38007 var baseDim = res.unit.base.key;
38008 UNIT_SYSTEMS.auto[baseDim] = {
38009 unit: res.unit,
38010 prefix: res.prefix
38011 };
38012 }
38013 }
38014
38015 // Has the string been entirely consumed?
38016 skipWhitespace();
38017 if(c) {
38018 throw new SyntaxError('Could not parse: "' + str + '"');
38019 }
38020
38021 // Is there a trailing slash?
38022 if(expectingUnit) {
38023 throw new SyntaxError('Trailing characters: "' + str + '"');
38024 }
38025
38026 // Is the parentheses stack empty?
38027 if(powerMultiplierStack.length !== 0) {
38028 throw new SyntaxError('Unmatched "(" in "' + text + '"');
38029 }
38030
38031 // Are there any units at all?
38032 if(unit.units.length == 0 && !options.allowNoUnits) {
38033 throw new SyntaxError('"' + str + '" contains no units');
38034 }
38035
38036 unit.value = (value != undefined) ? unit._normalize(value) : null;
38037 return unit;
38038 };
38039
38040 /**
38041 * create a copy of this unit
38042 * @memberof Unit
38043 * @return {Unit} Returns a cloned version of the unit
38044 */
38045 Unit.prototype.clone = function () {
38046 var unit = new Unit();
38047
38048 unit.fixPrefix = this.fixPrefix;
38049 unit.isUnitListSimplified = this.isUnitListSimplified;
38050
38051 unit.value = clone(this.value);
38052 unit.dimensions = this.dimensions.slice(0);
38053 unit.units = [];
38054 for(var i = 0; i < this.units.length; i++) {
38055 unit.units[i] = { };
38056 for (var p in this.units[i]) {
38057 if (this.units[i].hasOwnProperty(p)) {
38058 unit.units[i][p] = this.units[i][p];
38059 }
38060 }
38061 }
38062
38063 return unit;
38064 };
38065
38066 /**
38067 * Return whether the unit is derived (such as m/s, or cm^2, but not N)
38068 * @memberof Unit
38069 * @return {boolean} True if the unit is derived
38070 */
38071 Unit.prototype._isDerived = function() {
38072 if(this.units.length === 0) {
38073 return false;
38074 }
38075 return this.units.length > 1 || Math.abs(this.units[0].power - 1.0) > 1e-15;
38076 };
38077
38078 /**
38079 * Normalize a value, based on its currently set unit(s)
38080 * @memberof Unit
38081 * @param {number | BigNumber | Fraction | boolean} value
38082 * @return {number | BigNumber | Fraction | boolean} normalized value
38083 * @private
38084 */
38085 Unit.prototype._normalize = function (value) {
38086 var unitValue, unitOffset, unitPower, unitPrefixValue;
38087 var convert;
38088
38089 if (value == null || this.units.length === 0) {
38090 return value;
38091 }
38092 else if (this._isDerived()) {
38093 // This is a derived unit, so do not apply offsets.
38094 // For example, with J kg^-1 degC^-1 you would NOT want to apply the offset.
38095 var res = value;
38096 convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed
38097
38098 for(var i=0; i < this.units.length; i++) {
38099 unitValue = convert(this.units[i].unit.value);
38100 unitPrefixValue = convert(this.units[i].prefix.value);
38101 unitPower = convert(this.units[i].power);
38102 res = multiply(res, pow(multiply(unitValue, unitPrefixValue), unitPower));
38103 }
38104
38105 return res;
38106 }
38107 else {
38108 // This is a single unit of power 1, like kg or degC
38109 convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed
38110
38111 unitValue = convert(this.units[0].unit.value);
38112 unitOffset = convert(this.units[0].unit.offset);
38113 unitPrefixValue = convert(this.units[0].prefix.value);
38114
38115 return multiply(add(value, unitOffset), multiply(unitValue, unitPrefixValue));
38116 }
38117 };
38118
38119 /**
38120 * Denormalize a value, based on its currently set unit(s)
38121 * @memberof Unit
38122 * @param {number} value
38123 * @param {number} [prefixValue] Optional prefix value to be used (ignored if this is a derived unit)
38124 * @return {number} denormalized value
38125 * @private
38126 */
38127 Unit.prototype._denormalize = function (value, prefixValue) {
38128 var unitValue, unitOffset, unitPower, unitPrefixValue;
38129 var convert;
38130
38131 if (value == null || this.units.length === 0) {
38132 return value;
38133 }
38134 else if (this._isDerived()) {
38135 // This is a derived unit, so do not apply offsets.
38136 // For example, with J kg^-1 degC^-1 you would NOT want to apply the offset.
38137 // 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.
38138 var res = value;
38139 convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed
38140
38141 for (var i = 0; i < this.units.length; i++) {
38142 unitValue = convert(this.units[i].unit.value);
38143 unitPrefixValue = convert(this.units[i].prefix.value);
38144 unitPower = convert(this.units[i].power);
38145 res = divide(res, pow(multiply(unitValue, unitPrefixValue), unitPower));
38146 }
38147
38148 return res;
38149 }
38150 else {
38151 // This is a single unit of power 1, like kg or degC
38152 convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed
38153
38154 unitValue = convert(this.units[0].unit.value);
38155 unitPrefixValue = convert(this.units[0].prefix.value);
38156 unitOffset = convert(this.units[0].unit.offset);
38157
38158 if (prefixValue == undefined) {
38159 return subtract(divide(divide(value, unitValue), unitPrefixValue), unitOffset);
38160 }
38161 else {
38162 return subtract(divide(divide(value, unitValue), prefixValue), unitOffset);
38163 }
38164 }
38165 };
38166
38167 /**
38168 * Find a unit from a string
38169 * @memberof Unit
38170 * @param {string} str A string like 'cm' or 'inch'
38171 * @returns {Object | null} result When found, an object with fields unit and
38172 * prefix is returned. Else, null is returned.
38173 * @private
38174 */
38175 function _findUnit(str) {
38176
38177 // 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.
38178 if(UNITS.hasOwnProperty(str)) {
38179 var unit = UNITS[str];
38180 var prefix = unit.prefixes[''];
38181 return {
38182 unit: unit,
38183 prefix: prefix
38184 }
38185 }
38186
38187 for (var name in UNITS) {
38188 if (UNITS.hasOwnProperty(name)) {
38189 if (endsWith(str, name)) {
38190 var unit = UNITS[name];
38191 var prefixLen = (str.length - name.length);
38192 var prefixName = str.substring(0, prefixLen);
38193 var prefix = unit.prefixes.hasOwnProperty(prefixName)
38194 ? unit.prefixes[prefixName]
38195 : undefined;
38196 if (prefix !== undefined) {
38197 // store unit, prefix, and value
38198 return {
38199 unit: unit,
38200 prefix: prefix
38201 };
38202 }
38203 }
38204 }
38205 }
38206
38207 return null;
38208 }
38209
38210 /**
38211 * Test if the given expression is a unit.
38212 * The unit can have a prefix but cannot have a value.
38213 * @memberof Unit
38214 * @param {string} name A string to be tested whether it is a value less unit.
38215 * The unit can have prefix, like "cm"
38216 * @return {boolean} true if the given string is a unit
38217 */
38218 Unit.isValuelessUnit = function (name) {
38219 return (_findUnit(name) != null);
38220 };
38221
38222 /**
38223 * check if this unit has given base unit
38224 * If this unit is a derived unit, this will ALWAYS return false, since by definition base units are not derived.
38225 * @memberof Unit
38226 * @param {BASE_UNITS | string | undefined} base
38227 */
38228 Unit.prototype.hasBase = function (base) {
38229
38230 if(typeof(base) === "string") {
38231 base = BASE_UNITS[base];
38232 }
38233
38234 if(!base)
38235 return false;
38236
38237
38238 // All dimensions must be the same
38239 for(var i=0; i<BASE_DIMENSIONS.length; i++) {
38240 if (Math.abs((this.dimensions[i] || 0) - (base.dimensions[i] || 0)) > 1e-12) {
38241 return false;
38242 }
38243 }
38244 return true;
38245
38246 };
38247
38248 /**
38249 * Check if this unit has a base or bases equal to another base or bases
38250 * For derived units, the exponent on each base also must match
38251 * @memberof Unit
38252 * @param {Unit} other
38253 * @return {boolean} true if equal base
38254 */
38255 Unit.prototype.equalBase = function (other) {
38256 // All dimensions must be the same
38257 for(var i=0; i<BASE_DIMENSIONS.length; i++) {
38258 if (Math.abs((this.dimensions[i] || 0) - (other.dimensions[i] || 0)) > 1e-12) {
38259 return false;
38260 }
38261 }
38262 return true;
38263 };
38264
38265 /**
38266 * Check if this unit equals another unit
38267 * @memberof Unit
38268 * @param {Unit} other
38269 * @return {boolean} true if both units are equal
38270 */
38271 Unit.prototype.equals = function (other) {
38272 return (this.equalBase(other) && equal(this.value, other.value));
38273 };
38274
38275 /**
38276 * Multiply this unit with another one
38277 * @memberof Unit
38278 * @param {Unit} other
38279 * @return {Unit} product of this unit and the other unit
38280 */
38281 Unit.prototype.multiply = function (other) {
38282 var res = this.clone();
38283
38284 for(var i = 0; i<BASE_DIMENSIONS.length; i++) {
38285 // Dimensions arrays may be of different lengths. Default to 0.
38286 res.dimensions[i] = (this.dimensions[i] || 0) + (other.dimensions[i] || 0);
38287 }
38288
38289 // Append other's units list onto res (simplify later in Unit.prototype.format)
38290 for(var i=0; i<other.units.length; i++) {
38291 // Make a deep copy
38292 var inverted = {};
38293 for(var key in other.units[i]) {
38294 inverted[key] = other.units[i][key];
38295 }
38296 res.units.push(inverted);
38297 }
38298
38299 // If at least one operand has a value, then the result should also have a value
38300 if(this.value != null || other.value != null) {
38301 var valThis = this.value == null ? this._normalize(1) : this.value;
38302 var valOther = other.value == null ? other._normalize(1) : other.value;
38303 res.value = multiply(valThis, valOther);
38304 }
38305 else {
38306 res.value = null;
38307 }
38308
38309 // Trigger simplification of the unit list at some future time
38310 res.isUnitListSimplified = false;
38311
38312 return getNumericIfUnitless(res);
38313 };
38314
38315 /**
38316 * Divide this unit by another one
38317 * @memberof Unit
38318 * @param {Unit} other
38319 * @return {Unit} result of dividing this unit by the other unit
38320 */
38321 Unit.prototype.divide = function (other) {
38322 var res = this.clone();
38323
38324 for(var i=0; i<BASE_DIMENSIONS.length; i++) {
38325 // Dimensions arrays may be of different lengths. Default to 0.
38326 res.dimensions[i] = (this.dimensions[i] || 0) - (other.dimensions[i] || 0);
38327 }
38328
38329 // Invert and append other's units list onto res (simplify later in Unit.prototype.format)
38330 for(var i=0; i<other.units.length; i++) {
38331 // Make a deep copy
38332 var inverted = {};
38333 for(var key in other.units[i]) {
38334 inverted[key] = other.units[i][key];
38335 }
38336 inverted.power = -inverted.power;
38337 res.units.push(inverted);
38338 }
38339
38340 // If at least one operand has a value, the result should have a value
38341 if (this.value != null || other.value != null) {
38342 var valThis = this.value == null ? this._normalize(1) : this.value;
38343 var valOther = other.value == null ? other._normalize(1) : other.value;
38344 res.value = divide(valThis, valOther);
38345 }
38346 else {
38347 res.value = null;
38348 }
38349
38350 // Trigger simplification of the unit list at some future time
38351 res.isUnitListSimplified = false;
38352
38353 return getNumericIfUnitless(res);
38354 };
38355
38356 /**
38357 * Calculate the power of a unit
38358 * @memberof Unit
38359 * @param {number | Fraction | BigNumber} p
38360 * @returns {Unit} The result: this^p
38361 */
38362 Unit.prototype.pow = function (p) {
38363 var res = this.clone();
38364
38365 for(var i=0; i<BASE_DIMENSIONS.length; i++) {
38366 // Dimensions arrays may be of different lengths. Default to 0.
38367 res.dimensions[i] = (this.dimensions[i] || 0) * p;
38368 }
38369
38370 // Adjust the power of each unit in the list
38371 for(var i=0; i<res.units.length; i++) {
38372 res.units[i].power *= p;
38373 }
38374
38375 if(res.value != null) {
38376 res.value = pow(res.value, p);
38377
38378 // only allow numeric output, we don't want to return a Complex number
38379 //if (!isNumeric(res.value)) {
38380 // res.value = NaN;
38381 //}
38382 // Update: Complex supported now
38383 }
38384 else {
38385 res.value = null;
38386 }
38387
38388 // Trigger lazy evaluation of the unit list
38389 res.isUnitListSimplified = false;
38390
38391 return getNumericIfUnitless(res);
38392 };
38393
38394 /**
38395 * Return the numeric value of this unit if it is dimensionless, has a value, and config.predictable == false; or the original unit otherwise
38396 * @param {Unit} unit
38397 * @returns {number | Fraction | BigNumber | Unit} The numeric value of the unit if conditions are met, or the original unit otherwise
38398 */
38399 var getNumericIfUnitless = function(unit) {
38400 if(unit.equalBase(BASE_UNITS.NONE) && unit.value !== null && !config.predictable) {
38401 return unit.value;
38402 }
38403 else {
38404 return unit;
38405 }
38406 }
38407
38408
38409 /**
38410 * Calculate the absolute value of a unit
38411 * @memberof Unit
38412 * @param {number | Fraction | BigNumber} x
38413 * @returns {Unit} The result: |x|, absolute value of x
38414 */
38415 Unit.prototype.abs = function () {
38416 // This gives correct, but unexpected, results for units with an offset.
38417 // For example, abs(-283.15 degC) = -263.15 degC !!!
38418 var ret = this.clone();
38419 ret.value = abs(ret.value);
38420
38421 for(var i in ret.units) {
38422 if(ret.units[i].unit.name === 'VA' || ret.units[i].unit.name === 'VAR') {
38423 ret.units[i].unit = UNITS["W"];
38424 }
38425 }
38426
38427 return ret;
38428 };
38429
38430 /**
38431 * Convert the unit to a specific unit name.
38432 * @memberof Unit
38433 * @param {string | Unit} valuelessUnit A unit without value. Can have prefix, like "cm"
38434 * @returns {Unit} Returns a clone of the unit with a fixed prefix and unit.
38435 */
38436 Unit.prototype.to = function (valuelessUnit) {
38437 var other;
38438 var value = this.value == null ? this._normalize(1) : this.value;
38439 if (typeof valuelessUnit === 'string') {
38440 //other = new Unit(null, valuelessUnit);
38441 other = Unit.parse(valuelessUnit);
38442 if (!this.equalBase(other)) {
38443 throw new Error('Units do not match');
38444 }
38445 if (other.value !== null) {
38446 throw new Error('Cannot convert to a unit with a value');
38447 }
38448
38449 other.value = clone(value);
38450 other.fixPrefix = true;
38451 other.isUnitListSimplified = true;
38452 return other;
38453 }
38454 else if (type.isUnit(valuelessUnit)) {
38455 if (!this.equalBase(valuelessUnit)) {
38456 throw new Error('Units do not match');
38457 }
38458 if (valuelessUnit.value !== null) {
38459 throw new Error('Cannot convert to a unit with a value');
38460 }
38461 other = valuelessUnit.clone();
38462 other.value = clone(value);
38463 other.fixPrefix = true;
38464 other.isUnitListSimplified = true;
38465 return other;
38466 }
38467 else {
38468 throw new Error('String or Unit expected as parameter');
38469 }
38470 };
38471
38472 /**
38473 * Return the value of the unit when represented with given valueless unit
38474 * @memberof Unit
38475 * @param {string | Unit} valuelessUnit For example 'cm' or 'inch'
38476 * @return {number} Returns the unit value as number.
38477 */
38478 // TODO: deprecate Unit.toNumber? It's always better to use toNumeric
38479 Unit.prototype.toNumber = function (valuelessUnit) {
38480 return toNumber(this.toNumeric(valuelessUnit));
38481 };
38482
38483 /**
38484 * Return the value of the unit in the original numeric type
38485 * @memberof Unit
38486 * @param {string | Unit} valuelessUnit For example 'cm' or 'inch'
38487 * @return {number | BigNumber | Fraction} Returns the unit value
38488 */
38489 Unit.prototype.toNumeric = function (valuelessUnit) {
38490 var other = this;
38491 if(valuelessUnit) {
38492 // Allow getting the numeric value without converting to a different unit
38493 other = this.to(valuelessUnit);
38494 }
38495
38496 other.simplifyUnitListLazy();
38497
38498 if(other._isDerived()) {
38499 return other._denormalize(other.value);
38500 }
38501 else {
38502 return other._denormalize(other.value, other.units[0].prefix.value);
38503 }
38504 };
38505
38506 /**
38507 * Get a string representation of the unit.
38508 * @memberof Unit
38509 * @return {string}
38510 */
38511 Unit.prototype.toString = function () {
38512 return this.format();
38513 };
38514
38515 /**
38516 * Get a JSON representation of the unit
38517 * @memberof Unit
38518 * @returns {Object} Returns a JSON object structured as:
38519 * `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}`
38520 */
38521 Unit.prototype.toJSON = function () {
38522 return {
38523 mathjs: 'Unit',
38524 value: this._denormalize(this.value),
38525 unit: this.formatUnits(),
38526 fixPrefix: this.fixPrefix
38527 };
38528 };
38529
38530 /**
38531 * Instantiate a Unit from a JSON object
38532 * @memberof Unit
38533 * @param {Object} json A JSON object structured as:
38534 * `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}`
38535 * @return {Unit}
38536 */
38537 Unit.fromJSON = function (json) {
38538 var unit = new Unit(json.value, json.unit);
38539 unit.fixPrefix = json.fixPrefix || false;
38540 return unit;
38541 };
38542
38543 /**
38544 * Returns the string representation of the unit.
38545 * @memberof Unit
38546 * @return {string}
38547 */
38548 Unit.prototype.valueOf = Unit.prototype.toString;
38549
38550 /**
38551 * Attempt to simplify the list of units for this unit according to the dimensions array and the current unit system. After the call, this Unit will contain a list of the "best" units for formatting.
38552 * Intended to be evaluated lazily. You must set isUnitListSimplified = false before the call! After the call, isUnitListSimplified will be set to true.
38553 */
38554 Unit.prototype.simplifyUnitListLazy = function() {
38555
38556 if (this.isUnitListSimplified || this.value == null) {
38557 return;
38558 }
38559
38560 var proposedUnitList = [];
38561
38562 // Search for a matching base
38563 var matchingBase;
38564 for(var key in currentUnitSystem) {
38565 if(this.hasBase(BASE_UNITS[key])) {
38566 matchingBase = key;
38567 break;
38568 }
38569 }
38570
38571 if(matchingBase === 'NONE')
38572 {
38573 this.units = [];
38574 }
38575 else {
38576 var matchingUnit;
38577 if(matchingBase) {
38578 // Does the unit system have a matching unit?
38579 if(currentUnitSystem.hasOwnProperty(matchingBase)) {
38580 matchingUnit = currentUnitSystem[matchingBase];
38581 }
38582 }
38583 var value;
38584 var str;
38585 if(matchingUnit) {
38586 this.units = [{
38587 unit: matchingUnit.unit,
38588 prefix: matchingUnit.prefix,
38589 power: 1.0
38590 }];
38591 }
38592 else {
38593 // Multiple units or units with powers are formatted like this:
38594 // 5 (kg m^2) / (s^3 mol)
38595 // Build an representation from the base units of the current unit system
38596 var missingBaseDim = false;
38597 for(var i=0; i<BASE_DIMENSIONS.length; i++) {
38598 var baseDim = BASE_DIMENSIONS[i];
38599 if(Math.abs(this.dimensions[i] || 0) > 1e-12) {
38600 if(currentUnitSystem.hasOwnProperty(baseDim)) {
38601 proposedUnitList.push({
38602 unit: currentUnitSystem[baseDim].unit,
38603 prefix: currentUnitSystem[baseDim].prefix,
38604 power: this.dimensions[i] || 0
38605 });
38606 }
38607 else {
38608 missingBaseDim = true;
38609 }
38610 }
38611 }
38612
38613 // Is the proposed unit list "simpler" than the existing one?
38614 if(proposedUnitList.length < this.units.length && !missingBaseDim) {
38615 // Replace this unit list with the proposed list
38616 this.units = proposedUnitList;
38617 }
38618 }
38619 }
38620
38621 this.isUnitListSimplified = true;
38622 };
38623
38624 Unit.prototype.toSI = function() {
38625
38626 var ret = this.clone();
38627
38628 var proposedUnitList = [];
38629
38630 // Multiple units or units with powers are formatted like this:
38631 // 5 (kg m^2) / (s^3 mol)
38632 // Build an representation from the base units of the SI unit system
38633 var missingBaseDim = false;
38634 for(var i=0; i<BASE_DIMENSIONS.length; i++) {
38635 var baseDim = BASE_DIMENSIONS[i];
38636 if(Math.abs(ret.dimensions[i] || 0) > 1e-12) {
38637 if(UNIT_SYSTEMS["si"].hasOwnProperty(baseDim)) {
38638 proposedUnitList.push({
38639 unit: UNIT_SYSTEMS["si"][baseDim].unit,
38640 prefix: UNIT_SYSTEMS["si"][baseDim].prefix,
38641 power: ret.dimensions[i] || 0
38642 });
38643 }
38644 else {
38645 throw new Error("Cannot express custom unit " + baseDim + " in SI units");
38646 }
38647 }
38648 }
38649
38650 // Replace this unit list with the proposed list
38651 ret.units = proposedUnitList;
38652
38653 ret.isUnitListSimplified = true;
38654
38655 return ret;
38656 }
38657
38658 /**
38659 * Get a string representation of the units of this Unit, without the value.
38660 * @memberof Unit
38661 * @return {string}
38662 */
38663 Unit.prototype.formatUnits = function () {
38664
38665 // Lazy evaluation of the unit list
38666 this.simplifyUnitListLazy();
38667
38668 var strNum = "";
38669 var strDen = "";
38670 var nNum = 0;
38671 var nDen = 0;
38672
38673 for(var i=0; i<this.units.length; i++) {
38674 if(this.units[i].power > 0) {
38675 nNum++;
38676 strNum += " " + this.units[i].prefix.name + this.units[i].unit.name;
38677 if(Math.abs(this.units[i].power - 1.0) > 1e-15) {
38678 strNum += "^" + this.units[i].power;
38679 }
38680 }
38681 else if(this.units[i].power < 0) {
38682 nDen++;
38683 }
38684 }
38685
38686 if(nDen > 0) {
38687 for(var i=0; i<this.units.length; i++) {
38688 if(this.units[i].power < 0) {
38689 if(nNum > 0) {
38690 strDen += " " + this.units[i].prefix.name + this.units[i].unit.name;
38691 if(Math.abs(this.units[i].power + 1.0) > 1e-15) {
38692 strDen += "^" + (-this.units[i].power);
38693 }
38694 }
38695 else {
38696 strDen += " " + this.units[i].prefix.name + this.units[i].unit.name;
38697 strDen += "^" + (this.units[i].power);
38698 }
38699 }
38700 }
38701 }
38702 // Remove leading " "
38703 strNum = strNum.substr(1);
38704 strDen = strDen.substr(1);
38705
38706 // Add parans for better copy/paste back into the eval, for example, or for better pretty print formatting
38707 if(nNum > 1 && nDen > 0) {
38708 strNum = "(" + strNum + ")";
38709 }
38710 if(nDen > 1 && nNum > 0) {
38711 strDen = "(" + strDen + ")";
38712 }
38713
38714 var str = strNum;
38715 if(nNum > 0 && nDen > 0) {
38716 str += " / ";
38717 }
38718 str += strDen;
38719
38720 return str;
38721 };
38722
38723 /**
38724 * Get a string representation of the Unit, with optional formatting options.
38725 * @memberof Unit
38726 * @param {Object | number | Function} [options] Formatting options. See
38727 * lib/utils/number:format for a
38728 * description of the available
38729 * options.
38730 * @return {string}
38731 */
38732 Unit.prototype.format = function (options) {
38733
38734 // Simplfy the unit list, if necessary
38735 this.simplifyUnitListLazy();
38736
38737 // 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.
38738 var isImaginary = false;
38739 var isReal = true;
38740 if(typeof(this.value) !== 'undefined' && this.value !== null && type.isComplex(this.value)) {
38741 // TODO: Make this better, for example, use relative magnitude of re and im rather than absolute
38742 isImaginary = Math.abs(this.value.re) < 1e-14;
38743 isReal = Math.abs(this.value.im) < 1e-14;
38744 }
38745
38746 for(var i in this.units) {
38747 if(this.units[i].unit) {
38748 if(this.units[i].unit.name === 'VA' && isImaginary) {
38749 this.units[i].unit = UNITS["VAR"];
38750 }
38751 else if(this.units[i].unit.name === 'VAR' && !isImaginary) {
38752 this.units[i].unit = UNITS["VA"];
38753 }
38754 }
38755 }
38756
38757
38758 // Now apply the best prefix
38759 // Units must have only one unit and not have the fixPrefix flag set
38760 if (this.units.length === 1 && !this.fixPrefix) {
38761 // Units must have integer powers, otherwise the prefix will change the
38762 // outputted value by not-an-integer-power-of-ten
38763 if (Math.abs(this.units[0].power - Math.round(this.units[0].power)) < 1e-14) {
38764 // Apply the best prefix
38765 this.units[0].prefix = this._bestPrefix();
38766 }
38767 }
38768
38769
38770 var value = this._denormalize(this.value);
38771 var str = (this.value !== null) ? format(value, options || {}) : '';
38772 var unitStr = this.formatUnits();
38773 if(this.value && type.isComplex(this.value)) {
38774 str = "(" + str + ")"; // Surround complex values with ( ) to enable better parsing
38775 }
38776 if(unitStr.length > 0 && str.length > 0) {
38777 str += " ";
38778 }
38779 str += unitStr;
38780
38781 return str;
38782 };
38783
38784 /**
38785 * Calculate the best prefix using current value.
38786 * @memberof Unit
38787 * @returns {Object} prefix
38788 * @private
38789 */
38790 Unit.prototype._bestPrefix = function () {
38791 if (this.units.length !== 1) {
38792 throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!");
38793 }
38794 if (Math.abs(this.units[0].power - Math.round(this.units[0].power)) >= 1e-14) {
38795 throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!");
38796 }
38797
38798 // find the best prefix value (resulting in the value of which
38799 // the absolute value of the log10 is closest to zero,
38800 // though with a little offset of 1.2 for nicer values: you get a
38801 // sequence 1mm 100mm 500mm 0.6m 1m 10m 100m 500m 0.6km 1km ...
38802
38803 // Note: the units value can be any numeric type, but to find the best
38804 // prefix it's enough to work with limited precision of a regular number
38805 // Update: using mathjs abs since we also allow complex numbers
38806 var absValue = abs(this.value);
38807 var absUnitValue = abs(this.units[0].unit.value);
38808 var bestPrefix = this.units[0].prefix;
38809 if (absValue === 0) {
38810 return bestPrefix;
38811 }
38812 var power = this.units[0].power;
38813 var bestDiff = Math.log(absValue / Math.pow(bestPrefix.value * absUnitValue, power)) / Math.LN10 - 1.2;
38814 if(bestDiff > -2.200001 && bestDiff < 1.800001) return bestPrefix; // Allow the original prefix
38815 bestDiff = Math.abs(bestDiff);
38816 var prefixes = this.units[0].unit.prefixes;
38817 for (var p in prefixes) {
38818 if (prefixes.hasOwnProperty(p)) {
38819 var prefix = prefixes[p];
38820 if (prefix.scientific) {
38821
38822 var diff = Math.abs(
38823 Math.log(absValue / Math.pow(prefix.value * absUnitValue, power)) / Math.LN10 - 1.2);
38824
38825 if (diff < bestDiff
38826 || (diff === bestDiff && prefix.name.length < bestPrefix.name.length)) {
38827 // choose the prefix with the smallest diff, or if equal, choose the one
38828 // with the shortest name (can happen with SHORTLONG for example)
38829 bestPrefix = prefix;
38830 bestDiff = diff;
38831 }
38832 }
38833 }
38834 }
38835
38836 return bestPrefix;
38837 };
38838
38839 /**
38840 * Returns an array of units whose sum is equal to this unit
38841 * @memberof Unit
38842 * @param {Array} [parts] An array of strings or valueless units.
38843 *
38844 * Example:
38845 *
38846 * var u = new Unit(1, 'm');
38847 * u.splitUnit(['feet', 'inch']);
38848 * [ 3 feet, 3.3700787401575 inch ]
38849 *
38850 * @return {Array} An array of units.
38851 */
38852 Unit.prototype.splitUnit = function(parts) {
38853
38854 var x = this.clone();
38855 var ret = [];
38856 for(var i=0; i<parts.length; i++) {
38857 // Convert x to the requested unit
38858 x = x.to(parts[i]);
38859 if(i==parts.length-1) break;
38860
38861 // Get the numeric value of this unit
38862 var xNumeric = x.toNumeric();
38863
38864 // Check to see if xNumeric is nearly equal to an integer,
38865 // since fix can incorrectly round down if there is round-off error
38866 var xRounded = round(xNumeric);
38867 var xFixed;
38868 var isNearlyEqual = equal(xRounded, xNumeric);
38869 if (isNearlyEqual) {
38870 xFixed = xRounded;
38871 }
38872 else {
38873 xFixed = fix(x.toNumeric());
38874 }
38875
38876 var y = new Unit(xFixed, parts[i].toString());
38877 ret.push(y);
38878 x = subtract(x, y);
38879 }
38880
38881 // This little bit fixes a bug where the remainder should be 0 but is a little bit off.
38882 // But instead of comparing x, the remainder, with zero--we will compare the sum of
38883 // all the parts so far with the original value. If they are nearly equal,
38884 // we set the remainder to 0.
38885 var testSum = 0;
38886 for(var i=0; i<ret.length; i++) {
38887 testSum = add(testSum, ret[i].value);
38888 }
38889 if(equal(testSum, this.value)) {
38890 x.value = 0;
38891 }
38892
38893 ret.push(x);
38894
38895 return ret;
38896 };
38897
38898 var PREFIXES = {
38899 NONE: {
38900 '': {name: '', value: 1, scientific: true}
38901 },
38902 SHORT: {
38903 '': {name: '', value: 1, scientific: true},
38904
38905 'da': {name: 'da', value: 1e1, scientific: false},
38906 'h': {name: 'h', value: 1e2, scientific: false},
38907 'k': {name: 'k', value: 1e3, scientific: true},
38908 'M': {name: 'M', value: 1e6, scientific: true},
38909 'G': {name: 'G', value: 1e9, scientific: true},
38910 'T': {name: 'T', value: 1e12, scientific: true},
38911 'P': {name: 'P', value: 1e15, scientific: true},
38912 'E': {name: 'E', value: 1e18, scientific: true},
38913 'Z': {name: 'Z', value: 1e21, scientific: true},
38914 'Y': {name: 'Y', value: 1e24, scientific: true},
38915
38916 'd': {name: 'd', value: 1e-1, scientific: false},
38917 'c': {name: 'c', value: 1e-2, scientific: false},
38918 'm': {name: 'm', value: 1e-3, scientific: true},
38919 'u': {name: 'u', value: 1e-6, scientific: true},
38920 'n': {name: 'n', value: 1e-9, scientific: true},
38921 'p': {name: 'p', value: 1e-12, scientific: true},
38922 'f': {name: 'f', value: 1e-15, scientific: true},
38923 'a': {name: 'a', value: 1e-18, scientific: true},
38924 'z': {name: 'z', value: 1e-21, scientific: true},
38925 'y': {name: 'y', value: 1e-24, scientific: true}
38926 },
38927 LONG: {
38928 '': {name: '', value: 1, scientific: true},
38929
38930 'deca': {name: 'deca', value: 1e1, scientific: false},
38931 'hecto': {name: 'hecto', value: 1e2, scientific: false},
38932 'kilo': {name: 'kilo', value: 1e3, scientific: true},
38933 'mega': {name: 'mega', value: 1e6, scientific: true},
38934 'giga': {name: 'giga', value: 1e9, scientific: true},
38935 'tera': {name: 'tera', value: 1e12, scientific: true},
38936 'peta': {name: 'peta', value: 1e15, scientific: true},
38937 'exa': {name: 'exa', value: 1e18, scientific: true},
38938 'zetta': {name: 'zetta', value: 1e21, scientific: true},
38939 'yotta': {name: 'yotta', value: 1e24, scientific: true},
38940
38941 'deci': {name: 'deci', value: 1e-1, scientific: false},
38942 'centi': {name: 'centi', value: 1e-2, scientific: false},
38943 'milli': {name: 'milli', value: 1e-3, scientific: true},
38944 'micro': {name: 'micro', value: 1e-6, scientific: true},
38945 'nano': {name: 'nano', value: 1e-9, scientific: true},
38946 'pico': {name: 'pico', value: 1e-12, scientific: true},
38947 'femto': {name: 'femto', value: 1e-15, scientific: true},
38948 'atto': {name: 'atto', value: 1e-18, scientific: true},
38949 'zepto': {name: 'zepto', value: 1e-21, scientific: true},
38950 'yocto': {name: 'yocto', value: 1e-24, scientific: true}
38951 },
38952 SQUARED: {
38953 '': {name: '', value: 1, scientific: true},
38954
38955 'da': {name: 'da', value: 1e2, scientific: false},
38956 'h': {name: 'h', value: 1e4, scientific: false},
38957 'k': {name: 'k', value: 1e6, scientific: true},
38958 'M': {name: 'M', value: 1e12, scientific: true},
38959 'G': {name: 'G', value: 1e18, scientific: true},
38960 'T': {name: 'T', value: 1e24, scientific: true},
38961 'P': {name: 'P', value: 1e30, scientific: true},
38962 'E': {name: 'E', value: 1e36, scientific: true},
38963 'Z': {name: 'Z', value: 1e42, scientific: true},
38964 'Y': {name: 'Y', value: 1e48, scientific: true},
38965
38966 'd': {name: 'd', value: 1e-2, scientific: false},
38967 'c': {name: 'c', value: 1e-4, scientific: false},
38968 'm': {name: 'm', value: 1e-6, scientific: true},
38969 'u': {name: 'u', value: 1e-12, scientific: true},
38970 'n': {name: 'n', value: 1e-18, scientific: true},
38971 'p': {name: 'p', value: 1e-24, scientific: true},
38972 'f': {name: 'f', value: 1e-30, scientific: true},
38973 'a': {name: 'a', value: 1e-36, scientific: true},
38974 'z': {name: 'z', value: 1e-42, scientific: true},
38975 'y': {name: 'y', value: 1e-48, scientific: true}
38976 },
38977 CUBIC: {
38978 '': {name: '', value: 1, scientific: true},
38979
38980 'da': {name: 'da', value: 1e3, scientific: false},
38981 'h': {name: 'h', value: 1e6, scientific: false},
38982 'k': {name: 'k', value: 1e9, scientific: true},
38983 'M': {name: 'M', value: 1e18, scientific: true},
38984 'G': {name: 'G', value: 1e27, scientific: true},
38985 'T': {name: 'T', value: 1e36, scientific: true},
38986 'P': {name: 'P', value: 1e45, scientific: true},
38987 'E': {name: 'E', value: 1e54, scientific: true},
38988 'Z': {name: 'Z', value: 1e63, scientific: true},
38989 'Y': {name: 'Y', value: 1e72, scientific: true},
38990
38991 'd': {name: 'd', value: 1e-3, scientific: false},
38992 'c': {name: 'c', value: 1e-6, scientific: false},
38993 'm': {name: 'm', value: 1e-9, scientific: true},
38994 'u': {name: 'u', value: 1e-18, scientific: true},
38995 'n': {name: 'n', value: 1e-27, scientific: true},
38996 'p': {name: 'p', value: 1e-36, scientific: true},
38997 'f': {name: 'f', value: 1e-45, scientific: true},
38998 'a': {name: 'a', value: 1e-54, scientific: true},
38999 'z': {name: 'z', value: 1e-63, scientific: true},
39000 'y': {name: 'y', value: 1e-72, scientific: true}
39001 },
39002 BINARY_SHORT: {
39003 '': {name: '', value: 1, scientific: true},
39004 'k': {name: 'k', value: 1e3, scientific: true},
39005 'M': {name: 'M', value: 1e6, scientific: true},
39006 'G': {name: 'G', value: 1e9, scientific: true},
39007 'T': {name: 'T', value: 1e12, scientific: true},
39008 'P': {name: 'P', value: 1e15, scientific: true},
39009 'E': {name: 'E', value: 1e18, scientific: true},
39010 'Z': {name: 'Z', value: 1e21, scientific: true},
39011 'Y': {name: 'Y', value: 1e24, scientific: true},
39012
39013 'Ki': {name: 'Ki', value: 1024, scientific: true},
39014 'Mi': {name: 'Mi', value: Math.pow(1024, 2), scientific: true},
39015 'Gi': {name: 'Gi', value: Math.pow(1024, 3), scientific: true},
39016 'Ti': {name: 'Ti', value: Math.pow(1024, 4), scientific: true},
39017 'Pi': {name: 'Pi', value: Math.pow(1024, 5), scientific: true},
39018 'Ei': {name: 'Ei', value: Math.pow(1024, 6), scientific: true},
39019 'Zi': {name: 'Zi', value: Math.pow(1024, 7), scientific: true},
39020 'Yi': {name: 'Yi', value: Math.pow(1024, 8), scientific: true}
39021 },
39022 BINARY_LONG: {
39023 '': {name: '', value: 1, scientific: true},
39024 'kilo': {name: 'kilo', value: 1e3, scientific: true},
39025 'mega': {name: 'mega', value: 1e6, scientific: true},
39026 'giga': {name: 'giga', value: 1e9, scientific: true},
39027 'tera': {name: 'tera', value: 1e12, scientific: true},
39028 'peta': {name: 'peta', value: 1e15, scientific: true},
39029 'exa': {name: 'exa', value: 1e18, scientific: true},
39030 'zetta': {name: 'zetta', value: 1e21, scientific: true},
39031 'yotta': {name: 'yotta', value: 1e24, scientific: true},
39032
39033 'kibi': {name: 'kibi', value: 1024, scientific: true},
39034 'mebi': {name: 'mebi', value: Math.pow(1024, 2), scientific: true},
39035 'gibi': {name: 'gibi', value: Math.pow(1024, 3), scientific: true},
39036 'tebi': {name: 'tebi', value: Math.pow(1024, 4), scientific: true},
39037 'pebi': {name: 'pebi', value: Math.pow(1024, 5), scientific: true},
39038 'exi': {name: 'exi', value: Math.pow(1024, 6), scientific: true},
39039 'zebi': {name: 'zebi', value: Math.pow(1024, 7), scientific: true},
39040 'yobi': {name: 'yobi', value: Math.pow(1024, 8), scientific: true}
39041 },
39042 BTU: {
39043 '': {name: '', value: 1, scientific: true},
39044 'MM': {name: 'MM', value: 1e6, scientific: true}
39045 }
39046 };
39047
39048 // Add a prefix list for both short and long prefixes (for ohm in particular, since Mohm and megaohm are both acceptable):
39049 PREFIXES.SHORTLONG = {};
39050 for (var key in PREFIXES.SHORT) {
39051 if(PREFIXES.SHORT.hasOwnProperty(key)) {
39052 PREFIXES.SHORTLONG[key] = PREFIXES.SHORT[key];
39053 }
39054 }
39055 for (var key in PREFIXES.LONG) {
39056 if(PREFIXES.LONG.hasOwnProperty(key)) {
39057 PREFIXES.SHORTLONG[key] = PREFIXES.LONG[key];
39058 }
39059 }
39060
39061 /* Internally, each unit is represented by a value and a dimension array. The elements of the dimensions array have the following meaning:
39062 * Index Dimension
39063 * ----- ---------
39064 * 0 Length
39065 * 1 Mass
39066 * 2 Time
39067 * 3 Current
39068 * 4 Temperature
39069 * 5 Luminous intensity
39070 * 6 Amount of substance
39071 * 7 Angle
39072 * 8 Bit (digital)
39073 * 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].
39074 *
39075 */
39076
39077 var BASE_DIMENSIONS = ["MASS", "LENGTH", "TIME", "CURRENT", "TEMPERATURE", "LUMINOUS_INTENSITY", "AMOUNT_OF_SUBSTANCE", "ANGLE", "BIT"];
39078
39079 var BASE_UNITS = {
39080 NONE: {
39081 dimensions: [0, 0, 0, 0, 0, 0, 0, 0, 0]
39082 },
39083 MASS: {
39084 dimensions: [1, 0, 0, 0, 0, 0, 0, 0, 0]
39085 },
39086 LENGTH: {
39087 dimensions: [0, 1, 0, 0, 0, 0, 0, 0, 0]
39088 },
39089 TIME: {
39090 dimensions: [0, 0, 1, 0, 0, 0, 0, 0, 0]
39091 },
39092 CURRENT: {
39093 dimensions: [0, 0, 0, 1, 0, 0, 0, 0, 0]
39094 },
39095 TEMPERATURE: {
39096 dimensions: [0, 0, 0, 0, 1, 0, 0, 0, 0]
39097 },
39098 LUMINOUS_INTENSITY: {
39099 dimensions: [0, 0, 0, 0, 0, 1, 0, 0, 0]
39100 },
39101 AMOUNT_OF_SUBSTANCE: {
39102 dimensions: [0, 0, 0, 0, 0, 0, 1, 0, 0]
39103 },
39104
39105 FORCE: {
39106 dimensions: [1, 1, -2, 0, 0, 0, 0, 0, 0]
39107 },
39108 SURFACE: {
39109 dimensions: [0, 2, 0, 0, 0, 0, 0, 0, 0]
39110 },
39111 VOLUME: {
39112 dimensions: [0, 3, 0, 0, 0, 0, 0, 0, 0]
39113 },
39114 ENERGY: {
39115 dimensions: [1, 2, -2, 0, 0, 0, 0, 0, 0]
39116 },
39117 POWER: {
39118 dimensions: [1, 2, -3, 0, 0, 0, 0, 0, 0]
39119 },
39120 PRESSURE: {
39121 dimensions: [1, -1, -2, 0, 0, 0, 0, 0, 0]
39122 },
39123
39124 ELECTRIC_CHARGE: {
39125 dimensions: [0, 0, 1, 1, 0, 0, 0, 0, 0]
39126 },
39127 ELECTRIC_CAPACITANCE: {
39128 dimensions: [-1, -2, 4, 2, 0, 0, 0, 0, 0]
39129 },
39130 ELECTRIC_POTENTIAL: {
39131 dimensions: [1, 2, -3, -1, 0, 0, 0, 0, 0]
39132 },
39133 ELECTRIC_RESISTANCE: {
39134 dimensions: [1, 2, -3, -2, 0, 0, 0, 0, 0]
39135 },
39136 ELECTRIC_INDUCTANCE: {
39137 dimensions: [1, 2, -2, -2, 0, 0, 0, 0, 0]
39138 },
39139 ELECTRIC_CONDUCTANCE: {
39140 dimensions: [-1, -2, 3, 2, 0, 0, 0, 0, 0]
39141 },
39142 MAGNETIC_FLUX: {
39143 dimensions: [1, 2, -2, -1, 0, 0, 0, 0, 0]
39144 },
39145 MAGNETIC_FLUX_DENSITY: {
39146 dimensions: [1, 0, -2, -1, 0, 0, 0, 0, 0]
39147 },
39148
39149 FREQUENCY: {
39150 dimensions: [0, 0, -1, 0, 0, 0, 0, 0, 0]
39151 },
39152 ANGLE: {
39153 dimensions: [0, 0, 0, 0, 0, 0, 0, 1, 0]
39154 },
39155 BIT: {
39156 dimensions: [0, 0, 0, 0, 0, 0, 0, 0, 1]
39157 }
39158 };
39159
39160 for(var key in BASE_UNITS) {
39161 BASE_UNITS[key].key = key;
39162 }
39163
39164 var BASE_UNIT_NONE = {};
39165
39166 var UNIT_NONE = {name: '', base: BASE_UNIT_NONE, value: 1, offset: 0, dimensions: [0,0,0,0,0,0,0,0,0]};
39167
39168 var UNITS = {
39169 // length
39170 meter: {
39171 name: 'meter',
39172 base: BASE_UNITS.LENGTH,
39173 prefixes: PREFIXES.LONG,
39174 value: 1,
39175 offset: 0
39176 },
39177 inch: {
39178 name: 'inch',
39179 base: BASE_UNITS.LENGTH,
39180 prefixes: PREFIXES.NONE,
39181 value: 0.0254,
39182 offset: 0
39183 },
39184 foot: {
39185 name: 'foot',
39186 base: BASE_UNITS.LENGTH,
39187 prefixes: PREFIXES.NONE,
39188 value: 0.3048,
39189 offset: 0
39190 },
39191 yard: {
39192 name: 'yard',
39193 base: BASE_UNITS.LENGTH,
39194 prefixes: PREFIXES.NONE,
39195 value: 0.9144,
39196 offset: 0
39197 },
39198 mile: {
39199 name: 'mile',
39200 base: BASE_UNITS.LENGTH,
39201 prefixes: PREFIXES.NONE,
39202 value: 1609.344,
39203 offset: 0
39204 },
39205 link: {
39206 name: 'link',
39207 base: BASE_UNITS.LENGTH,
39208 prefixes: PREFIXES.NONE,
39209 value: 0.201168,
39210 offset: 0
39211 },
39212 rod: {
39213 name: 'rod',
39214 base: BASE_UNITS.LENGTH,
39215 prefixes: PREFIXES.NONE,
39216 value: 5.029210,
39217 offset: 0
39218 },
39219 chain: {
39220 name: 'chain',
39221 base: BASE_UNITS.LENGTH,
39222 prefixes: PREFIXES.NONE,
39223 value: 20.1168,
39224 offset: 0
39225 },
39226 angstrom: {
39227 name: 'angstrom',
39228 base: BASE_UNITS.LENGTH,
39229 prefixes: PREFIXES.NONE,
39230 value: 1e-10,
39231 offset: 0
39232 },
39233
39234 m: {
39235 name: 'm',
39236 base: BASE_UNITS.LENGTH,
39237 prefixes: PREFIXES.SHORT,
39238 value: 1,
39239 offset: 0
39240 },
39241 'in': {
39242 name: 'in',
39243 base: BASE_UNITS.LENGTH,
39244 prefixes: PREFIXES.NONE,
39245 value: 0.0254,
39246 offset: 0
39247 },
39248 ft: {
39249 name: 'ft',
39250 base: BASE_UNITS.LENGTH,
39251 prefixes: PREFIXES.NONE,
39252 value: 0.3048,
39253 offset: 0
39254 },
39255 yd: {
39256 name: 'yd',
39257 base: BASE_UNITS.LENGTH,
39258 prefixes: PREFIXES.NONE,
39259 value: 0.9144,
39260 offset: 0
39261 },
39262 mi: {
39263 name: 'mi',
39264 base: BASE_UNITS.LENGTH,
39265 prefixes: PREFIXES.NONE,
39266 value: 1609.344,
39267 offset: 0
39268 },
39269 li: {
39270 name: 'li',
39271 base: BASE_UNITS.LENGTH,
39272 prefixes: PREFIXES.NONE,
39273 value: 0.201168,
39274 offset: 0
39275 },
39276 rd: {
39277 name: 'rd',
39278 base: BASE_UNITS.LENGTH,
39279 prefixes: PREFIXES.NONE,
39280 value: 5.029210,
39281 offset: 0
39282 },
39283 ch: {
39284 name: 'ch',
39285 base: BASE_UNITS.LENGTH,
39286 prefixes: PREFIXES.NONE,
39287 value: 20.1168,
39288 offset: 0
39289 },
39290 mil: {
39291 name: 'mil',
39292 base: BASE_UNITS.LENGTH,
39293 prefixes: PREFIXES.NONE,
39294 value: 0.0000254,
39295 offset: 0
39296 }, // 1/1000 inch
39297
39298 // Surface
39299 m2: {
39300 name: 'm2',
39301 base: BASE_UNITS.SURFACE,
39302 prefixes: PREFIXES.SQUARED,
39303 value: 1,
39304 offset: 0
39305 },
39306 sqin: {
39307 name: 'sqin',
39308 base: BASE_UNITS.SURFACE,
39309 prefixes: PREFIXES.NONE,
39310 value: 0.00064516,
39311 offset: 0
39312 }, // 645.16 mm2
39313 sqft: {
39314 name: 'sqft',
39315 base: BASE_UNITS.SURFACE,
39316 prefixes: PREFIXES.NONE,
39317 value: 0.09290304,
39318 offset: 0
39319 }, // 0.09290304 m2
39320 sqyd: {
39321 name: 'sqyd',
39322 base: BASE_UNITS.SURFACE,
39323 prefixes: PREFIXES.NONE,
39324 value: 0.83612736,
39325 offset: 0
39326 }, // 0.83612736 m2
39327 sqmi: {
39328 name: 'sqmi',
39329 base: BASE_UNITS.SURFACE,
39330 prefixes: PREFIXES.NONE,
39331 value: 2589988.110336,
39332 offset: 0
39333 }, // 2.589988110336 km2
39334 sqrd: {
39335 name: 'sqrd',
39336 base: BASE_UNITS.SURFACE,
39337 prefixes: PREFIXES.NONE,
39338 value: 25.29295,
39339 offset: 0
39340 }, // 25.29295 m2
39341 sqch: {
39342 name: 'sqch',
39343 base: BASE_UNITS.SURFACE,
39344 prefixes: PREFIXES.NONE,
39345 value: 404.6873,
39346 offset: 0
39347 }, // 404.6873 m2
39348 sqmil: {
39349 name: 'sqmil',
39350 base: BASE_UNITS.SURFACE,
39351 prefixes: PREFIXES.NONE,
39352 value: 6.4516e-10,
39353 offset: 0
39354 }, // 6.4516 * 10^-10 m2
39355 acre: {
39356 name: 'acre',
39357 base: BASE_UNITS.SURFACE,
39358 prefixes: PREFIXES.NONE,
39359 value: 4046.86,
39360 offset: 0
39361 }, // 4046.86 m2
39362 hectare: {
39363 name: 'hectare',
39364 base: BASE_UNITS.SURFACE,
39365 prefixes: PREFIXES.NONE,
39366 value: 10000,
39367 offset: 0
39368 }, // 10000 m2
39369
39370 // Volume
39371 m3: {
39372 name: 'm3',
39373 base: BASE_UNITS.VOLUME,
39374 prefixes: PREFIXES.CUBIC,
39375 value: 1,
39376 offset: 0
39377 },
39378 L: {
39379 name: 'L',
39380 base: BASE_UNITS.VOLUME,
39381 prefixes: PREFIXES.SHORT,
39382 value: 0.001,
39383 offset: 0
39384 }, // litre
39385 l: {
39386 name: 'l',
39387 base: BASE_UNITS.VOLUME,
39388 prefixes: PREFIXES.SHORT,
39389 value: 0.001,
39390 offset: 0
39391 }, // litre
39392 litre: {
39393 name: 'litre',
39394 base: BASE_UNITS.VOLUME,
39395 prefixes: PREFIXES.LONG,
39396 value: 0.001,
39397 offset: 0
39398 },
39399 cuin: {
39400 name: 'cuin',
39401 base: BASE_UNITS.VOLUME,
39402 prefixes: PREFIXES.NONE,
39403 value: 1.6387064e-5,
39404 offset: 0
39405 }, // 1.6387064e-5 m3
39406 cuft: {
39407 name: 'cuft',
39408 base: BASE_UNITS.VOLUME,
39409 prefixes: PREFIXES.NONE,
39410 value: 0.028316846592,
39411 offset: 0
39412 }, // 28.316 846 592 L
39413 cuyd: {
39414 name: 'cuyd',
39415 base: BASE_UNITS.VOLUME,
39416 prefixes: PREFIXES.NONE,
39417 value: 0.764554857984,
39418 offset: 0
39419 }, // 764.554 857 984 L
39420 teaspoon: {
39421 name: 'teaspoon',
39422 base: BASE_UNITS.VOLUME,
39423 prefixes: PREFIXES.NONE,
39424 value: 0.000005,
39425 offset: 0
39426 }, // 5 mL
39427 tablespoon: {
39428 name: 'tablespoon',
39429 base: BASE_UNITS.VOLUME,
39430 prefixes: PREFIXES.NONE,
39431 value: 0.000015,
39432 offset: 0
39433 }, // 15 mL
39434 //{name: 'cup', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.000240, offset: 0}, // 240 mL // not possible, we have already another cup
39435 drop: {
39436 name: 'drop',
39437 base: BASE_UNITS.VOLUME,
39438 prefixes: PREFIXES.NONE,
39439 value: 5e-8,
39440 offset: 0
39441 }, // 0.05 mL = 5e-8 m3
39442 gtt: {
39443 name: 'gtt',
39444 base: BASE_UNITS.VOLUME,
39445 prefixes: PREFIXES.NONE,
39446 value: 5e-8,
39447 offset: 0
39448 }, // 0.05 mL = 5e-8 m3
39449
39450 // Liquid volume
39451 minim: {
39452 name: 'minim',
39453 base: BASE_UNITS.VOLUME,
39454 prefixes: PREFIXES.NONE,
39455 value: 0.00000006161152,
39456 offset: 0
39457 }, // 0.06161152 mL
39458 fluiddram: {
39459 name: 'fluiddram',
39460 base: BASE_UNITS.VOLUME,
39461 prefixes: PREFIXES.NONE,
39462 value: 0.0000036966911,
39463 offset: 0
39464 }, // 3.696691 mL
39465 fluidounce: {
39466 name: 'fluidounce',
39467 base: BASE_UNITS.VOLUME,
39468 prefixes: PREFIXES.NONE,
39469 value: 0.00002957353,
39470 offset: 0
39471 }, // 29.57353 mL
39472 gill: {
39473 name: 'gill',
39474 base: BASE_UNITS.VOLUME,
39475 prefixes: PREFIXES.NONE,
39476 value: 0.0001182941,
39477 offset: 0
39478 }, // 118.2941 mL
39479 cc: {
39480 name: 'cc',
39481 base: BASE_UNITS.VOLUME,
39482 prefixes: PREFIXES.NONE,
39483 value: 1e-6,
39484 offset: 0
39485 }, // 1e-6 L
39486 cup: {
39487 name: 'cup',
39488 base: BASE_UNITS.VOLUME,
39489 prefixes: PREFIXES.NONE,
39490 value: 0.0002365882,
39491 offset: 0
39492 }, // 236.5882 mL
39493 pint: {
39494 name: 'pint',
39495 base: BASE_UNITS.VOLUME,
39496 prefixes: PREFIXES.NONE,
39497 value: 0.0004731765,
39498 offset: 0
39499 }, // 473.1765 mL
39500 quart: {
39501 name: 'quart',
39502 base: BASE_UNITS.VOLUME,
39503 prefixes: PREFIXES.NONE,
39504 value: 0.0009463529,
39505 offset: 0
39506 }, // 946.3529 mL
39507 gallon: {
39508 name: 'gallon',
39509 base: BASE_UNITS.VOLUME,
39510 prefixes: PREFIXES.NONE,
39511 value: 0.003785412,
39512 offset: 0
39513 }, // 3.785412 L
39514 beerbarrel: {
39515 name: 'beerbarrel',
39516 base: BASE_UNITS.VOLUME,
39517 prefixes: PREFIXES.NONE,
39518 value: 0.1173478,
39519 offset: 0
39520 }, // 117.3478 L
39521 oilbarrel: {
39522 name: 'oilbarrel',
39523 base: BASE_UNITS.VOLUME,
39524 prefixes: PREFIXES.NONE,
39525 value: 0.1589873,
39526 offset: 0
39527 }, // 158.9873 L
39528 hogshead: {
39529 name: 'hogshead',
39530 base: BASE_UNITS.VOLUME,
39531 prefixes: PREFIXES.NONE,
39532 value: 0.2384810,
39533 offset: 0
39534 }, // 238.4810 L
39535
39536 //{name: 'min', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.00000006161152, offset: 0}, // 0.06161152 mL // min is already in use as minute
39537 fldr: {
39538 name: 'fldr',
39539 base: BASE_UNITS.VOLUME,
39540 prefixes: PREFIXES.NONE,
39541 value: 0.0000036966911,
39542 offset: 0
39543 }, // 3.696691 mL
39544 floz: {
39545 name: 'floz',
39546 base: BASE_UNITS.VOLUME,
39547 prefixes: PREFIXES.NONE,
39548 value: 0.00002957353,
39549 offset: 0
39550 }, // 29.57353 mL
39551 gi: {
39552 name: 'gi',
39553 base: BASE_UNITS.VOLUME,
39554 prefixes: PREFIXES.NONE,
39555 value: 0.0001182941,
39556 offset: 0
39557 }, // 118.2941 mL
39558 cp: {
39559 name: 'cp',
39560 base: BASE_UNITS.VOLUME,
39561 prefixes: PREFIXES.NONE,
39562 value: 0.0002365882,
39563 offset: 0
39564 }, // 236.5882 mL
39565 pt: {
39566 name: 'pt',
39567 base: BASE_UNITS.VOLUME,
39568 prefixes: PREFIXES.NONE,
39569 value: 0.0004731765,
39570 offset: 0
39571 }, // 473.1765 mL
39572 qt: {
39573 name: 'qt',
39574 base: BASE_UNITS.VOLUME,
39575 prefixes: PREFIXES.NONE,
39576 value: 0.0009463529,
39577 offset: 0
39578 }, // 946.3529 mL
39579 gal: {
39580 name: 'gal',
39581 base: BASE_UNITS.VOLUME,
39582 prefixes: PREFIXES.NONE,
39583 value: 0.003785412,
39584 offset: 0
39585 }, // 3.785412 L
39586 bbl: {
39587 name: 'bbl',
39588 base: BASE_UNITS.VOLUME,
39589 prefixes: PREFIXES.NONE,
39590 value: 0.1173478,
39591 offset: 0
39592 }, // 117.3478 L
39593 obl: {
39594 name: 'obl',
39595 base: BASE_UNITS.VOLUME,
39596 prefixes: PREFIXES.NONE,
39597 value: 0.1589873,
39598 offset: 0
39599 }, // 158.9873 L
39600 //{name: 'hogshead', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.2384810, offset: 0}, // 238.4810 L // TODO: hh?
39601
39602 // Mass
39603 g: {
39604 name: 'g',
39605 base: BASE_UNITS.MASS,
39606 prefixes: PREFIXES.SHORT,
39607 value: 0.001,
39608 offset: 0
39609 },
39610 gram: {
39611 name: 'gram',
39612 base: BASE_UNITS.MASS,
39613 prefixes: PREFIXES.LONG,
39614 value: 0.001,
39615 offset: 0
39616 },
39617
39618 ton: {
39619 name: 'ton',
39620 base: BASE_UNITS.MASS,
39621 prefixes: PREFIXES.SHORT,
39622 value: 907.18474,
39623 offset: 0
39624 },
39625 tonne: {
39626 name: 'tonne',
39627 base: BASE_UNITS.MASS,
39628 prefixes: PREFIXES.SHORT,
39629 value: 1000,
39630 offset: 0
39631 },
39632
39633 grain: {
39634 name: 'grain',
39635 base: BASE_UNITS.MASS,
39636 prefixes: PREFIXES.NONE,
39637 value: 64.79891e-6,
39638 offset: 0
39639 },
39640 dram: {
39641 name: 'dram',
39642 base: BASE_UNITS.MASS,
39643 prefixes: PREFIXES.NONE,
39644 value: 1.7718451953125e-3,
39645 offset: 0
39646 },
39647 ounce: {
39648 name: 'ounce',
39649 base: BASE_UNITS.MASS,
39650 prefixes: PREFIXES.NONE,
39651 value: 28.349523125e-3,
39652 offset: 0
39653 },
39654 poundmass: {
39655 name: 'poundmass',
39656 base: BASE_UNITS.MASS,
39657 prefixes: PREFIXES.NONE,
39658 value: 453.59237e-3,
39659 offset: 0
39660 },
39661 hundredweight: {
39662 name: 'hundredweight',
39663 base: BASE_UNITS.MASS,
39664 prefixes: PREFIXES.NONE,
39665 value: 45.359237,
39666 offset: 0
39667 },
39668 stick: {
39669 name: 'stick',
39670 base: BASE_UNITS.MASS,
39671 prefixes: PREFIXES.NONE,
39672 value: 115e-3,
39673 offset: 0
39674 },
39675 stone: {
39676 name: 'stone',
39677 base: BASE_UNITS.MASS,
39678 prefixes: PREFIXES.NONE,
39679 value: 6.35029318,
39680 offset: 0
39681 },
39682
39683 gr: {
39684 name: 'gr',
39685 base: BASE_UNITS.MASS,
39686 prefixes: PREFIXES.NONE,
39687 value: 64.79891e-6,
39688 offset: 0
39689 },
39690 dr: {
39691 name: 'dr',
39692 base: BASE_UNITS.MASS,
39693 prefixes: PREFIXES.NONE,
39694 value: 1.7718451953125e-3,
39695 offset: 0
39696 },
39697 oz: {
39698 name: 'oz',
39699 base: BASE_UNITS.MASS,
39700 prefixes: PREFIXES.NONE,
39701 value: 28.349523125e-3,
39702 offset: 0
39703 },
39704 lbm: {
39705 name: 'lbm',
39706 base: BASE_UNITS.MASS,
39707 prefixes: PREFIXES.NONE,
39708 value: 453.59237e-3,
39709 offset: 0
39710 },
39711 cwt: {
39712 name: 'cwt',
39713 base: BASE_UNITS.MASS,
39714 prefixes: PREFIXES.NONE,
39715 value: 45.359237,
39716 offset: 0
39717 },
39718
39719 // Time
39720 s: {
39721 name: 's',
39722 base: BASE_UNITS.TIME,
39723 prefixes: PREFIXES.SHORT,
39724 value: 1,
39725 offset: 0
39726 },
39727 min: {
39728 name: 'min',
39729 base: BASE_UNITS.TIME,
39730 prefixes: PREFIXES.NONE,
39731 value: 60,
39732 offset: 0
39733 },
39734 h: {
39735 name: 'h',
39736 base: BASE_UNITS.TIME,
39737 prefixes: PREFIXES.NONE,
39738 value: 3600,
39739 offset: 0
39740 },
39741 second: {
39742 name: 'second',
39743 base: BASE_UNITS.TIME,
39744 prefixes: PREFIXES.LONG,
39745 value: 1,
39746 offset: 0
39747 },
39748 sec: {
39749 name: 'sec',
39750 base: BASE_UNITS.TIME,
39751 prefixes: PREFIXES.LONG,
39752 value: 1,
39753 offset: 0
39754 },
39755 minute: {
39756 name: 'minute',
39757 base: BASE_UNITS.TIME,
39758 prefixes: PREFIXES.NONE,
39759 value: 60,
39760 offset: 0
39761 },
39762 hour: {
39763 name: 'hour',
39764 base: BASE_UNITS.TIME,
39765 prefixes: PREFIXES.NONE,
39766 value: 3600,
39767 offset: 0
39768 },
39769 day: {
39770 name: 'day',
39771 base: BASE_UNITS.TIME,
39772 prefixes: PREFIXES.NONE,
39773 value: 86400,
39774 offset: 0
39775 },
39776 week: {
39777 name: 'week',
39778 base: BASE_UNITS.TIME,
39779 prefixes: PREFIXES.NONE,
39780 value: 7*86400,
39781 offset: 0
39782 },
39783 month: {
39784 name: 'month',
39785 base: BASE_UNITS.TIME,
39786 prefixes: PREFIXES.NONE,
39787 value: 2629800, //1/12th of Julian year
39788 offset: 0
39789 },
39790 year: {
39791 name: 'year',
39792 base: BASE_UNITS.TIME,
39793 prefixes: PREFIXES.NONE,
39794 value: 31557600, //Julian year
39795 offset: 0
39796 },
39797 decade: {
39798 name: 'year',
39799 base: BASE_UNITS.TIME,
39800 prefixes: PREFIXES.NONE,
39801 value: 315576000, //Julian decade
39802 offset: 0
39803 },
39804 century: {
39805 name: 'century',
39806 base: BASE_UNITS.TIME,
39807 prefixes: PREFIXES.NONE,
39808 value: 3155760000, //Julian century
39809 offset: 0
39810 },
39811 millennium: {
39812 name: 'millennium',
39813 base: BASE_UNITS.TIME,
39814 prefixes: PREFIXES.NONE,
39815 value: 31557600000, //Julian millennium
39816 offset: 0
39817 },
39818
39819 // Frequency
39820 hertz: {
39821 name: 'Hertz',
39822 base: BASE_UNITS.FREQUENCY,
39823 prefixes: PREFIXES.LONG,
39824 value: 1,
39825 offset: 0,
39826 reciprocal: true
39827 },
39828 Hz: {
39829 name: 'Hz',
39830 base: BASE_UNITS.FREQUENCY,
39831 prefixes: PREFIXES.SHORT,
39832 value: 1,
39833 offset: 0,
39834 reciprocal: true
39835 },
39836
39837 // Angle
39838 rad: {
39839 name: 'rad',
39840 base: BASE_UNITS.ANGLE,
39841 prefixes: PREFIXES.LONG,
39842 value: 1,
39843 offset: 0
39844 },
39845 // deg = rad / (2*pi) * 360 = rad / 0.017453292519943295769236907684888
39846 deg: {
39847 name: 'deg',
39848 base: BASE_UNITS.ANGLE,
39849 prefixes: PREFIXES.LONG,
39850 value: null, // will be filled in by calculateAngleValues()
39851 offset: 0
39852 },
39853 // grad = rad / (2*pi) * 400 = rad / 0.015707963267948966192313216916399
39854 grad: {
39855 name: 'grad',
39856 base: BASE_UNITS.ANGLE,
39857 prefixes: PREFIXES.LONG,
39858 value: null, // will be filled in by calculateAngleValues()
39859 offset: 0
39860 },
39861 // cycle = rad / (2*pi) = rad / 6.2831853071795864769252867665793
39862 cycle: {
39863 name: 'cycle',
39864 base: BASE_UNITS.ANGLE,
39865 prefixes: PREFIXES.NONE,
39866 value: null, // will be filled in by calculateAngleValues()
39867 offset: 0
39868 },
39869 // arcsec = rad / (3600 * (360 / 2 * pi)) = rad / 0.0000048481368110953599358991410235795
39870 arcsec: {
39871 name: 'arcsec',
39872 base: BASE_UNITS.ANGLE,
39873 prefixes: PREFIXES.NONE,
39874 value: null, // will be filled in by calculateAngleValues()
39875 offset: 0
39876 },
39877 // arcmin = rad / (60 * (360 / 2 * pi)) = rad / 0.00029088820866572159615394846141477
39878 arcmin: {
39879 name: 'arcmin',
39880 base: BASE_UNITS.ANGLE,
39881 prefixes: PREFIXES.NONE,
39882 value: null, // will be filled in by calculateAngleValues()
39883 offset: 0
39884 },
39885
39886 // Electric current
39887 A: {
39888 name: 'A',
39889 base: BASE_UNITS.CURRENT,
39890 prefixes: PREFIXES.SHORT,
39891 value: 1,
39892 offset: 0
39893 },
39894 ampere: {
39895 name: 'ampere',
39896 base: BASE_UNITS.CURRENT,
39897 prefixes: PREFIXES.LONG,
39898 value: 1,
39899 offset: 0
39900 },
39901
39902 // Temperature
39903 // K(C) = °C + 273.15
39904 // K(F) = (°F + 459.67) / 1.8
39905 // K(R) = °R / 1.8
39906 K: {
39907 name: 'K',
39908 base: BASE_UNITS.TEMPERATURE,
39909 prefixes: PREFIXES.NONE,
39910 value: 1,
39911 offset: 0
39912 },
39913 degC: {
39914 name: 'degC',
39915 base: BASE_UNITS.TEMPERATURE,
39916 prefixes: PREFIXES.NONE,
39917 value: 1,
39918 offset: 273.15
39919 },
39920 degF: {
39921 name: 'degF',
39922 base: BASE_UNITS.TEMPERATURE,
39923 prefixes: PREFIXES.NONE,
39924 value: 1 / 1.8,
39925 offset: 459.67
39926 },
39927 degR: {
39928 name: 'degR',
39929 base: BASE_UNITS.TEMPERATURE,
39930 prefixes: PREFIXES.NONE,
39931 value: 1 / 1.8,
39932 offset: 0
39933 },
39934 kelvin: {
39935 name: 'kelvin',
39936 base: BASE_UNITS.TEMPERATURE,
39937 prefixes: PREFIXES.NONE,
39938 value: 1,
39939 offset: 0
39940 },
39941 celsius: {
39942 name: 'celsius',
39943 base: BASE_UNITS.TEMPERATURE,
39944 prefixes: PREFIXES.NONE,
39945 value: 1,
39946 offset: 273.15
39947 },
39948 fahrenheit: {
39949 name: 'fahrenheit',
39950 base: BASE_UNITS.TEMPERATURE,
39951 prefixes: PREFIXES.NONE,
39952 value: 1 / 1.8,
39953 offset: 459.67
39954 },
39955 rankine: {
39956 name: 'rankine',
39957 base: BASE_UNITS.TEMPERATURE,
39958 prefixes: PREFIXES.NONE,
39959 value: 1 / 1.8,
39960 offset: 0
39961 },
39962
39963 // amount of substance
39964 mol: {
39965 name: 'mol',
39966 base: BASE_UNITS.AMOUNT_OF_SUBSTANCE,
39967 prefixes: PREFIXES.SHORT,
39968 value: 1,
39969 offset: 0
39970 },
39971 mole: {
39972 name: 'mole',
39973 base: BASE_UNITS.AMOUNT_OF_SUBSTANCE,
39974 prefixes: PREFIXES.LONG,
39975 value: 1,
39976 offset: 0
39977 },
39978
39979 // luminous intensity
39980 cd: {
39981 name: 'cd',
39982 base: BASE_UNITS.LUMINOUS_INTENSITY,
39983 prefixes: PREFIXES.NONE,
39984 value: 1,
39985 offset: 0
39986 },
39987 candela: {
39988 name: 'candela',
39989 base: BASE_UNITS.LUMINOUS_INTENSITY,
39990 prefixes: PREFIXES.NONE,
39991 value: 1,
39992 offset: 0
39993 },
39994 // TODO: units STERADIAN
39995 //{name: 'sr', base: BASE_UNITS.STERADIAN, prefixes: PREFIXES.NONE, value: 1, offset: 0},
39996 //{name: 'steradian', base: BASE_UNITS.STERADIAN, prefixes: PREFIXES.NONE, value: 1, offset: 0},
39997
39998 // Force
39999 N: {
40000 name: 'N',
40001 base: BASE_UNITS.FORCE,
40002 prefixes: PREFIXES.SHORT,
40003 value: 1,
40004 offset: 0
40005 },
40006 newton: {
40007 name: 'newton',
40008 base: BASE_UNITS.FORCE,
40009 prefixes: PREFIXES.LONG,
40010 value: 1,
40011 offset: 0
40012 },
40013 dyn: {
40014 name: 'dyn',
40015 base: BASE_UNITS.FORCE,
40016 prefixes: PREFIXES.SHORT,
40017 value: 0.00001,
40018 offset: 0
40019 },
40020 dyne: {
40021 name: 'dyne',
40022 base: BASE_UNITS.FORCE,
40023 prefixes: PREFIXES.LONG,
40024 value: 0.00001,
40025 offset: 0
40026 },
40027 lbf: {
40028 name: 'lbf',
40029 base: BASE_UNITS.FORCE,
40030 prefixes: PREFIXES.NONE,
40031 value: 4.4482216152605,
40032 offset: 0
40033 },
40034 poundforce: {
40035 name: 'poundforce',
40036 base: BASE_UNITS.FORCE,
40037 prefixes: PREFIXES.NONE,
40038 value: 4.4482216152605,
40039 offset: 0
40040 },
40041 kip: {
40042 name: 'kip',
40043 base: BASE_UNITS.FORCE,
40044 prefixes: PREFIXES.LONG,
40045 value: 4448.2216,
40046 offset: 0
40047 },
40048
40049 // Energy
40050 J: {
40051 name: 'J',
40052 base: BASE_UNITS.ENERGY,
40053 prefixes: PREFIXES.SHORT,
40054 value: 1,
40055 offset: 0
40056 },
40057 joule: {
40058 name: 'joule',
40059 base: BASE_UNITS.ENERGY,
40060 prefixes: PREFIXES.SHORT,
40061 value: 1,
40062 offset: 0
40063 },
40064 erg: {
40065 name: 'erg',
40066 base: BASE_UNITS.ENERGY,
40067 prefixes: PREFIXES.NONE,
40068 value: 1e-7,
40069 offset: 0
40070 },
40071 Wh: {
40072 name: 'Wh',
40073 base: BASE_UNITS.ENERGY,
40074 prefixes: PREFIXES.SHORT,
40075 value: 3600,
40076 offset: 0
40077 },
40078 BTU: {
40079 name: 'BTU',
40080 base: BASE_UNITS.ENERGY,
40081 prefixes: PREFIXES.BTU,
40082 value: 1055.05585262,
40083 offset: 0
40084 },
40085 eV: {
40086 name: 'eV',
40087 base: BASE_UNITS.ENERGY,
40088 prefixes: PREFIXES.SHORT,
40089 value: 1.602176565e-19,
40090 offset: 0
40091 },
40092 electronvolt: {
40093 name: 'electronvolt',
40094 base: BASE_UNITS.ENERGY,
40095 prefixes: PREFIXES.LONG,
40096 value: 1.602176565e-19,
40097 offset: 0
40098 },
40099
40100
40101 // Power
40102 W: {
40103 name: 'W',
40104 base: BASE_UNITS.POWER,
40105 prefixes: PREFIXES.SHORT,
40106 value: 1,
40107 offset: 0
40108 },
40109 watt: {
40110 name: 'W',
40111 base: BASE_UNITS.POWER,
40112 prefixes: PREFIXES.LONG,
40113 value: 1,
40114 offset: 0
40115 },
40116 hp: {
40117 name: 'hp',
40118 base: BASE_UNITS.POWER,
40119 prefixes: PREFIXES.NONE,
40120 value: 745.6998715386,
40121 offset: 0
40122 },
40123
40124 // Electrical power units
40125 VAR: {
40126 name: 'VAR',
40127 base: BASE_UNITS.POWER,
40128 prefixes: PREFIXES.SHORT,
40129 value: Complex.I,
40130 offset: 0
40131 },
40132
40133 VA: {
40134 name: 'VA',
40135 base: BASE_UNITS.POWER,
40136 prefixes: PREFIXES.SHORT,
40137 value: 1,
40138 offset: 0
40139 },
40140
40141 // Pressure
40142 Pa: {
40143 name: 'Pa',
40144 base: BASE_UNITS.PRESSURE,
40145 prefixes: PREFIXES.SHORT,
40146 value: 1,
40147 offset: 0
40148 },
40149 psi: {
40150 name: 'psi',
40151 base: BASE_UNITS.PRESSURE,
40152 prefixes: PREFIXES.NONE,
40153 value: 6894.75729276459,
40154 offset: 0
40155 },
40156 atm: {
40157 name: 'atm',
40158 base: BASE_UNITS.PRESSURE,
40159 prefixes: PREFIXES.NONE,
40160 value: 101325,
40161 offset: 0
40162 },
40163 bar: {
40164 name: 'bar',
40165 base: BASE_UNITS.PRESSURE,
40166 prefixes: PREFIXES.NONE,
40167 value: 100000,
40168 offset: 0
40169 },
40170 torr: {
40171 name: 'torr',
40172 base: BASE_UNITS.PRESSURE,
40173 prefixes: PREFIXES.NONE,
40174 value: 133.322,
40175 offset: 0
40176 },
40177 mmHg: {
40178 name: 'mmHg',
40179 base: BASE_UNITS.PRESSURE,
40180 prefixes: PREFIXES.NONE,
40181 value: 133.322,
40182 offset: 0
40183 },
40184 mmH2O: {
40185 name: 'mmH2O',
40186 base: BASE_UNITS.PRESSURE,
40187 prefixes: PREFIXES.NONE,
40188 value: 9.80665,
40189 offset: 0
40190 },
40191 cmH2O: {
40192 name: 'cmH2O',
40193 base: BASE_UNITS.PRESSURE,
40194 prefixes: PREFIXES.NONE,
40195 value: 98.0665,
40196 offset: 0
40197 },
40198
40199 // Electric charge
40200 coulomb: {
40201 name: 'coulomb',
40202 base: BASE_UNITS.ELECTRIC_CHARGE,
40203 prefixes: PREFIXES.LONG,
40204 value: 1,
40205 offset: 0
40206 },
40207 C: {
40208 name: 'C',
40209 base: BASE_UNITS.ELECTRIC_CHARGE,
40210 prefixes: PREFIXES.SHORT,
40211 value: 1,
40212 offset: 0
40213 },
40214 // Electric capacitance
40215 farad: {
40216 name: 'farad',
40217 base: BASE_UNITS.ELECTRIC_CAPACITANCE,
40218 prefixes: PREFIXES.LONG,
40219 value: 1,
40220 offset: 0
40221 },
40222 F: {
40223 name: 'F',
40224 base: BASE_UNITS.ELECTRIC_CAPACITANCE,
40225 prefixes: PREFIXES.SHORT,
40226 value: 1,
40227 offset: 0
40228 },
40229 // Electric potential
40230 volt: {
40231 name: 'volt',
40232 base: BASE_UNITS.ELECTRIC_POTENTIAL,
40233 prefixes: PREFIXES.LONG,
40234 value: 1,
40235 offset: 0
40236 },
40237 V: {
40238 name: 'V',
40239 base: BASE_UNITS.ELECTRIC_POTENTIAL,
40240 prefixes: PREFIXES.SHORT,
40241 value: 1,
40242 offset: 0
40243 },
40244 // Electric resistance
40245 ohm: {
40246 name: 'ohm',
40247 base: BASE_UNITS.ELECTRIC_RESISTANCE,
40248 prefixes: PREFIXES.SHORTLONG, // Both Mohm and megaohm are acceptable
40249 value: 1,
40250 offset: 0
40251 },
40252 /*
40253 * Unicode breaks in browsers if charset is not specified
40254 Ω: {
40255 name: 'Ω',
40256 base: BASE_UNITS.ELECTRIC_RESISTANCE,
40257 prefixes: PREFIXES.SHORT,
40258 value: 1,
40259 offset: 0
40260 },
40261 */
40262 // Electric inductance
40263 henry: {
40264 name: 'henry',
40265 base: BASE_UNITS.ELECTRIC_INDUCTANCE,
40266 prefixes: PREFIXES.LONG,
40267 value: 1,
40268 offset: 0
40269 },
40270 H: {
40271 name: 'H',
40272 base: BASE_UNITS.ELECTRIC_INDUCTANCE,
40273 prefixes: PREFIXES.SHORT,
40274 value: 1,
40275 offset: 0
40276 },
40277 // Electric conductance
40278 siemens: {
40279 name: 'siemens',
40280 base: BASE_UNITS.ELECTRIC_CONDUCTANCE,
40281 prefixes: PREFIXES.LONG,
40282 value: 1,
40283 offset: 0
40284 },
40285 S: {
40286 name: 'S',
40287 base: BASE_UNITS.ELECTRIC_CONDUCTANCE,
40288 prefixes: PREFIXES.SHORT,
40289 value: 1,
40290 offset: 0
40291 },
40292 // Magnetic flux
40293 weber: {
40294 name: 'weber',
40295 base: BASE_UNITS.MAGNETIC_FLUX,
40296 prefixes: PREFIXES.LONG,
40297 value: 1,
40298 offset: 0
40299 },
40300 Wb: {
40301 name: 'Wb',
40302 base: BASE_UNITS.MAGNETIC_FLUX,
40303 prefixes: PREFIXES.SHORT,
40304 value: 1,
40305 offset: 0
40306 },
40307 // Magnetic flux density
40308 tesla: {
40309 name: 'tesla',
40310 base: BASE_UNITS.MAGNETIC_FLUX_DENSITY,
40311 prefixes: PREFIXES.LONG,
40312 value: 1,
40313 offset: 0
40314 },
40315 T: {
40316 name: 'T',
40317 base: BASE_UNITS.MAGNETIC_FLUX_DENSITY,
40318 prefixes: PREFIXES.SHORT,
40319 value: 1,
40320 offset: 0
40321 },
40322
40323 // Binary
40324 b: {
40325 name: 'b',
40326 base: BASE_UNITS.BIT,
40327 prefixes: PREFIXES.BINARY_SHORT,
40328 value: 1,
40329 offset: 0
40330 },
40331 bits: {
40332 name: 'bits',
40333 base: BASE_UNITS.BIT,
40334 prefixes: PREFIXES.BINARY_LONG,
40335 value: 1,
40336 offset: 0
40337 },
40338 B: {
40339 name: 'B',
40340 base: BASE_UNITS.BIT,
40341 prefixes: PREFIXES.BINARY_SHORT,
40342 value: 8,
40343 offset: 0
40344 },
40345 bytes: {
40346 name: 'bytes',
40347 base: BASE_UNITS.BIT,
40348 prefixes: PREFIXES.BINARY_LONG,
40349 value: 8,
40350 offset: 0
40351 }
40352 };
40353
40354 // aliases (formerly plurals)
40355 var ALIASES = {
40356 meters: 'meter',
40357 inches: 'inch',
40358 feet: 'foot',
40359 yards: 'yard',
40360 miles: 'mile',
40361 links: 'link',
40362 rods: 'rod',
40363 chains: 'chain',
40364 angstroms: 'angstrom',
40365
40366 lt: 'l',
40367 litres: 'litre',
40368 liter: 'litre',
40369 liters: 'litre',
40370 teaspoons: 'teaspoon',
40371 tablespoons: 'tablespoon',
40372 minims: 'minim',
40373 fluiddrams: 'fluiddram',
40374 fluidounces: 'fluidounce',
40375 gills: 'gill',
40376 cups: 'cup',
40377 pints: 'pint',
40378 quarts: 'quart',
40379 gallons: 'gallon',
40380 beerbarrels: 'beerbarrel',
40381 oilbarrels: 'oilbarrel',
40382 hogsheads: 'hogshead',
40383 gtts: 'gtt',
40384
40385 grams: 'gram',
40386 tons: 'ton',
40387 tonnes: 'tonne',
40388 grains: 'grain',
40389 drams: 'dram',
40390 ounces: 'ounce',
40391 poundmasses: 'poundmass',
40392 hundredweights: 'hundredweight',
40393 sticks: 'stick',
40394 lb: 'lbm',
40395 lbs: 'lbm',
40396
40397 kips: 'kip',
40398
40399 acres: 'acre',
40400 hectares: 'hectare',
40401 sqfeet: 'sqft',
40402 sqyard: 'sqyd',
40403 sqmile: 'sqmi',
40404 sqmiles: 'sqmi',
40405
40406 mmhg: 'mmHg',
40407 mmh2o: 'mmH2O',
40408 cmh2o: 'cmH2O',
40409
40410 seconds: 'second',
40411 secs: 'second',
40412 minutes: 'minute',
40413 mins: 'minute',
40414 hours: 'hour',
40415 hr: 'hour',
40416 hrs: 'hour',
40417 days: 'day',
40418 weeks: 'week',
40419 months: 'month',
40420 years: 'year',
40421
40422 hertz: 'hertz',
40423
40424 radians: 'rad',
40425 degree: 'deg',
40426 degrees: 'deg',
40427 gradian: 'grad',
40428 gradians: 'grad',
40429 cycles: 'cycle',
40430 arcsecond: 'arcsec',
40431 arcseconds: 'arcsec',
40432 arcminute: 'arcmin',
40433 arcminutes: 'arcmin',
40434
40435 BTUs: 'BTU',
40436 watts: 'watt',
40437 joules: 'joule',
40438
40439 amperes: 'ampere',
40440 coulombs: 'coulomb',
40441 volts: 'volt',
40442 ohms: 'ohm',
40443 farads: 'farad',
40444 webers: 'weber',
40445 teslas: 'tesla',
40446 electronvolts: 'electronvolt',
40447 moles: 'mole'
40448
40449 };
40450
40451 /**
40452 * Calculate the values for the angle units.
40453 * Value is calculated as number or BigNumber depending on the configuration
40454 * @param {{number: 'number' | 'BigNumber'}} config
40455 */
40456 function calculateAngleValues (config) {
40457 if (config.number === 'BigNumber') {
40458 var pi = constants.pi(type.BigNumber);
40459 UNITS.rad.value = new type.BigNumber(1);
40460 UNITS.deg.value = pi.div(180); // 2 * pi / 360;
40461 UNITS.grad.value = pi.div(200); // 2 * pi / 400;
40462 UNITS.cycle.value = pi.times(2); // 2 * pi
40463 UNITS.arcsec.value = pi.div(648000); // 2 * pi / 360 / 3600
40464 UNITS.arcmin.value = pi.div(10800); // 2 * pi / 360 / 60
40465 }
40466 else { // number
40467 UNITS.rad.value = 1;
40468 UNITS.deg.value = Math.PI / 180; // 2 * pi / 360;
40469 UNITS.grad.value = Math.PI / 200; // 2 * pi / 400;
40470 UNITS.cycle.value = Math.PI * 2; // 2 * pi
40471 UNITS.arcsec.value = Math.PI / 648000; // 2 * pi / 360 / 3600;
40472 UNITS.arcmin.value = Math.PI / 10800; // 2 * pi / 360 / 60;
40473 }
40474 }
40475
40476 // apply the angle values now
40477 calculateAngleValues(config);
40478
40479 // recalculate the values on change of configuration
40480 math.on('config', function (curr, prev) {
40481 if (curr.number !== prev.number) {
40482 calculateAngleValues(curr);
40483 }
40484 });
40485
40486 /**
40487 * 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.
40488 * A user perhaps could issue a command to select a preferred unit system, or use the default (see below).
40489 * 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.
40490 */
40491 var UNIT_SYSTEMS = {
40492 si: {
40493 // Base units
40494 NONE: {unit: UNIT_NONE, prefix: PREFIXES.NONE['']},
40495 LENGTH: {unit: UNITS.m, prefix: PREFIXES.SHORT['']},
40496 MASS: {unit: UNITS.g, prefix: PREFIXES.SHORT['k']},
40497 TIME: {unit: UNITS.s, prefix: PREFIXES.SHORT['']},
40498 CURRENT: {unit: UNITS.A, prefix: PREFIXES.SHORT['']},
40499 TEMPERATURE: {unit: UNITS.K, prefix: PREFIXES.SHORT['']},
40500 LUMINOUS_INTENSITY: {unit: UNITS.cd, prefix: PREFIXES.SHORT['']},
40501 AMOUNT_OF_SUBSTANCE: {unit: UNITS.mol, prefix: PREFIXES.SHORT['']},
40502 ANGLE: {unit: UNITS.rad, prefix: PREFIXES.SHORT['']},
40503 BIT: {unit: UNITS.bit, prefix: PREFIXES.SHORT['']},
40504
40505 // Derived units
40506 FORCE: {unit: UNITS.N, prefix: PREFIXES.SHORT['']},
40507 ENERGY: {unit: UNITS.J, prefix: PREFIXES.SHORT['']},
40508 POWER: {unit: UNITS.W, prefix: PREFIXES.SHORT['']},
40509 PRESSURE: {unit: UNITS.Pa, prefix: PREFIXES.SHORT['']},
40510 ELECTRIC_CHARGE: {unit: UNITS.C, prefix: PREFIXES.SHORT['']},
40511 ELECTRIC_CAPACITANCE: {unit: UNITS.F, prefix: PREFIXES.SHORT['']},
40512 ELECTRIC_POTENTIAL: {unit: UNITS.V, prefix: PREFIXES.SHORT['']},
40513 ELECTRIC_RESISTANCE: {unit: UNITS.ohm, prefix: PREFIXES.SHORT['']},
40514 ELECTRIC_INDUCTANCE: {unit: UNITS.H, prefix: PREFIXES.SHORT['']},
40515 ELECTRIC_CONDUCTANCE: {unit: UNITS.S, prefix: PREFIXES.SHORT['']},
40516 MAGNETIC_FLUX: {unit: UNITS.Wb, prefix: PREFIXES.SHORT['']},
40517 MAGNETIC_FLUX_DENSITY: {unit: UNITS.T, prefix: PREFIXES.SHORT['']},
40518 FREQUENCY: {unit: UNITS.Hz, prefix: PREFIXES.SHORT['']}
40519 }
40520 };
40521
40522 // Clone to create the other unit systems
40523 UNIT_SYSTEMS.cgs = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si));
40524 UNIT_SYSTEMS.cgs.LENGTH = {unit: UNITS.m, prefix: PREFIXES.SHORT['c']};
40525 UNIT_SYSTEMS.cgs.MASS = {unit: UNITS.g, prefix: PREFIXES.SHORT['']};
40526 UNIT_SYSTEMS.cgs.FORCE = {unit: UNITS.dyn, prefix: PREFIXES.SHORT['']};
40527 UNIT_SYSTEMS.cgs.ENERGY = {unit: UNITS.erg, prefix: PREFIXES.NONE['']};
40528 // there are wholly 4 unique cgs systems for electricity and magnetism,
40529 // so let's not worry about it unless somebody complains
40530
40531 UNIT_SYSTEMS.us = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si));
40532 UNIT_SYSTEMS.us.LENGTH = {unit: UNITS.ft, prefix: PREFIXES.NONE['']};
40533 UNIT_SYSTEMS.us.MASS = {unit: UNITS.lbm, prefix: PREFIXES.NONE['']};
40534 UNIT_SYSTEMS.us.TEMPERATURE = {unit: UNITS.degF, prefix: PREFIXES.NONE['']};
40535 UNIT_SYSTEMS.us.FORCE = {unit: UNITS.lbf, prefix: PREFIXES.NONE['']};
40536 UNIT_SYSTEMS.us.ENERGY = {unit: UNITS.BTU, prefix: PREFIXES.BTU['']};
40537 UNIT_SYSTEMS.us.POWER = {unit: UNITS.hp, prefix: PREFIXES.NONE['']};
40538 UNIT_SYSTEMS.us.PRESSURE = {unit: UNITS.psi, prefix: PREFIXES.NONE['']};
40539
40540 // Add additional unit systems here.
40541
40542
40543
40544 // Choose a unit system to seed the auto unit system.
40545 UNIT_SYSTEMS.auto = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si));
40546
40547 // Set the current unit system
40548 var currentUnitSystem = UNIT_SYSTEMS.auto;
40549
40550 /**
40551 * Set a unit system for formatting derived units.
40552 * @param {string} [name] The name of the unit system.
40553 */
40554 Unit.setUnitSystem = function(name) {
40555 if(UNIT_SYSTEMS.hasOwnProperty(name)) {
40556 currentUnitSystem = UNIT_SYSTEMS[name];
40557 }
40558 else {
40559 throw new Error('Unit system ' + name + ' does not exist. Choices are: ' + Object.keys(UNIT_SYSTEMS).join(', '));
40560 }
40561 };
40562
40563 /**
40564 * Return the current unit system.
40565 * @return {string} The current unit system.
40566 */
40567 Unit.getUnitSystem = function() {
40568 for(var key in UNIT_SYSTEMS) {
40569 if(UNIT_SYSTEMS[key] === currentUnitSystem) {
40570 return key;
40571 }
40572 }
40573 };
40574
40575 /**
40576 * Converters to convert from number to an other numeric type like BigNumber
40577 * or Fraction
40578 */
40579 Unit.typeConverters = {
40580 BigNumber: function (x) {
40581 return new type.BigNumber(x + ''); // stringify to prevent constructor error
40582 },
40583
40584 Fraction: function (x) {
40585 return new type.Fraction(x);
40586 },
40587
40588 Complex: function (x) {
40589 return x;
40590 },
40591
40592 number: function (x) {
40593 return x;
40594 }
40595 };
40596
40597 /**
40598 * Retrieve the right convertor function corresponding with the type
40599 * of provided exampleValue.
40600 *
40601 * @param {string} type A string 'number', 'BigNumber', or 'Fraction'
40602 * In case of an unknown type,
40603 * @return {Function}
40604 */
40605 Unit._getNumberConverter = function (type) {
40606 if (!Unit.typeConverters[type]) {
40607 throw new TypeError('Unsupported type "' + type + '"');
40608 }
40609
40610 return Unit.typeConverters[type];
40611 };
40612
40613 // Add dimensions to each built-in unit
40614 for (var key in UNITS) {
40615 var unit = UNITS[key];
40616 unit.dimensions = unit.base.dimensions;
40617 }
40618
40619 // Create aliases
40620 for (var name in ALIASES) {
40621 if(ALIASES.hasOwnProperty(name)) {
40622 var unit = UNITS[ALIASES[name]];
40623 var alias = {};
40624 for(var key in unit) {
40625 if(unit.hasOwnProperty(key)) {
40626 alias[key] = unit[key];
40627 }
40628 }
40629 alias.name = name;
40630 UNITS[name] = alias;
40631 }
40632 }
40633
40634 function assertUnitNameIsValid(name) {
40635 for(var i=0; i<name.length; i++) {
40636 var c = name.charAt(i);
40637
40638 var isValidAlpha = function (p) {
40639 return /^[a-zA-Z]$/.test(p);
40640 };
40641
40642 var isDigit = function (c) {
40643 return (c >= '0' && c <= '9');
40644 }
40645
40646 if(i === 0 && !isValidAlpha(c))
40647 throw new Error('Invalid unit name (must begin with alpha character): "' + name + '"');
40648
40649 if(i > 0 && !( isValidAlpha(c)
40650 || isDigit(c)))
40651 throw new Error('Invalid unit name (only alphanumeric characters are allowed): "' + name + '"');
40652
40653 }
40654 }
40655
40656 /**
40657 * Wrapper around createUnitSingle.
40658 * Example:
40659 * createUnit({
40660 * foo: { },
40661 * bar: {
40662 * definition: 'kg/foo',
40663 * aliases: ['ba', 'barr', 'bars'],
40664 * offset: 200
40665 * },
40666 * baz: '4 bar'
40667 * },
40668 * {
40669 * override: true;
40670 * });
40671 * @param {object} obj Object map. Each key becomes a unit which is defined by its value.
40672 * @param {object} options
40673 */
40674 Unit.createUnit = function(obj, options) {
40675
40676 if(typeof(obj) !== 'object') {
40677 throw new TypeError("createUnit expects first parameter to be of type 'Object'");
40678 }
40679
40680 // Remove all units and aliases we are overriding
40681 if(options && options.override) {
40682 for(var key in obj) {
40683 if(obj.hasOwnProperty(key)) {
40684 Unit.deleteUnit(key);
40685 }
40686 if(obj[key].aliases) {
40687 for(var i=0; i<obj[key].aliases.length; i++) {
40688 Unit.deleteUnit(obj[key].aliases[i]);
40689 }
40690 }
40691 }
40692 }
40693
40694 // TODO: traverse multiple times until all units have been added
40695 var lastUnit;
40696 for(var key in obj) {
40697 if(obj.hasOwnProperty(key)) {
40698 lastUnit = Unit.createUnitSingle(key, obj[key]);
40699 }
40700 }
40701 return lastUnit;
40702 };
40703
40704 /**
40705 * Create a user-defined unit and register it with the Unit type.
40706 * Example:
40707 * createUnitSingle('knot', '0.514444444 m/s')
40708 * createUnitSingle('acre', new Unit(43560, 'ft^2'))
40709 *
40710 * @param {string} name The name of the new unit. Must be unique. Example: 'knot'
40711 * @param {string, Unit} definition Definition of the unit in terms of existing units. For example, '0.514444444 m / s'.
40712 * @param {Object} options (optional) An object containing any of the following properties:
40713 * prefixes {string} "none", "short", "long", "binary_short", or "binary_long". The default is "none".
40714 * aliases {Array} Array of strings. Example: ['knots', 'kt', 'kts']
40715 * 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.
40716 *
40717 * @return {Unit}
40718 */
40719 Unit.createUnitSingle = function(name, obj, options) {
40720
40721 if(typeof(obj) === 'undefined' || obj === null) {
40722 obj = {};
40723 }
40724
40725 if(typeof(name) !== 'string') {
40726 throw new TypeError("createUnitSingle expects first parameter to be of type 'string'");
40727 }
40728
40729 // Check collisions with existing units
40730 if(UNITS.hasOwnProperty(name)) {
40731 throw new Error('Cannot create unit "' + name + '": a unit with that name already exists');
40732 }
40733
40734 // 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.
40735
40736 assertUnitNameIsValid(name);
40737
40738 var defUnit = null; // The Unit from which the new unit will be created.
40739 var aliases = [];
40740 var offset = 0;
40741 var definition;
40742 var prefixes;
40743 if(obj && obj.type === 'Unit') {
40744 defUnit = obj.clone();
40745 }
40746 else if(typeof(obj) === 'string') {
40747 if(obj !== '') {
40748 definition = obj;
40749 }
40750 }
40751 else if(typeof(obj) === 'object') {
40752 definition = obj.definition;
40753 prefixes = obj.prefixes;
40754 offset = obj.offset;
40755 if (obj.aliases) {
40756 aliases = obj.aliases.valueOf(); // aliases could be a Matrix, so convert to Array
40757 }
40758 }
40759 else {
40760 throw new TypeError('Cannot create unit "' + name + '" from "' + obj.toString() + '": expecting "string" or "Unit" or "Object"');
40761 }
40762
40763 if(aliases) {
40764 for (var i=0; i<aliases.length; i++) {
40765 if(UNITS.hasOwnProperty(aliases[i])) {
40766 throw new Error('Cannot create alias "' + aliases[i] + '": a unit with that name already exists');
40767 }
40768 }
40769 }
40770
40771 if(definition && typeof(definition) === 'string' && !defUnit) {
40772 try {
40773 defUnit = Unit.parse(definition, {allowNoUnits: true});
40774 }
40775 catch (ex) {
40776 ex.message = 'Could not create unit "' + name + '" from "' + definition + '": ' + ex.message;
40777 throw(ex);
40778 }
40779 }
40780 else if(definition && definition.type === 'Unit') {
40781 defUnit = definition.clone();
40782 }
40783
40784 aliases = aliases || [];
40785 offset = offset || 0;
40786 if(prefixes && prefixes.toUpperCase)
40787 prefixes = PREFIXES[prefixes.toUpperCase()] || PREFIXES.NONE;
40788 else
40789 prefixes = PREFIXES.NONE;
40790
40791
40792 // If defUnit is null, it is because the user did not
40793 // specify a defintion. So create a new base dimension.
40794 var newUnit = {};
40795 if(!defUnit) {
40796 // Add a new base dimension
40797 var baseName = name + "_STUFF"; // foo --> foo_STUFF, or the essence of foo
40798 if(BASE_DIMENSIONS.indexOf(baseName) >= 0) {
40799 throw new Error('Cannot create new base unit "' + name + '": a base unit with that name already exists (and cannot be overridden)');
40800 }
40801 BASE_DIMENSIONS.push(baseName);
40802
40803 // Push 0 onto existing base units
40804 for(var b in BASE_UNITS) {
40805 if(BASE_UNITS.hasOwnProperty(b)) {
40806 BASE_UNITS[b].dimensions[BASE_DIMENSIONS.length-1] = 0;
40807 }
40808 }
40809
40810 // Add the new base unit
40811 var newBaseUnit = { dimensions: [] };
40812 for(var i=0; i<BASE_DIMENSIONS.length; i++) {
40813 newBaseUnit.dimensions[i] = 0;
40814 }
40815 newBaseUnit.dimensions[BASE_DIMENSIONS.length-1] = 1;
40816 newBaseUnit.key = baseName;
40817 BASE_UNITS[baseName] = newBaseUnit;
40818
40819 newUnit = {
40820 name: name,
40821 value: 1,
40822 dimensions: BASE_UNITS[baseName].dimensions.slice(0),
40823 prefixes: prefixes,
40824 offset: offset,
40825 base: baseName
40826 };
40827
40828 currentUnitSystem[baseName] = {
40829 unit: newUnit,
40830 prefix: PREFIXES.NONE['']
40831 };
40832
40833 }
40834 else {
40835
40836 newUnit = {
40837 name: name,
40838 value: defUnit.value,
40839 dimensions: defUnit.dimensions.slice(0),
40840 prefixes: prefixes,
40841 offset: offset,
40842 };
40843
40844 // Create a new base if no matching base exists
40845 var anyMatch = false;
40846 for(var i in BASE_UNITS) {
40847 if(BASE_UNITS.hasOwnProperty(i)) {
40848 var match = true;
40849 for(var j=0; j<BASE_DIMENSIONS.length; j++) {
40850 if (Math.abs((newUnit.dimensions[j] || 0) - (BASE_UNITS[i].dimensions[j] || 0)) > 1e-12) {
40851 match = false;
40852 break;
40853 }
40854 }
40855 if(match) {
40856 anyMatch = true;
40857 break;
40858 }
40859 }
40860 }
40861 if(!anyMatch) {
40862 var baseName = name + "_STUFF"; // foo --> foo_STUFF, or the essence of foo
40863 // Add the new base unit
40864 var newBaseUnit = { dimensions: defUnit.dimensions.slice(0) };
40865 newBaseUnit.key = baseName;
40866 BASE_UNITS[baseName] = newBaseUnit;
40867
40868 currentUnitSystem[baseName] = {
40869 unit: newUnit,
40870 prefix: PREFIXES.NONE['']
40871 };
40872
40873 newUnit.base = baseName;
40874 }
40875 }
40876
40877 Unit.UNITS[name] = newUnit;
40878
40879 for (var i=0; i<aliases.length; i++) {
40880 var aliasName = aliases[i];
40881 var alias = {};
40882 for(var key in newUnit) {
40883 if(newUnit.hasOwnProperty(key)) {
40884 alias[key] = newUnit[key];
40885 }
40886 }
40887 alias.name = aliasName;
40888 Unit.UNITS[aliasName] = alias;
40889 }
40890
40891 return new Unit(null, name);
40892 };
40893
40894 Unit.deleteUnit = function(name) {
40895 delete Unit.UNITS[name];
40896 };
40897
40898 // expose arrays with prefixes, dimensions, units, systems
40899 Unit.PREFIXES = PREFIXES;
40900 Unit.BASE_DIMENSIONS = BASE_DIMENSIONS;
40901 Unit.BASE_UNITS = BASE_UNITS;
40902 Unit.UNIT_SYSTEMS = UNIT_SYSTEMS;
40903 Unit.UNITS = UNITS;
40904
40905 return Unit;
40906}
40907
40908exports.name = 'Unit';
40909exports.path = 'type';
40910exports.factory = factory;
40911exports.math = true; // request access to the math namespace
40912
40913
40914/***/ }),
40915/* 189 */
40916/***/ (function(module, exports, __webpack_require__) {
40917
40918"use strict";
40919
40920
40921var deepMap = __webpack_require__(1);
40922
40923function factory (type, config, load, typed) {
40924 /**
40925 * Create a unit. Depending on the passed arguments, the function
40926 * will create and return a new math.type.Unit object.
40927 * When a matrix is provided, all elements will be converted to units.
40928 *
40929 * Syntax:
40930 *
40931 * math.unit(unit : string)
40932 * math.unit(value : number, unit : string)
40933 *
40934 * Examples:
40935 *
40936 * var a = math.unit(5, 'cm'); // returns Unit 50 mm
40937 * var b = math.unit('23 kg'); // returns Unit 23 kg
40938 * a.to('m'); // returns Unit 0.05 m
40939 *
40940 * See also:
40941 *
40942 * bignumber, boolean, complex, index, matrix, number, string, createUnit
40943 *
40944 * @param {* | Array | Matrix} args A number and unit.
40945 * @return {Unit | Array | Matrix} The created unit
40946 */
40947
40948 var unit = typed('unit', {
40949 'Unit': function (x) {
40950 return x.clone();
40951 },
40952
40953 'string': function (x) {
40954 if (type.Unit.isValuelessUnit(x)) {
40955 return new type.Unit(null, x); // a pure unit
40956 }
40957
40958 return type.Unit.parse(x); // a unit with value, like '5cm'
40959 },
40960
40961 'number | BigNumber | Fraction | Complex, string': function (value, unit) {
40962 return new type.Unit(value, unit);
40963 },
40964
40965 'Array | Matrix': function (x) {
40966 return deepMap(x, unit);
40967 }
40968 });
40969
40970 unit.toTex = {
40971 1: '\\left(${args[0]}\\right)',
40972 2: '\\left(\\left(${args[0]}\\right)${args[1]}\\right)'
40973 };
40974
40975 return unit;
40976}
40977
40978exports.name = 'unit';
40979exports.factory = factory;
40980
40981
40982/***/ }),
40983/* 190 */
40984/***/ (function(module, exports, __webpack_require__) {
40985
40986"use strict";
40987
40988
40989var deepMap = __webpack_require__(1);
40990
40991function factory (type, config, load, typed) {
40992 /**
40993 * Create a user-defined unit and register it with the Unit type.
40994 *
40995 * Syntax:
40996 *
40997 * math.createUnit({
40998 * baseUnit1: {
40999 * aliases: [string, ...]
41000 * prefixes: object
41001 * },
41002 * unit2: {
41003 * definition: string,
41004 * aliases: [string, ...]
41005 * prefixes: object,
41006 * offset: number
41007 * },
41008 * unit3: string // Shortcut
41009 * })
41010 *
41011 * // Another shortcut:
41012 * math.createUnit(string, unit : string, [object])
41013 *
41014 * Examples:
41015 *
41016 * math.createUnit('foo');
41017 * math.createUnit('knot', {definition: '0.514444444 m/s', aliases: ['knots', 'kt', 'kts']});
41018 * math.createUnit('mph', '1 mile/hour');
41019 *
41020 * @param {string} name The name of the new unit. Must be unique. Example: 'knot'
41021 * @param {string, Unit} definition Definition of the unit in terms of existing units. For example, '0.514444444 m / s'.
41022 * @param {Object} options (optional) An object containing any of the following properties:
41023 * prefixes {string} "none", "short", "long", "binary_short", or "binary_long". The default is "none".
41024 * aliases {Array} Array of strings. Example: ['knots', 'kt', 'kts']
41025 * offset {Numeric} An offset to apply when converting from the unit. For example, the offset for celsius is 273.15. Default is 0.
41026 *
41027 * See also:
41028 *
41029 * unit
41030 *
41031 * @return {Unit} The new unit
41032 */
41033 var createUnit = typed('createUnit', {
41034
41035 // 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.
41036 'Object, Object': function(obj, options) {
41037 return type.Unit.createUnit(obj, options);
41038 },
41039
41040 // Same as above but without the options.
41041 'Object': function(obj) {
41042 return type.Unit.createUnit(obj, {});
41043 },
41044
41045 // Shortcut method for creating one unit.
41046 'string, Unit | string | Object, Object': function (name, def, options) {
41047 var obj = {};
41048 obj[name] = def;
41049 return type.Unit.createUnit(obj, options);
41050 },
41051
41052 // Same as above but without the options.
41053 'string, Unit | string | Object': function (name, def) {
41054 var obj = {};
41055 obj[name] = def;
41056 return type.Unit.createUnit(obj, {});
41057 },
41058
41059 // Without a definition, creates a base unit.
41060 'string': function (name) {
41061 var obj = {};
41062 obj[name] = {};
41063 return type.Unit.createUnit(obj, {});
41064 },
41065 });
41066
41067 return createUnit;
41068}
41069
41070exports.name = 'createUnit';
41071exports.factory = factory;
41072
41073
41074/***/ }),
41075/* 191 */
41076/***/ (function(module, exports, __webpack_require__) {
41077
41078"use strict";
41079
41080
41081var deepMap = __webpack_require__(1);
41082
41083function factory (type, config, load, typed) {
41084
41085 /**
41086 * Split a unit in an array of units whose sum is equal to the original unit.
41087 *
41088 * Syntax:
41089 *
41090 * splitUnit(unit: Unit, parts: Array.<Unit>)
41091 *
41092 * Example:
41093 *
41094 * math.splitUnit(new Unit(1, 'm'), ['feet', 'inch']);
41095 * // [ 3 feet, 3.3700787401575 inch ]
41096 *
41097 * See also:
41098 *
41099 * unit
41100 *
41101 * @param {Array} [parts] An array of strings or valueless units.
41102 * @return {Array} An array of units.
41103 */
41104 var splitUnit = typed('splitUnit', {
41105 'Unit, Array': function(unit, parts) {
41106 return unit.splitUnit(parts);
41107 }
41108 });
41109
41110 return splitUnit;
41111
41112}
41113
41114exports.name = 'splitUnit';
41115exports.factory = factory;
41116
41117
41118/***/ }),
41119/* 192 */
41120/***/ (function(module, exports, __webpack_require__) {
41121
41122var lazy = __webpack_require__(5).lazy;
41123
41124
41125function factory (type, config, load, typed, math) {
41126
41127 // helper function to create a unit with a fixed prefix
41128 function fixedUnit(str) {
41129 var unit = type.Unit.parse(str);
41130 unit.fixPrefix = true;
41131 return unit;
41132 }
41133
41134 // Source: http://www.wikiwand.com/en/Physical_constant
41135
41136 // Universal constants
41137 setLazyConstant(math, 'speedOfLight', function () {return fixedUnit('299792458 m s^-1')});
41138 setLazyConstant(math, 'gravitationConstant', function () {return fixedUnit('6.6738480e-11 m^3 kg^-1 s^-2')});
41139 setLazyConstant(math, 'planckConstant', function () {return fixedUnit('6.626069311e-34 J s')});
41140 setLazyConstant(math, 'reducedPlanckConstant',function () {return fixedUnit('1.05457172647e-34 J s')});
41141
41142 // Electromagnetic constants
41143 setLazyConstant(math, 'magneticConstant', function () {return fixedUnit('1.2566370614e-6 N A^-2')});
41144 setLazyConstant(math, 'electricConstant', function () {return fixedUnit('8.854187817e-12 F m^-1')});
41145 setLazyConstant(math, 'vacuumImpedance', function () {return fixedUnit('376.730313461 ohm')});
41146 setLazyConstant(math, 'coulomb', function () {return fixedUnit('8.9875517873681764e9 N m^2 C^-2')});
41147 setLazyConstant(math, 'elementaryCharge', function () {return fixedUnit('1.60217656535e-19 C')});
41148 setLazyConstant(math, 'bohrMagneton', function () {return fixedUnit('9.2740096820e-24 J T^-1')});
41149 setLazyConstant(math, 'conductanceQuantum', function () {return fixedUnit('7.748091734625e-5 S')});
41150 setLazyConstant(math, 'inverseConductanceQuantum', function () {return fixedUnit('12906.403721742 ohm')});
41151 setLazyConstant(math, 'magneticFluxQuantum', function () {return fixedUnit('2.06783375846e-15 Wb')});
41152 setLazyConstant(math, 'nuclearMagneton', function () {return fixedUnit('5.0507835311e-27 J T^-1')});
41153 setLazyConstant(math, 'klitzing', function () {return fixedUnit('25812.807443484 ohm')});
41154 //setLazyConstant(math, 'josephson', function () {return fixedUnit('4.8359787011e-14 Hz V^-1')}); // TODO: support for Hz needed
41155
41156 // Atomic and nuclear constants
41157 setLazyConstant(math, 'bohrRadius', function () {return fixedUnit('5.291772109217e-11 m')});
41158 setLazyConstant(math, 'classicalElectronRadius', function () {return fixedUnit('2.817940326727e-15 m')});
41159 setLazyConstant(math, 'electronMass', function () {return fixedUnit('9.1093829140e-31 kg')});
41160 setLazyConstant(math, 'fermiCoupling', function () {return fixedUnit('1.1663645e-5 GeV^-2')});
41161 setLazyConstant(math, 'fineStructure', function () {return 7.297352569824e-3});
41162 setLazyConstant(math, 'hartreeEnergy', function () {return fixedUnit('4.3597443419e-18 J')});
41163 setLazyConstant(math, 'protonMass', function () {return fixedUnit('1.67262177774e-27 kg')});
41164 setLazyConstant(math, 'deuteronMass', function () {return fixedUnit('3.3435830926e-27 kg')});
41165 setLazyConstant(math, 'neutronMass', function () {return fixedUnit('1.6749271613e-27 kg')});
41166 setLazyConstant(math, 'quantumOfCirculation', function () {return fixedUnit('3.636947552024e-4 m^2 s^-1')});
41167 setLazyConstant(math, 'rydberg', function () {return fixedUnit('10973731.56853955 m^-1')});
41168 setLazyConstant(math, 'thomsonCrossSection', function () {return fixedUnit('6.65245873413e-29 m^2')});
41169 setLazyConstant(math, 'weakMixingAngle', function () {return 0.222321});
41170 setLazyConstant(math, 'efimovFactor', function () {return 22.7});
41171
41172 // Physico-chemical constants
41173 setLazyConstant(math, 'atomicMass', function () {return fixedUnit('1.66053892173e-27 kg')});
41174 setLazyConstant(math, 'avogadro', function () {return fixedUnit('6.0221412927e23 mol^-1')});
41175 setLazyConstant(math, 'boltzmann', function () {return fixedUnit('1.380648813e-23 J K^-1')});
41176 setLazyConstant(math, 'faraday', function () {return fixedUnit('96485.336521 C mol^-1')});
41177 setLazyConstant(math, 'firstRadiation', function () {return fixedUnit('3.7417715317e-16 W m^2')});
41178 // setLazyConstant(math, 'spectralRadiance', function () {return fixedUnit('1.19104286953e-16 W m^2 sr^-1')}); // TODO spectralRadiance
41179 setLazyConstant(math, 'loschmidt', function () {return fixedUnit('2.686780524e25 m^-3')});
41180 setLazyConstant(math, 'gasConstant', function () {return fixedUnit('8.314462175 J K^-1 mol^-1')});
41181 setLazyConstant(math, 'molarPlanckConstant', function () {return fixedUnit('3.990312717628e-10 J s mol^-1')});
41182 setLazyConstant(math, 'molarVolume', function () {return fixedUnit('2.241396820e-10 m^3 mol^-1')});
41183 setLazyConstant(math, 'sackurTetrode', function () {return -1.164870823});
41184 setLazyConstant(math, 'secondRadiation', function () {return fixedUnit('1.438777013e-2 m K')});
41185 setLazyConstant(math, 'stefanBoltzmann', function () {return fixedUnit('5.67037321e-8 W m^-2 K^-4')});
41186 setLazyConstant(math, 'wienDisplacement', function () {return fixedUnit('2.897772126e-3 m K')});
41187
41188 // Adopted values
41189 setLazyConstant(math, 'molarMass', function () {return fixedUnit('1e-3 kg mol^-1')});
41190 setLazyConstant(math, 'molarMassC12', function () {return fixedUnit('1.2e-2 kg mol^-1')});
41191 setLazyConstant(math, 'gravity', function () {return fixedUnit('9.80665 m s^-2')});
41192 // atm is defined in Unit.js
41193
41194 // Natural units
41195 setLazyConstant(math, 'planckLength', function () {return fixedUnit('1.61619997e-35 m')});
41196 setLazyConstant(math, 'planckMass', function () {return fixedUnit('2.1765113e-8 kg')});
41197 setLazyConstant(math, 'planckTime', function () {return fixedUnit('5.3910632e-44 s')});
41198 setLazyConstant(math, 'planckCharge', function () {return fixedUnit('1.87554595641e-18 C')});
41199 setLazyConstant(math, 'planckTemperature', function () {return fixedUnit('1.41683385e+32 K')});
41200
41201}
41202
41203// create a lazy constant in both math and mathWithTransform
41204function setLazyConstant (math, name, resolver) {
41205 lazy(math, name, resolver);
41206 lazy(math.expression.mathWithTransform, name, resolver);
41207}
41208
41209exports.factory = factory;
41210exports.lazy = false; // no lazy loading of constants, the constants themselves are lazy when needed
41211exports.math = true; // request access to the math namespace
41212
41213
41214/***/ }),
41215/* 193 */
41216/***/ (function(module, exports, __webpack_require__) {
41217
41218"use strict";
41219
41220
41221var object = __webpack_require__(5);
41222var bigConstants = __webpack_require__(96);
41223
41224function factory (type, config, load, typed, math) {
41225 // listen for changed in the configuration, automatically reload
41226 // constants when needed
41227 math.on('config', function (curr, prev) {
41228 if (curr.number !== prev.number) {
41229 factory(type, config, load, typed, math);
41230 }
41231 });
41232
41233 setConstant(math, 'true', true);
41234 setConstant(math, 'false', false);
41235 setConstant(math, 'null', null);
41236 setConstant(math, 'uninitialized', __webpack_require__(2).UNINITIALIZED);
41237
41238 if (config.number === 'BigNumber') {
41239 setConstant(math, 'Infinity', new type.BigNumber(Infinity));
41240 setConstant(math, 'NaN', new type.BigNumber(NaN));
41241
41242 setLazyConstant(math, 'pi', function () {return bigConstants.pi(type.BigNumber)});
41243 setLazyConstant(math, 'tau', function () {return bigConstants.tau(type.BigNumber)});
41244 setLazyConstant(math, 'e', function () {return bigConstants.e(type.BigNumber)});
41245 setLazyConstant(math, 'phi', function () {return bigConstants.phi(type.BigNumber)}); // golden ratio, (1+sqrt(5))/2
41246
41247 // uppercase constants (for compatibility with built-in Math)
41248 setLazyConstant(math, 'E', function () {return math.e;});
41249 setLazyConstant(math, 'LN2', function () {return new type.BigNumber(2).ln();});
41250 setLazyConstant(math, 'LN10', function () {return new type.BigNumber(10).ln()});
41251 setLazyConstant(math, 'LOG2E', function () {return new type.BigNumber(1).div(new type.BigNumber(2).ln());});
41252 setLazyConstant(math, 'LOG10E', function () {return new type.BigNumber(1).div(new type.BigNumber(10).ln())});
41253 setLazyConstant(math, 'PI', function () {return math.pi});
41254 setLazyConstant(math, 'SQRT1_2', function () {return new type.BigNumber('0.5').sqrt()});
41255 setLazyConstant(math, 'SQRT2', function () {return new type.BigNumber(2).sqrt()});
41256 }
41257 else {
41258 setConstant(math, 'Infinity', Infinity);
41259 setConstant(math, 'NaN', NaN);
41260
41261 setConstant(math, 'pi', Math.PI);
41262 setConstant(math, 'tau', Math.PI * 2);
41263 setConstant(math, 'e', Math.E);
41264 setConstant(math, 'phi', 1.61803398874989484820458683436563811772030917980576286213545); // golden ratio, (1+sqrt(5))/2
41265
41266 // uppercase constants (for compatibility with built-in Math)
41267 setConstant(math, 'E', math.e);
41268 setConstant(math, 'LN2', Math.LN2);
41269 setConstant(math, 'LN10', Math.LN10);
41270 setConstant(math, 'LOG2E', Math.LOG2E);
41271 setConstant(math, 'LOG10E', Math.LOG10E);
41272 setConstant(math, 'PI', math.pi);
41273 setConstant(math, 'SQRT1_2', Math.SQRT1_2);
41274 setConstant(math, 'SQRT2', Math.SQRT2);
41275 }
41276
41277 // complex i
41278 setConstant(math, 'i', type.Complex.I);
41279
41280 // meta information
41281 setConstant(math, 'version', __webpack_require__(194));
41282}
41283
41284// create a constant in both math and mathWithTransform
41285function setConstant(math, name, value) {
41286 math[name] = value;
41287 math.expression.mathWithTransform[name] = value;
41288}
41289
41290// create a lazy constant in both math and mathWithTransform
41291function setLazyConstant (math, name, resolver) {
41292 object.lazy(math, name, resolver);
41293 object.lazy(math.expression.mathWithTransform, name, resolver);
41294}
41295
41296exports.factory = factory;
41297exports.lazy = false; // no lazy loading of constants, the constants themselves are lazy when needed
41298exports.math = true; // request access to the math namespace
41299
41300/***/ }),
41301/* 194 */
41302/***/ (function(module, exports) {
41303
41304module.exports = '3.20.2';
41305// Note: This file is automatically generated when building math.js.
41306// Changes made in this file will be overwritten.
41307
41308
41309/***/ }),
41310/* 195 */
41311/***/ (function(module, exports, __webpack_require__) {
41312
41313module.exports = [
41314 // Note that the docs folder is called "embeddedDocs" and not "docs" to prevent issues
41315 // with yarn autoclean. See https://github.com/josdejong/mathjs/issues/969
41316 __webpack_require__(100),
41317 __webpack_require__(388),
41318 __webpack_require__(393),
41319 __webpack_require__(395),
41320
41321 __webpack_require__(406),
41322 __webpack_require__(41),
41323 __webpack_require__(113)
41324];
41325
41326
41327/***/ }),
41328/* 196 */
41329/***/ (function(module, exports) {
41330
41331module.exports = {
41332 'name': 'bignumber',
41333 'category': 'Construction',
41334 'syntax': [
41335 'bignumber(x)'
41336 ],
41337 'description':
41338 'Create a big number from a number or string.',
41339 'examples': [
41340 '0.1 + 0.2',
41341 'bignumber(0.1) + bignumber(0.2)',
41342 'bignumber("7.2")',
41343 'bignumber("7.2e500")',
41344 'bignumber([0.1, 0.2, 0.3])'
41345 ],
41346 'seealso': [
41347 'boolean', 'complex', 'fraction', 'index', 'matrix', 'string', 'unit'
41348 ]
41349};
41350
41351
41352/***/ }),
41353/* 197 */
41354/***/ (function(module, exports) {
41355
41356module.exports = {
41357 'name': 'boolean',
41358 'category': 'Construction',
41359 'syntax': [
41360 'x',
41361 'boolean(x)'
41362 ],
41363 'description':
41364 'Convert a string or number into a boolean.',
41365 'examples': [
41366 'boolean(0)',
41367 'boolean(1)',
41368 'boolean(3)',
41369 'boolean("true")',
41370 'boolean("false")',
41371 'boolean([1, 0, 1, 1])'
41372 ],
41373 'seealso': [
41374 'bignumber', 'complex', 'index', 'matrix', 'number', 'string', 'unit'
41375 ]
41376};
41377
41378
41379/***/ }),
41380/* 198 */
41381/***/ (function(module, exports) {
41382
41383module.exports = {
41384 'name': 'complex',
41385 'category': 'Construction',
41386 'syntax': [
41387 'complex()',
41388 'complex(re, im)',
41389 'complex(string)'
41390 ],
41391 'description':
41392 'Create a complex number.',
41393 'examples': [
41394 'complex()',
41395 'complex(2, 3)',
41396 'complex("7 - 2i")'
41397 ],
41398 'seealso': [
41399 'bignumber', 'boolean', 'index', 'matrix', 'number', 'string', 'unit'
41400 ]
41401};
41402
41403
41404/***/ }),
41405/* 199 */
41406/***/ (function(module, exports) {
41407
41408module.exports = {
41409 'name': 'createUnit',
41410 'category': 'Construction',
41411 'syntax': [
41412 'createUnit(definitions)',
41413 'createUnit(name, definition)'
41414 ],
41415 'description':
41416 'Create a user-defined unit and register it with the Unit type.',
41417 'examples': [
41418 'createUnit("foo")',
41419 'createUnit("knot", {definition: "0.514444444 m/s", aliases: ["knots", "kt", "kts"]})',
41420 'createUnit("mph", "1 mile/hour")'
41421 ],
41422 'seealso': [
41423 'unit', 'splitUnit'
41424 ]
41425};
41426
41427
41428/***/ }),
41429/* 200 */
41430/***/ (function(module, exports) {
41431
41432module.exports = {
41433 'name': 'fraction',
41434 'category': 'Construction',
41435 'syntax': [
41436 'fraction(num)',
41437 'fraction(num,den)'
41438 ],
41439 'description':
41440 'Create a fraction from a number or from a numerator and denominator.',
41441 'examples': [
41442 'fraction(0.125)',
41443 'fraction(1, 3) + fraction(2, 5)'
41444 ],
41445 'seealso': [
41446 'bignumber', 'boolean', 'complex', 'index', 'matrix', 'string', 'unit'
41447 ]
41448};
41449
41450
41451/***/ }),
41452/* 201 */
41453/***/ (function(module, exports) {
41454
41455module.exports = {
41456 'name': 'index',
41457 'category': 'Construction',
41458 'syntax': [
41459 '[start]',
41460 '[start:end]',
41461 '[start:step:end]',
41462 '[start1, start 2, ...]',
41463 '[start1:end1, start2:end2, ...]',
41464 '[start1:step1:end1, start2:step2:end2, ...]'
41465 ],
41466 'description':
41467 'Create an index to get or replace a subset of a matrix',
41468 'examples': [
41469 '[]',
41470 '[1, 2, 3]',
41471 'A = [1, 2, 3; 4, 5, 6]',
41472 'A[1, :]',
41473 'A[1, 2] = 50',
41474 'A[0:2, 0:2] = ones(2, 2)'
41475 ],
41476 'seealso': [
41477 'bignumber', 'boolean', 'complex', 'matrix,', 'number', 'range', 'string', 'unit'
41478 ]
41479};
41480
41481
41482/***/ }),
41483/* 202 */
41484/***/ (function(module, exports) {
41485
41486module.exports = {
41487 'name': 'matrix',
41488 'category': 'Construction',
41489 'syntax': [
41490 '[]',
41491 '[a1, b1, ...; a2, b2, ...]',
41492 'matrix()',
41493 'matrix("dense")',
41494 'matrix([...])'
41495 ],
41496 'description':
41497 'Create a matrix.',
41498 'examples': [
41499 '[]',
41500 '[1, 2, 3]',
41501 '[1, 2, 3; 4, 5, 6]',
41502 'matrix()',
41503 'matrix([3, 4])',
41504 'matrix([3, 4; 5, 6], "sparse")',
41505 'matrix([3, 4; 5, 6], "sparse", "number")'
41506 ],
41507 'seealso': [
41508 'bignumber', 'boolean', 'complex', 'index', 'number', 'string', 'unit', 'sparse'
41509 ]
41510};
41511
41512
41513/***/ }),
41514/* 203 */
41515/***/ (function(module, exports) {
41516
41517module.exports = {
41518 'name': 'number',
41519 'category': 'Construction',
41520 'syntax': [
41521 'x',
41522 'number(x)',
41523 'number(unit, valuelessUnit)'
41524 ],
41525 'description':
41526 'Create a number or convert a string or boolean into a number.',
41527 'examples': [
41528 '2',
41529 '2e3',
41530 '4.05',
41531 'number(2)',
41532 'number("7.2")',
41533 'number(true)',
41534 'number([true, false, true, true])',
41535 'number(unit("52cm"), "m")'
41536 ],
41537 'seealso': [
41538 'bignumber', 'boolean', 'complex', 'fraction', 'index', 'matrix', 'string', 'unit'
41539 ]
41540};
41541
41542
41543/***/ }),
41544/* 204 */
41545/***/ (function(module, exports) {
41546
41547module.exports = {
41548 'name': 'sparse',
41549 'category': 'Construction',
41550 'syntax': [
41551 'sparse()',
41552 'sparse([a1, b1, ...; a1, b2, ...])',
41553 'sparse([a1, b1, ...; a1, b2, ...], "number")'
41554 ],
41555 'description':
41556 'Create a sparse matrix.',
41557 'examples': [
41558 'sparse()',
41559 'sparse([3, 4; 5, 6])',
41560 'sparse([3, 0; 5, 0], "number")'
41561 ],
41562 'seealso': [
41563 'bignumber', 'boolean', 'complex', 'index', 'number', 'string', 'unit', 'matrix'
41564 ]
41565};
41566
41567
41568/***/ }),
41569/* 205 */
41570/***/ (function(module, exports) {
41571
41572module.exports = {
41573 'name': 'splitUnit',
41574 'category': 'Construction',
41575 'syntax': [
41576 'splitUnit(unit: Unit, parts: Unit[])'
41577 ],
41578 'description':
41579 'Split a unit in an array of units whose sum is equal to the original unit.',
41580 'examples': [
41581 'splitUnit(1 m, ["feet", "inch"])'
41582 ],
41583 'seealso': [
41584 'unit', 'createUnit'
41585 ]
41586};
41587
41588
41589/***/ }),
41590/* 206 */
41591/***/ (function(module, exports) {
41592
41593module.exports = {
41594 'name': 'string',
41595 'category': 'Construction',
41596 'syntax': [
41597 '"text"',
41598 'string(x)'
41599 ],
41600 'description':
41601 'Create a string or convert a value to a string',
41602 'examples': [
41603 '"Hello World!"',
41604 'string(4.2)',
41605 'string(3 + 2i)'
41606 ],
41607 'seealso': [
41608 'bignumber', 'boolean', 'complex', 'index', 'matrix', 'number', 'unit'
41609 ]
41610};
41611
41612
41613/***/ }),
41614/* 207 */
41615/***/ (function(module, exports) {
41616
41617module.exports = {
41618 'name': 'unit',
41619 'category': 'Construction',
41620 'syntax': [
41621 'value unit',
41622 'unit(value, unit)',
41623 'unit(string)'
41624 ],
41625 'description':
41626 'Create a unit.',
41627 'examples': [
41628 '5.5 mm',
41629 '3 inch',
41630 'unit(7.1, "kilogram")',
41631 'unit("23 deg")'
41632 ],
41633 'seealso': [
41634 'bignumber', 'boolean', 'complex', 'index', 'matrix', 'number', 'string'
41635 ]
41636};
41637
41638
41639/***/ }),
41640/* 208 */
41641/***/ (function(module, exports) {
41642
41643module.exports = {
41644 'name': 'false',
41645 'category': 'Constants',
41646 'syntax': [
41647 'false'
41648 ],
41649 'description': 'Boolean value false',
41650 'examples': [
41651 'false'
41652 ],
41653 'seealso': ['true']
41654};
41655
41656
41657/***/ }),
41658/* 209 */
41659/***/ (function(module, exports) {
41660
41661module.exports = {
41662 'name': 'i',
41663 'category': 'Constants',
41664 'syntax': [
41665 'i'
41666 ],
41667 '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.',
41668 'examples': [
41669 'i',
41670 'i * i',
41671 'sqrt(-1)'
41672 ],
41673 'seealso': []
41674};
41675
41676
41677/***/ }),
41678/* 210 */
41679/***/ (function(module, exports) {
41680
41681module.exports = {
41682 'name': 'Infinity',
41683 'category': 'Constants',
41684 'syntax': [
41685 'Infinity'
41686 ],
41687 'description': 'Infinity, a number which is larger than the maximum number that can be handled by a floating point number.',
41688 'examples': [
41689 'Infinity',
41690 '1 / 0'
41691 ],
41692 'seealso': []
41693};
41694
41695
41696/***/ }),
41697/* 211 */
41698/***/ (function(module, exports) {
41699
41700module.exports = {
41701 'name': 'LN2',
41702 'category': 'Constants',
41703 'syntax': [
41704 'LN2'
41705 ],
41706 'description': 'Returns the natural logarithm of 2, approximately equal to 0.693',
41707 'examples': [
41708 'LN2',
41709 'log(2)'
41710 ],
41711 'seealso': []
41712};
41713
41714
41715/***/ }),
41716/* 212 */
41717/***/ (function(module, exports) {
41718
41719module.exports = {
41720 'name': 'LN10',
41721 'category': 'Constants',
41722 'syntax': [
41723 'LN10'
41724 ],
41725 'description': 'Returns the natural logarithm of 10, approximately equal to 2.302',
41726 'examples': [
41727 'LN10',
41728 'log(10)'
41729 ],
41730 'seealso': []
41731};
41732
41733
41734/***/ }),
41735/* 213 */
41736/***/ (function(module, exports) {
41737
41738module.exports = {
41739 'name': 'LOG2E',
41740 'category': 'Constants',
41741 'syntax': [
41742 'LOG2E'
41743 ],
41744 'description': 'Returns the base-2 logarithm of E, approximately equal to 1.442',
41745 'examples': [
41746 'LOG2E',
41747 'log(e, 2)'
41748 ],
41749 'seealso': []
41750};
41751
41752
41753/***/ }),
41754/* 214 */
41755/***/ (function(module, exports) {
41756
41757module.exports = {
41758 'name': 'LOG10E',
41759 'category': 'Constants',
41760 'syntax': [
41761 'LOG10E'
41762 ],
41763 'description': 'Returns the base-10 logarithm of E, approximately equal to 0.434',
41764 'examples': [
41765 'LOG10E',
41766 'log(e, 10)'
41767 ],
41768 'seealso': []
41769};
41770
41771
41772/***/ }),
41773/* 215 */
41774/***/ (function(module, exports) {
41775
41776module.exports = {
41777 'name': 'NaN',
41778 'category': 'Constants',
41779 'syntax': [
41780 'NaN'
41781 ],
41782 'description': 'Not a number',
41783 'examples': [
41784 'NaN',
41785 '0 / 0'
41786 ],
41787 'seealso': []
41788};
41789
41790
41791/***/ }),
41792/* 216 */
41793/***/ (function(module, exports) {
41794
41795module.exports = {
41796 'name': 'null',
41797 'category': 'Constants',
41798 'syntax': [
41799 'null'
41800 ],
41801 'description': 'Value null',
41802 'examples': [
41803 'null'
41804 ],
41805 'seealso': ['true', 'false']
41806};
41807
41808
41809/***/ }),
41810/* 217 */
41811/***/ (function(module, exports) {
41812
41813module.exports = {
41814 'name': 'phi',
41815 'category': 'Constants',
41816 'syntax': [
41817 'phi'
41818 ],
41819 '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...',
41820 'examples': [
41821 'phi'
41822 ],
41823 'seealso': []
41824};
41825
41826
41827/***/ }),
41828/* 218 */
41829/***/ (function(module, exports) {
41830
41831module.exports = {
41832 'name': 'SQRT1_2',
41833 'category': 'Constants',
41834 'syntax': [
41835 'SQRT1_2'
41836 ],
41837 'description': 'Returns the square root of 1/2, approximately equal to 0.707',
41838 'examples': [
41839 'SQRT1_2',
41840 'sqrt(1/2)'
41841 ],
41842 'seealso': []
41843};
41844
41845
41846/***/ }),
41847/* 219 */
41848/***/ (function(module, exports) {
41849
41850module.exports = {
41851 'name': 'SQRT2',
41852 'category': 'Constants',
41853 'syntax': [
41854 'SQRT2'
41855 ],
41856 'description': 'Returns the square root of 2, approximately equal to 1.414',
41857 'examples': [
41858 'SQRT2',
41859 'sqrt(2)'
41860 ],
41861 'seealso': []
41862};
41863
41864
41865/***/ }),
41866/* 220 */
41867/***/ (function(module, exports) {
41868
41869module.exports = {
41870 'name': 'tau',
41871 'category': 'Constants',
41872 'syntax': [
41873 'tau'
41874 ],
41875 'description': 'Tau is the ratio constant of a circle\'s circumference to radius, equal to 2 * pi, approximately 6.2832.',
41876 'examples': [
41877 'tau',
41878 '2 * pi'
41879 ],
41880 'seealso': ['pi']
41881};
41882
41883
41884/***/ }),
41885/* 221 */
41886/***/ (function(module, exports) {
41887
41888module.exports = {
41889 'name': 'true',
41890 'category': 'Constants',
41891 'syntax': [
41892 'true'
41893 ],
41894 'description': 'Boolean value true',
41895 'examples': [
41896 'true'
41897 ],
41898 'seealso': ['false']
41899};
41900
41901
41902/***/ }),
41903/* 222 */
41904/***/ (function(module, exports) {
41905
41906module.exports = {
41907 'name': 'version',
41908 'category': 'Constants',
41909 'syntax': [
41910 'version'
41911 ],
41912 'description': 'A string with the version number of math.js',
41913 'examples': [
41914 'version'
41915 ],
41916 'seealso': []
41917};
41918
41919
41920/***/ }),
41921/* 223 */
41922/***/ (function(module, exports) {
41923
41924module.exports = {
41925 'name': 'derivative',
41926 'category': 'Algebra',
41927 'syntax': [
41928 'derivative(expr, variable)',
41929 'derivative(expr, variable, {simplify: boolean})'
41930 ],
41931 '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.',
41932 'examples': [
41933 'derivative("2x^3", "x")',
41934 'derivative("2x^3", "x", {simplify: false})',
41935 'derivative("2x^2 + 3x + 4", "x")',
41936 'derivative("sin(2x)", "x")',
41937 'f = parse("x^2 + x")',
41938 'x = parse("x")',
41939 'df = derivative(f, x)',
41940 'df.eval({x: 3})'
41941 ],
41942 'seealso': [
41943 'simplify', 'parse', 'eval'
41944 ]
41945};
41946
41947
41948/***/ }),
41949/* 224 */
41950/***/ (function(module, exports) {
41951
41952module.exports = {
41953 'name': 'lsolve',
41954 'category': 'Algebra',
41955 'syntax': [
41956 'x=lsolve(L, b)'
41957 ],
41958 'description':
41959 'Solves the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.',
41960 'examples': [
41961 'a = [-2, 3; 2, 1]',
41962 'b = [11, 9]',
41963 'x = lsolve(a, b)'
41964 ],
41965 'seealso': [
41966 'lup', 'lusolve', 'usolve', 'matrix', 'sparse'
41967 ]
41968};
41969
41970
41971/***/ }),
41972/* 225 */
41973/***/ (function(module, exports) {
41974
41975module.exports = {
41976 'name': 'lup',
41977 'category': 'Algebra',
41978 'syntax': [
41979 'lup(m)'
41980 ],
41981 'description':
41982 'Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in three matrices (L, U, P) where P * A = L * U',
41983 'examples': [
41984 'lup([[2, 1], [1, 4]])',
41985 'lup(matrix([[2, 1], [1, 4]]))',
41986 'lup(sparse([[2, 1], [1, 4]]))'
41987 ],
41988 'seealso': [
41989 'lusolve', 'lsolve', 'usolve', 'matrix', 'sparse', 'slu', 'qr'
41990 ]
41991};
41992
41993
41994/***/ }),
41995/* 226 */
41996/***/ (function(module, exports) {
41997
41998module.exports = {
41999 'name': 'lusolve',
42000 'category': 'Algebra',
42001 'syntax': [
42002 'x=lusolve(A, b)',
42003 'x=lusolve(lu, b)'
42004 ],
42005 'description': 'Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector.',
42006 'examples': [
42007 'a = [-2, 3; 2, 1]',
42008 'b = [11, 9]',
42009 'x = lusolve(a, b)'
42010 ],
42011 'seealso': [
42012 'lup', 'slu', 'lsolve', 'usolve', 'matrix', 'sparse'
42013 ]
42014};
42015
42016
42017/***/ }),
42018/* 227 */
42019/***/ (function(module, exports) {
42020
42021module.exports = {
42022 'name': 'simplify',
42023 'category': 'Algebra',
42024 'syntax': [
42025 'simplify(expr)',
42026 'simplify(expr, rules)'
42027 ],
42028 'description': 'Simplify an expression tree.',
42029 'examples': [
42030 'simplify("3 + 2 / 4")',
42031 'simplify("2x + x")',
42032 'f = parse("x * (x + 2 + x)")',
42033 'simplified = simplify(f)',
42034 'simplified.eval({x: 2})'
42035 ],
42036 'seealso': [
42037 'derivative', 'parse', 'eval'
42038 ]
42039};
42040
42041
42042/***/ }),
42043/* 228 */
42044/***/ (function(module, exports) {
42045
42046module.exports = {
42047 'name': 'rationalize',
42048 'category': 'Algebra',
42049 'syntax': [
42050 'rationalize(expr)',
42051 'rationalize(expr, scope)',
42052 'rationalize(expr, scope, detailed)'
42053 ],
42054 '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.',
42055 'examples': [
42056 'rationalize("2x/y - y/(x+1)")',
42057 'rationalize("2x/y - y/(x+1)", true)',
42058 ],
42059 'seealso': [
42060 'simplify'
42061 ]
42062};
42063
42064
42065/***/ }),
42066/* 229 */
42067/***/ (function(module, exports) {
42068
42069module.exports = {
42070 'name': 'slu',
42071 'category': 'Algebra',
42072 'syntax': [
42073 'slu(A, order, threshold)'
42074 ],
42075 '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',
42076 'examples': [
42077 '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)'
42078 ],
42079 'seealso': [
42080 'lusolve', 'lsolve', 'usolve', 'matrix', 'sparse', 'lup', 'qr'
42081 ]
42082};
42083
42084
42085/***/ }),
42086/* 230 */
42087/***/ (function(module, exports) {
42088
42089module.exports = {
42090 'name': 'usolve',
42091 'category': 'Algebra',
42092 'syntax': [
42093 'x=usolve(U, b)'
42094 ],
42095 'description':
42096 'Solves the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.',
42097 'examples': [
42098 'x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])'
42099 ],
42100 'seealso': [
42101 'lup', 'lusolve', 'lsolve', 'matrix', 'sparse'
42102 ]
42103};
42104
42105
42106/***/ }),
42107/* 231 */
42108/***/ (function(module, exports) {
42109
42110module.exports = {
42111 'name': 'qr',
42112 'category': 'Algebra',
42113 'syntax': [
42114 'qr(A)'
42115 ],
42116 'description':
42117 '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.',
42118 'examples': [
42119 'qr([[1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0]])'
42120 ],
42121 'seealso': [
42122 'lup', 'slu', 'matrix'
42123 ]
42124};
42125
42126
42127/***/ }),
42128/* 232 */
42129/***/ (function(module, exports) {
42130
42131module.exports = {
42132 'name': 'abs',
42133 'category': 'Arithmetic',
42134 'syntax': [
42135 'abs(x)'
42136 ],
42137 'description': 'Compute the absolute value.',
42138 'examples': [
42139 'abs(3.5)',
42140 'abs(-4.2)'
42141 ],
42142 'seealso': ['sign']
42143};
42144
42145
42146/***/ }),
42147/* 233 */
42148/***/ (function(module, exports) {
42149
42150module.exports = {
42151 'name': 'add',
42152 'category': 'Operators',
42153 'syntax': [
42154 'x + y',
42155 'add(x, y)'
42156 ],
42157 'description': 'Add two values.',
42158 'examples': [
42159 'a = 2.1 + 3.6',
42160 'a - 3.6',
42161 '3 + 2i',
42162 '3 cm + 2 inch',
42163 '"2.3" + "4"'
42164 ],
42165 'seealso': [
42166 'subtract'
42167 ]
42168};
42169
42170
42171/***/ }),
42172/* 234 */
42173/***/ (function(module, exports) {
42174
42175module.exports = {
42176 'name': 'cbrt',
42177 'category': 'Arithmetic',
42178 'syntax': [
42179 'cbrt(x)',
42180 'cbrt(x, allRoots)'
42181 ],
42182 'description':
42183 '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',
42184 'examples': [
42185 'cbrt(64)',
42186 'cube(4)',
42187 'cbrt(-8)',
42188 'cbrt(2 + 3i)',
42189 'cbrt(8i)',
42190 'cbrt(8i, true)',
42191 'cbrt(27 m^3)'
42192 ],
42193 'seealso': [
42194 'square',
42195 'sqrt',
42196 'cube',
42197 'multiply'
42198 ]
42199};
42200
42201
42202/***/ }),
42203/* 235 */
42204/***/ (function(module, exports) {
42205
42206module.exports = {
42207 'name': 'ceil',
42208 'category': 'Arithmetic',
42209 'syntax': [
42210 'ceil(x)'
42211 ],
42212 'description':
42213 'Round a value towards plus infinity. If x is complex, both real and imaginary part are rounded towards plus infinity.',
42214 'examples': [
42215 'ceil(3.2)',
42216 'ceil(3.8)',
42217 'ceil(-4.2)'
42218 ],
42219 'seealso': ['floor', 'fix', 'round']
42220};
42221
42222
42223/***/ }),
42224/* 236 */
42225/***/ (function(module, exports) {
42226
42227module.exports = {
42228 'name': 'cube',
42229 'category': 'Arithmetic',
42230 'syntax': [
42231 'cube(x)'
42232 ],
42233 'description': 'Compute the cube of a value. The cube of x is x * x * x.',
42234 'examples': [
42235 'cube(2)',
42236 '2^3',
42237 '2 * 2 * 2'
42238 ],
42239 'seealso': [
42240 'multiply',
42241 'square',
42242 'pow'
42243 ]
42244};
42245
42246
42247/***/ }),
42248/* 237 */
42249/***/ (function(module, exports) {
42250
42251module.exports = {
42252 'name': 'divide',
42253 'category': 'Operators',
42254 'syntax': [
42255 'x / y',
42256 'divide(x, y)'
42257 ],
42258 'description': 'Divide two values.',
42259 'examples': [
42260 'a = 2 / 3',
42261 'a * 3',
42262 '4.5 / 2',
42263 '3 + 4 / 2',
42264 '(3 + 4) / 2',
42265 '18 km / 4.5'
42266 ],
42267 'seealso': [
42268 'multiply'
42269 ]
42270};
42271
42272
42273/***/ }),
42274/* 238 */
42275/***/ (function(module, exports) {
42276
42277module.exports = {
42278 'name': 'dotDivide',
42279 'category': 'Operators',
42280 'syntax': [
42281 'x ./ y',
42282 'dotDivide(x, y)'
42283 ],
42284 'description': 'Divide two values element wise.',
42285 'examples': [
42286 'a = [1, 2, 3; 4, 5, 6]',
42287 'b = [2, 1, 1; 3, 2, 5]',
42288 'a ./ b'
42289 ],
42290 'seealso': [
42291 'multiply',
42292 'dotMultiply',
42293 'divide'
42294 ]
42295};
42296
42297
42298/***/ }),
42299/* 239 */
42300/***/ (function(module, exports) {
42301
42302module.exports = {
42303 'name': 'dotMultiply',
42304 'category': 'Operators',
42305 'syntax': [
42306 'x .* y',
42307 'dotMultiply(x, y)'
42308 ],
42309 'description': 'Multiply two values element wise.',
42310 'examples': [
42311 'a = [1, 2, 3; 4, 5, 6]',
42312 'b = [2, 1, 1; 3, 2, 5]',
42313 'a .* b'
42314 ],
42315 'seealso': [
42316 'multiply',
42317 'divide',
42318 'dotDivide'
42319 ]
42320};
42321
42322
42323/***/ }),
42324/* 240 */
42325/***/ (function(module, exports) {
42326
42327module.exports = {
42328 'name': 'dotpow',
42329 'category': 'Operators',
42330 'syntax': [
42331 'x .^ y',
42332 'dotpow(x, y)'
42333 ],
42334 'description':
42335 'Calculates the power of x to y element wise.',
42336 'examples': [
42337 'a = [1, 2, 3; 4, 5, 6]',
42338 'a .^ 2'
42339 ],
42340 'seealso': [
42341 'pow'
42342 ]
42343};
42344
42345
42346/***/ }),
42347/* 241 */
42348/***/ (function(module, exports) {
42349
42350module.exports = {
42351 'name': 'exp',
42352 'category': 'Arithmetic',
42353 'syntax': [
42354 'exp(x)'
42355 ],
42356 'description': 'Calculate the exponent of a value.',
42357 'examples': [
42358 'exp(1.3)',
42359 'e ^ 1.3',
42360 'log(exp(1.3))',
42361 'x = 2.4',
42362 '(exp(i*x) == cos(x) + i*sin(x)) # Euler\'s formula'
42363 ],
42364 'seealso': [
42365 'pow',
42366 'log'
42367 ]
42368};
42369
42370
42371/***/ }),
42372/* 242 */
42373/***/ (function(module, exports) {
42374
42375module.exports = {
42376 'name': 'fix',
42377 'category': 'Arithmetic',
42378 'syntax': [
42379 'fix(x)'
42380 ],
42381 'description':
42382 'Round a value towards zero. If x is complex, both real and imaginary part are rounded towards zero.',
42383 'examples': [
42384 'fix(3.2)',
42385 'fix(3.8)',
42386 'fix(-4.2)',
42387 'fix(-4.8)'
42388 ],
42389 'seealso': ['ceil', 'floor', 'round']
42390};
42391
42392
42393/***/ }),
42394/* 243 */
42395/***/ (function(module, exports) {
42396
42397module.exports = {
42398 'name': 'floor',
42399 'category': 'Arithmetic',
42400 'syntax': [
42401 'floor(x)'
42402 ],
42403 'description':
42404 'Round a value towards minus infinity.If x is complex, both real and imaginary part are rounded towards minus infinity.',
42405 'examples': [
42406 'floor(3.2)',
42407 'floor(3.8)',
42408 'floor(-4.2)'
42409 ],
42410 'seealso': ['ceil', 'fix', 'round']
42411};
42412
42413
42414/***/ }),
42415/* 244 */
42416/***/ (function(module, exports) {
42417
42418module.exports = {
42419 'name': 'gcd',
42420 'category': 'Arithmetic',
42421 'syntax': [
42422 'gcd(a, b)',
42423 'gcd(a, b, c, ...)'
42424 ],
42425 'description': 'Compute the greatest common divisor.',
42426 'examples': [
42427 'gcd(8, 12)',
42428 'gcd(-4, 6)',
42429 'gcd(25, 15, -10)'
42430 ],
42431 'seealso': [ 'lcm', 'xgcd' ]
42432};
42433
42434
42435/***/ }),
42436/* 245 */
42437/***/ (function(module, exports) {
42438
42439module.exports = {
42440 'name': 'hypot',
42441 'category': 'Arithmetic',
42442 'syntax': [
42443 'hypot(a, b, c, ...)',
42444 'hypot([a, b, c, ...])'
42445 ],
42446 'description': 'Calculate the hypotenusa of a list with values. ',
42447 'examples': [
42448 'hypot(3, 4)',
42449 'sqrt(3^2 + 4^2)',
42450 'hypot(-2)',
42451 'hypot([3, 4, 5])'
42452 ],
42453 'seealso': [ 'abs', 'norm' ]
42454};
42455
42456
42457/***/ }),
42458/* 246 */
42459/***/ (function(module, exports) {
42460
42461module.exports = {
42462 'name': 'lcm',
42463 'category': 'Arithmetic',
42464 'syntax': [
42465 'lcm(x, y)'
42466 ],
42467 'description': 'Compute the least common multiple.',
42468 'examples': [
42469 'lcm(4, 6)',
42470 'lcm(6, 21)',
42471 'lcm(6, 21, 5)'
42472 ],
42473 'seealso': [ 'gcd' ]
42474};
42475
42476
42477/***/ }),
42478/* 247 */
42479/***/ (function(module, exports) {
42480
42481module.exports = {
42482 'name': 'log',
42483 'category': 'Arithmetic',
42484 'syntax': [
42485 'log(x)',
42486 'log(x, base)'
42487 ],
42488 '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).',
42489 'examples': [
42490 'log(3.5)',
42491 'a = log(2.4)',
42492 'exp(a)',
42493 '10 ^ 4',
42494 'log(10000, 10)',
42495 'log(10000) / log(10)',
42496 'b = log(1024, 2)',
42497 '2 ^ b'
42498 ],
42499 'seealso': [
42500 'exp',
42501 'log10'
42502 ]
42503};
42504
42505/***/ }),
42506/* 248 */
42507/***/ (function(module, exports) {
42508
42509module.exports = {
42510 'name': 'log10',
42511 'category': 'Arithmetic',
42512 'syntax': [
42513 'log10(x)'
42514 ],
42515 'description': 'Compute the 10-base logarithm of a value.',
42516 'examples': [
42517 'log10(0.00001)',
42518 'log10(10000)',
42519 '10 ^ 4',
42520 'log(10000) / log(10)',
42521 'log(10000, 10)'
42522 ],
42523 'seealso': [
42524 'exp',
42525 'log'
42526 ]
42527};
42528
42529
42530/***/ }),
42531/* 249 */
42532/***/ (function(module, exports) {
42533
42534module.exports = {
42535 'name': 'mod',
42536 'category': 'Operators',
42537 'syntax': [
42538 'x % y',
42539 'x mod y',
42540 'mod(x, y)'
42541 ],
42542 'description':
42543 'Calculates the modulus, the remainder of an integer division.',
42544 'examples': [
42545 '7 % 3',
42546 '11 % 2',
42547 '10 mod 4',
42548 'isOdd(x) = x % 2',
42549 'isOdd(2)',
42550 'isOdd(3)'
42551 ],
42552 'seealso': ['divide']
42553};
42554
42555
42556/***/ }),
42557/* 250 */
42558/***/ (function(module, exports) {
42559
42560module.exports = {
42561 'name': 'multiply',
42562 'category': 'Operators',
42563 'syntax': [
42564 'x * y',
42565 'multiply(x, y)'
42566 ],
42567 'description': 'multiply two values.',
42568 'examples': [
42569 'a = 2.1 * 3.4',
42570 'a / 3.4',
42571 '2 * 3 + 4',
42572 '2 * (3 + 4)',
42573 '3 * 2.1 km'
42574 ],
42575 'seealso': [
42576 'divide'
42577 ]
42578};
42579
42580
42581/***/ }),
42582/* 251 */
42583/***/ (function(module, exports) {
42584
42585module.exports = {
42586 'name': 'norm',
42587 'category': 'Arithmetic',
42588 'syntax': [
42589 'norm(x)',
42590 'norm(x, p)'
42591 ],
42592 'description': 'Calculate the norm of a number, vector or matrix.',
42593 'examples': [
42594 'abs(-3.5)',
42595 'norm(-3.5)',
42596 'norm(3 - 4i)',
42597 'norm([1, 2, -3], Infinity)',
42598 'norm([1, 2, -3], -Infinity)',
42599 'norm([3, 4], 2)',
42600 'norm([[1, 2], [3, 4]], 1)',
42601 'norm([[1, 2], [3, 4]], "inf")',
42602 'norm([[1, 2], [3, 4]], "fro")'
42603 ]
42604};
42605
42606
42607/***/ }),
42608/* 252 */
42609/***/ (function(module, exports) {
42610
42611module.exports = {
42612 'name': 'nthRoot',
42613 'category': 'Arithmetic',
42614 'syntax': [
42615 'nthRoot(a)',
42616 'nthRoot(a, root)'
42617 ],
42618 'description': 'Calculate the nth root of a value. ' +
42619 'The principal nth root of a positive real number A, ' +
42620 'is the positive real solution of the equation "x^root = A".',
42621 'examples': [
42622 '4 ^ 3',
42623 'nthRoot(64, 3)',
42624 'nthRoot(9, 2)',
42625 'sqrt(9)'
42626 ],
42627 'seealso': [
42628 'sqrt',
42629 'pow'
42630 ]
42631};
42632
42633/***/ }),
42634/* 253 */
42635/***/ (function(module, exports) {
42636
42637module.exports = {
42638 'name': 'pow',
42639 'category': 'Operators',
42640 'syntax': [
42641 'x ^ y',
42642 'pow(x, y)'
42643 ],
42644 'description':
42645 'Calculates the power of x to y, x^y.',
42646 'examples': [
42647 '2^3',
42648 '2*2*2',
42649 '1 + e ^ (pi * i)'
42650 ],
42651 'seealso': [ 'multiply' ]
42652};
42653
42654
42655/***/ }),
42656/* 254 */
42657/***/ (function(module, exports) {
42658
42659module.exports = {
42660 'name': 'round',
42661 'category': 'Arithmetic',
42662 'syntax': [
42663 'round(x)',
42664 'round(x, n)'
42665 ],
42666 'description':
42667 '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.',
42668 'examples': [
42669 'round(3.2)',
42670 'round(3.8)',
42671 'round(-4.2)',
42672 'round(-4.8)',
42673 'round(pi, 3)',
42674 'round(123.45678, 2)'
42675 ],
42676 'seealso': ['ceil', 'floor', 'fix']
42677};
42678
42679
42680/***/ }),
42681/* 255 */
42682/***/ (function(module, exports) {
42683
42684module.exports = {
42685 'name': 'sign',
42686 'category': 'Arithmetic',
42687 'syntax': [
42688 'sign(x)'
42689 ],
42690 'description':
42691 '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.',
42692 'examples': [
42693 'sign(3.5)',
42694 'sign(-4.2)',
42695 'sign(0)'
42696 ],
42697 'seealso': [
42698 'abs'
42699 ]
42700};
42701
42702
42703/***/ }),
42704/* 256 */
42705/***/ (function(module, exports) {
42706
42707module.exports = {
42708 'name': 'sqrt',
42709 'category': 'Arithmetic',
42710 'syntax': [
42711 'sqrt(x)'
42712 ],
42713 'description':
42714 'Compute the square root value. If x = y * y, then y is the square root of x.',
42715 'examples': [
42716 'sqrt(25)',
42717 '5 * 5',
42718 'sqrt(-1)'
42719 ],
42720 'seealso': [
42721 'square',
42722 'multiply'
42723 ]
42724};
42725
42726
42727/***/ }),
42728/* 257 */
42729/***/ (function(module, exports) {
42730
42731module.exports = {
42732 'name': 'square',
42733 'category': 'Arithmetic',
42734 'syntax': [
42735 'square(x)'
42736 ],
42737 'description':
42738 'Compute the square of a value. The square of x is x * x.',
42739 'examples': [
42740 'square(3)',
42741 'sqrt(9)',
42742 '3^2',
42743 '3 * 3'
42744 ],
42745 'seealso': [
42746 'multiply',
42747 'pow',
42748 'sqrt',
42749 'cube'
42750 ]
42751};
42752
42753
42754/***/ }),
42755/* 258 */
42756/***/ (function(module, exports) {
42757
42758module.exports = {
42759 'name': 'subtract',
42760 'category': 'Operators',
42761 'syntax': [
42762 'x - y',
42763 'subtract(x, y)'
42764 ],
42765 'description': 'subtract two values.',
42766 'examples': [
42767 'a = 5.3 - 2',
42768 'a + 2',
42769 '2/3 - 1/6',
42770 '2 * 3 - 3',
42771 '2.1 km - 500m'
42772 ],
42773 'seealso': [
42774 'add'
42775 ]
42776};
42777
42778
42779/***/ }),
42780/* 259 */
42781/***/ (function(module, exports) {
42782
42783module.exports = {
42784 'name': 'unaryMinus',
42785 'category': 'Operators',
42786 'syntax': [
42787 '-x',
42788 'unaryMinus(x)'
42789 ],
42790 'description':
42791 'Inverse the sign of a value. Converts booleans and strings to numbers.',
42792 'examples': [
42793 '-4.5',
42794 '-(-5.6)',
42795 '-"22"'
42796 ],
42797 'seealso': [
42798 'add', 'subtract', 'unaryPlus'
42799 ]
42800};
42801
42802
42803/***/ }),
42804/* 260 */
42805/***/ (function(module, exports) {
42806
42807module.exports = {
42808 'name': 'unaryPlus',
42809 'category': 'Operators',
42810 'syntax': [
42811 '+x',
42812 'unaryPlus(x)'
42813 ],
42814 'description':
42815 'Converts booleans and strings to numbers.',
42816 'examples': [
42817 '+true',
42818 '+"2"'
42819 ],
42820 'seealso': [
42821 'add', 'subtract', 'unaryMinus'
42822 ]
42823};
42824
42825
42826/***/ }),
42827/* 261 */
42828/***/ (function(module, exports) {
42829
42830module.exports = {
42831 'name': 'xgcd',
42832 'category': 'Arithmetic',
42833 'syntax': [
42834 'xgcd(a, b)'
42835 ],
42836 '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.',
42837 'examples': [
42838 'xgcd(8, 12)',
42839 'gcd(8, 12)',
42840 'xgcd(36163, 21199)'
42841 ],
42842 'seealso': [ 'gcd', 'lcm' ]
42843};
42844
42845
42846/***/ }),
42847/* 262 */
42848/***/ (function(module, exports) {
42849
42850module.exports = {
42851 'name': 'bitAnd',
42852 'category': 'Bitwise',
42853 'syntax': [
42854 'x & y',
42855 'bitAnd(x, y)'
42856 ],
42857 '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',
42858 'examples': [
42859 '5 & 3',
42860 'bitAnd(53, 131)',
42861 '[1, 12, 31] & 42'
42862 ],
42863 'seealso': [
42864 'bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift'
42865 ]
42866};
42867
42868
42869/***/ }),
42870/* 263 */
42871/***/ (function(module, exports) {
42872
42873module.exports = {
42874 'name': 'bitNot',
42875 'category': 'Bitwise',
42876 'syntax': [
42877 '~x',
42878 'bitNot(x)'
42879 ],
42880 '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.',
42881 'examples': [
42882 '~1',
42883 '~2',
42884 'bitNot([2, -3, 4])'
42885 ],
42886 'seealso': [
42887 'bitAnd', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift'
42888 ]
42889};
42890
42891
42892/***/ }),
42893/* 264 */
42894/***/ (function(module, exports) {
42895
42896module.exports = {
42897 'name': 'bitOr',
42898 'category': 'Bitwise',
42899 'syntax': [
42900 'x | y',
42901 'bitOr(x, y)'
42902 ],
42903 '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.',
42904 'examples': [
42905 '5 | 3',
42906 'bitOr([1, 2, 3], 4)'
42907 ],
42908 'seealso': [
42909 'bitAnd', 'bitNot', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift'
42910 ]
42911};
42912
42913
42914/***/ }),
42915/* 265 */
42916/***/ (function(module, exports) {
42917
42918module.exports = {
42919 'name': 'bitXor',
42920 'category': 'Bitwise',
42921 'syntax': [
42922 'bitXor(x, y)'
42923 ],
42924 '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.',
42925 'examples': [
42926 'bitOr(1, 2)',
42927 'bitXor([2, 3, 4], 4)'
42928 ],
42929 'seealso': [
42930 'bitAnd', 'bitNot', 'bitOr', 'leftShift', 'rightArithShift', 'rightLogShift'
42931 ]
42932};
42933
42934
42935/***/ }),
42936/* 266 */
42937/***/ (function(module, exports) {
42938
42939module.exports = {
42940 'name': 'leftShift',
42941 'category': 'Bitwise',
42942 'syntax': [
42943 'x << y',
42944 'leftShift(x, y)'
42945 ],
42946 'description': 'Bitwise left logical shift of a value x by y number of bits.',
42947 'examples': [
42948 '4 << 1',
42949 '8 >> 1'
42950 ],
42951 'seealso': [
42952 'bitAnd', 'bitNot', 'bitOr', 'bitXor', 'rightArithShift', 'rightLogShift'
42953 ]
42954};
42955
42956
42957/***/ }),
42958/* 267 */
42959/***/ (function(module, exports) {
42960
42961module.exports = {
42962 'name': 'rightArithShift',
42963 'category': 'Bitwise',
42964 'syntax': [
42965 'x >> y',
42966 'rightArithShift(x, y)'
42967 ],
42968 'description': 'Bitwise right arithmetic shift of a value x by y number of bits.',
42969 'examples': [
42970 '8 >> 1',
42971 '4 << 1',
42972 '-12 >> 2'
42973 ],
42974 'seealso': [
42975 'bitAnd', 'bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightLogShift'
42976 ]
42977};
42978
42979
42980/***/ }),
42981/* 268 */
42982/***/ (function(module, exports) {
42983
42984module.exports = {
42985 'name': 'rightLogShift',
42986 'category': 'Bitwise',
42987 'syntax': [
42988 'x >>> y',
42989 'rightLogShift(x, y)'
42990 ],
42991 'description': 'Bitwise right logical shift of a value x by y number of bits.',
42992 'examples': [
42993 '8 >>> 1',
42994 '4 << 1',
42995 '-12 >>> 2'
42996 ],
42997 'seealso': [
42998 'bitAnd', 'bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift'
42999 ]
43000};
43001
43002
43003/***/ }),
43004/* 269 */
43005/***/ (function(module, exports) {
43006
43007module.exports = {
43008 'name': 'bellNumbers',
43009 'category': 'Combinatorics',
43010 'syntax': [
43011 'bellNumbers(n)'
43012 ],
43013 '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.',
43014 'examples': [
43015 'bellNumbers(3)',
43016 'bellNumbers(8)'
43017 ],
43018 'seealso': ['stirlingS2']
43019};
43020
43021/***/ }),
43022/* 270 */
43023/***/ (function(module, exports) {
43024
43025module.exports = {
43026 'name': 'catalan',
43027 'category': 'Combinatorics',
43028 'syntax': [
43029 'catalan(n)'
43030 ],
43031 'description': 'The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0.',
43032 'examples': [
43033 'catalan(3)',
43034 'catalan(8)'
43035 ],
43036 'seealso': ['bellNumbers']
43037};
43038
43039/***/ }),
43040/* 271 */
43041/***/ (function(module, exports) {
43042
43043module.exports = {
43044 'name': 'composition',
43045 'category': 'Combinatorics',
43046 'syntax': [
43047 'composition(n, k)'
43048 ],
43049 'description': 'The composition counts of n into k parts. composition only takes integer arguments. The following condition must be enforced: k <= n.',
43050 'examples': [
43051 'composition(5, 3)'
43052 ],
43053 'seealso': ['combinations']
43054};
43055
43056/***/ }),
43057/* 272 */
43058/***/ (function(module, exports) {
43059
43060module.exports = {
43061 'name': 'stirlingS2',
43062 'category': 'Combinatorics',
43063 'syntax': [
43064 'stirlingS2(n, k)'
43065 ],
43066 '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.',
43067 'examples': [
43068 'stirlingS2(5, 3)'
43069 ],
43070 'seealso': ['bellNumbers']
43071};
43072
43073
43074/***/ }),
43075/* 273 */
43076/***/ (function(module, exports) {
43077
43078module.exports = {
43079 'name': 'config',
43080 'category': 'Core',
43081 'syntax': [
43082 'config()',
43083 'config(options)'
43084 ],
43085 'description': 'Get configuration or change configuration.',
43086 'examples': [
43087 'config()',
43088 '1/3 + 1/4',
43089 'config({number: "Fraction"})',
43090 '1/3 + 1/4'
43091 ],
43092 'seealso': []
43093};
43094
43095
43096/***/ }),
43097/* 274 */
43098/***/ (function(module, exports) {
43099
43100module.exports = {
43101 'name': 'import',
43102 'category': 'Core',
43103 'syntax': [
43104 'import(functions)',
43105 'import(functions, options)'
43106 ],
43107 'description': 'Import functions or constants from an object.',
43108 'examples': [
43109 'import({myFn: f(x)=x^2, myConstant: 32 })',
43110 'myFn(2)',
43111 'myConstant'
43112 ],
43113 'seealso': []
43114};
43115
43116
43117/***/ }),
43118/* 275 */
43119/***/ (function(module, exports) {
43120
43121module.exports = {
43122 'name': 'typed',
43123 'category': 'Core',
43124 'syntax': [
43125 'typed(signatures)',
43126 'typed(name, signatures)'
43127 ],
43128 'description': 'Create a typed function.',
43129 'examples': [
43130 'double = typed({ "number, number": f(x)=x+x })',
43131 'double(2)',
43132 'double("hello")'
43133 ],
43134 'seealso': []
43135};
43136
43137
43138/***/ }),
43139/* 276 */
43140/***/ (function(module, exports) {
43141
43142module.exports = {
43143 'name': 'arg',
43144 'category': 'Complex',
43145 'syntax': [
43146 'arg(x)'
43147 ],
43148 'description':
43149 'Compute the argument of a complex value. If x = a+bi, the argument is computed as atan2(b, a).',
43150 'examples': [
43151 'arg(2 + 2i)',
43152 'atan2(3, 2)',
43153 'arg(2 + 3i)'
43154 ],
43155 'seealso': [
43156 're',
43157 'im',
43158 'conj',
43159 'abs'
43160 ]
43161};
43162
43163
43164/***/ }),
43165/* 277 */
43166/***/ (function(module, exports) {
43167
43168module.exports = {
43169 'name': 'conj',
43170 'category': 'Complex',
43171 'syntax': [
43172 'conj(x)'
43173 ],
43174 'description':
43175 'Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate is a-bi.',
43176 'examples': [
43177 'conj(2 + 3i)',
43178 'conj(2 - 3i)',
43179 'conj(-5.2i)'
43180 ],
43181 'seealso': [
43182 're',
43183 'im',
43184 'abs',
43185 'arg'
43186 ]
43187};
43188
43189
43190/***/ }),
43191/* 278 */
43192/***/ (function(module, exports) {
43193
43194module.exports = {
43195 'name': 're',
43196 'category': 'Complex',
43197 'syntax': [
43198 're(x)'
43199 ],
43200 'description': 'Get the real part of a complex number.',
43201 'examples': [
43202 're(2 + 3i)',
43203 'im(2 + 3i)',
43204 're(-5.2i)',
43205 're(2.4)'
43206 ],
43207 'seealso': [
43208 'im',
43209 'conj',
43210 'abs',
43211 'arg'
43212 ]
43213};
43214
43215
43216/***/ }),
43217/* 279 */
43218/***/ (function(module, exports) {
43219
43220module.exports = {
43221 'name': 'im',
43222 'category': 'Complex',
43223 'syntax': [
43224 'im(x)'
43225 ],
43226 'description': 'Get the imaginary part of a complex number.',
43227 'examples': [
43228 'im(2 + 3i)',
43229 're(2 + 3i)',
43230 'im(-5.2i)',
43231 'im(2.4)'
43232 ],
43233 'seealso': [
43234 're',
43235 'conj',
43236 'abs',
43237 'arg'
43238 ]
43239};
43240
43241
43242/***/ }),
43243/* 280 */
43244/***/ (function(module, exports) {
43245
43246module.exports = {
43247 'name': 'eval',
43248 'category': 'Expression',
43249 'syntax': [
43250 'eval(expression)',
43251 'eval([expr1, expr2, expr3, ...])'
43252 ],
43253 'description': 'Evaluate an expression or an array with expressions.',
43254 'examples': [
43255 'eval("2 + 3")',
43256 'eval("sqrt(" + 4 + ")")'
43257 ],
43258 'seealso': []
43259};
43260
43261
43262/***/ }),
43263/* 281 */
43264/***/ (function(module, exports) {
43265
43266module.exports = {
43267 'name': 'help',
43268 'category': 'Expression',
43269 'syntax': [
43270 'help(object)',
43271 'help(string)'
43272 ],
43273 'description': 'Display documentation on a function or data type.',
43274 'examples': [
43275 'help(sqrt)',
43276 'help("complex")'
43277 ],
43278 'seealso': []
43279};
43280
43281
43282/***/ }),
43283/* 282 */
43284/***/ (function(module, exports) {
43285
43286module.exports = {
43287 'name': 'distance',
43288 'category': 'Geometry',
43289 'syntax': [
43290 'distance([x1, y1], [x2, y2])',
43291 'distance([[x1, y1], [x2, y2])'
43292 ],
43293 'description': 'Calculates the Euclidean distance between two points.',
43294 'examples': [
43295 'distance([0,0], [4,4])',
43296 'distance([[0,0], [4,4]])'
43297 ],
43298 'seealso': []
43299};
43300
43301
43302/***/ }),
43303/* 283 */
43304/***/ (function(module, exports) {
43305
43306module.exports = {
43307 'name': 'intersect',
43308 'category': 'Geometry',
43309 'syntax': [
43310 'intersect(expr1, expr2, expr3, expr4)',
43311 'intersect(expr1, expr2, expr3)'
43312 ],
43313 'description': 'Computes the intersection point of lines and/or planes.',
43314 'examples': [
43315 'intersect([0, 0], [10, 10], [10, 0], [0, 10])',
43316 'intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6])'
43317 ],
43318 'seealso': []
43319};
43320
43321
43322/***/ }),
43323/* 284 */
43324/***/ (function(module, exports) {
43325
43326module.exports = {
43327 'name': 'and',
43328 'category': 'Logical',
43329 'syntax': [
43330 'x and y',
43331 'and(x, y)'
43332 ],
43333 'description': 'Logical and. Test whether two values are both defined with a nonzero/nonempty value.',
43334 'examples': [
43335 'true and false',
43336 'true and true',
43337 '2 and 4'
43338 ],
43339 'seealso': [
43340 'not', 'or', 'xor'
43341 ]
43342};
43343
43344
43345/***/ }),
43346/* 285 */
43347/***/ (function(module, exports) {
43348
43349module.exports = {
43350 'name': 'not',
43351 'category': 'Logical',
43352 'syntax': [
43353 'not x',
43354 'not(x)'
43355 ],
43356 'description': 'Logical not. Flips the boolean value of given argument.',
43357 'examples': [
43358 'not true',
43359 'not false',
43360 'not 2',
43361 'not 0'
43362 ],
43363 'seealso': [
43364 'and', 'or', 'xor'
43365 ]
43366};
43367
43368
43369/***/ }),
43370/* 286 */
43371/***/ (function(module, exports) {
43372
43373module.exports = {
43374 'name': 'or',
43375 'category': 'Logical',
43376 'syntax': [
43377 'x or y',
43378 'or(x, y)'
43379 ],
43380 'description': 'Logical or. Test if at least one value is defined with a nonzero/nonempty value.',
43381 'examples': [
43382 'true or false',
43383 'false or false',
43384 '0 or 4'
43385 ],
43386 'seealso': [
43387 'not', 'and', 'xor'
43388 ]
43389};
43390
43391
43392/***/ }),
43393/* 287 */
43394/***/ (function(module, exports) {
43395
43396module.exports = {
43397 'name': 'xor',
43398 'category': 'Logical',
43399 'syntax': [
43400 'x xor y',
43401 'xor(x, y)'
43402 ],
43403 'description': 'Logical exclusive or, xor. Test whether one and only one value is defined with a nonzero/nonempty value.',
43404 'examples': [
43405 'true xor false',
43406 'false xor false',
43407 'true xor true',
43408 '0 xor 4'
43409 ],
43410 'seealso': [
43411 'not', 'and', 'or'
43412 ]
43413};
43414
43415
43416/***/ }),
43417/* 288 */
43418/***/ (function(module, exports) {
43419
43420module.exports = {
43421 'name': 'concat',
43422 'category': 'Matrix',
43423 'syntax': [
43424 'concat(A, B, C, ...)',
43425 'concat(A, B, C, ..., dim)'
43426 ],
43427 '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.',
43428 'examples': [
43429 'A = [1, 2; 5, 6]',
43430 'B = [3, 4; 7, 8]',
43431 'concat(A, B)',
43432 'concat(A, B, 1)',
43433 'concat(A, B, 2)'
43434 ],
43435 'seealso': [
43436 'det', 'diag', 'eye', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'
43437 ]
43438};
43439
43440
43441/***/ }),
43442/* 289 */
43443/***/ (function(module, exports) {
43444
43445module.exports = {
43446 'name': 'cross',
43447 'category': 'Matrix',
43448 'syntax': [
43449 'cross(A, B)'
43450 ],
43451 'description': 'Calculate the cross product for two vectors in three dimensional space.',
43452 'examples': [
43453 'cross([1, 1, 0], [0, 1, 1])',
43454 'cross([3, -3, 1], [4, 9, 2])',
43455 'cross([2, 3, 4], [5, 6, 7])'
43456 ],
43457 'seealso': [
43458 'multiply',
43459 'dot'
43460 ]
43461};
43462
43463
43464/***/ }),
43465/* 290 */
43466/***/ (function(module, exports) {
43467
43468module.exports = {
43469 'name': 'det',
43470 'category': 'Matrix',
43471 'syntax': [
43472 'det(x)'
43473 ],
43474 'description': 'Calculate the determinant of a matrix',
43475 'examples': [
43476 'det([1, 2; 3, 4])',
43477 'det([-2, 2, 3; -1, 1, 3; 2, 0, -1])'
43478 ],
43479 'seealso': [
43480 'concat', 'diag', 'eye', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'
43481 ]
43482};
43483
43484
43485/***/ }),
43486/* 291 */
43487/***/ (function(module, exports) {
43488
43489module.exports = {
43490 'name': 'diag',
43491 'category': 'Matrix',
43492 'syntax': [
43493 'diag(x)',
43494 'diag(x, k)'
43495 ],
43496 '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.',
43497 'examples': [
43498 'diag(1:3)',
43499 'diag(1:3, 1)',
43500 'a = [1, 2, 3; 4, 5, 6; 7, 8, 9]',
43501 'diag(a)'
43502 ],
43503 'seealso': [
43504 'concat', 'det', 'eye', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'
43505 ]
43506};
43507
43508
43509/***/ }),
43510/* 292 */
43511/***/ (function(module, exports) {
43512
43513module.exports = {
43514 'name': 'dot',
43515 'category': 'Matrix',
43516 'syntax': [
43517 'dot(A, B)',
43518 'A * B'
43519 ],
43520 'description': 'Calculate the dot product of two vectors. ' +
43521 'The dot product of A = [a1, a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] ' +
43522 'is defined as dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn',
43523 'examples': [
43524 'dot([2, 4, 1], [2, 2, 3])',
43525 '[2, 4, 1] * [2, 2, 3]'
43526 ],
43527 'seealso': [
43528 'multiply',
43529 'cross'
43530 ]
43531};
43532
43533
43534/***/ }),
43535/* 293 */
43536/***/ (function(module, exports) {
43537
43538module.exports = {
43539 'name': 'eye',
43540 'category': 'Matrix',
43541 'syntax': [
43542 'eye(n)',
43543 'eye(m, n)',
43544 'eye([m, n])'
43545 ],
43546 'description': 'Returns the identity matrix with size m-by-n. The matrix has ones on the diagonal and zeros elsewhere.',
43547 'examples': [
43548 'eye(3)',
43549 'eye(3, 5)',
43550 'a = [1, 2, 3; 4, 5, 6]',
43551 'eye(size(a))'
43552 ],
43553 'seealso': [
43554 'concat', 'det', 'diag', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'
43555 ]
43556};
43557
43558
43559/***/ }),
43560/* 294 */
43561/***/ (function(module, exports) {
43562
43563module.exports = {
43564 'name': 'filter',
43565 'category': 'Matrix',
43566 'syntax': [
43567 'filter(x, test)'
43568 ],
43569 'description': 'Filter items in a matrix.',
43570 'examples': [
43571 'isPositive(x) = x > 0',
43572 'filter([6, -2, -1, 4, 3], isPositive)',
43573 'filter([6, -2, 0, 1, 0], x != 0)'
43574 ],
43575 'seealso': ['sort', 'map', 'forEach']
43576};
43577
43578
43579/***/ }),
43580/* 295 */
43581/***/ (function(module, exports) {
43582
43583module.exports = {
43584 'name': 'flatten',
43585 'category': 'Matrix',
43586 'syntax': [
43587 'flatten(x)'
43588 ],
43589 'description': 'Flatten a multi dimensional matrix into a single dimensional matrix.',
43590 'examples': [
43591 'a = [1, 2, 3; 4, 5, 6]',
43592 'size(a)',
43593 'b = flatten(a)',
43594 'size(b)'
43595 ],
43596 'seealso': [
43597 'concat', 'resize', 'size', 'squeeze'
43598 ]
43599};
43600
43601
43602/***/ }),
43603/* 296 */
43604/***/ (function(module, exports) {
43605
43606module.exports = {
43607 'name': 'forEach',
43608 'category': 'Matrix',
43609 'syntax': [
43610 'forEach(x, callback)'
43611 ],
43612 'description': 'Iterates over all elements of a matrix/array, and executes the given callback function.',
43613 'examples': [
43614 'forEach([1, 2, 3], function(val) { console.log(val) })'
43615 ],
43616 'seealso': ['map', 'sort', 'filter']
43617};
43618
43619
43620/***/ }),
43621/* 297 */
43622/***/ (function(module, exports) {
43623
43624module.exports = {
43625 'name': 'inv',
43626 'category': 'Matrix',
43627 'syntax': [
43628 'inv(x)'
43629 ],
43630 'description': 'Calculate the inverse of a matrix',
43631 'examples': [
43632 'inv([1, 2; 3, 4])',
43633 'inv(4)',
43634 '1 / 4'
43635 ],
43636 'seealso': [
43637 'concat', 'det', 'diag', 'eye', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'
43638 ]
43639};
43640
43641
43642/***/ }),
43643/* 298 */
43644/***/ (function(module, exports) {
43645
43646module.exports = {
43647 'name': 'kron',
43648 'category': 'Matrix',
43649 'syntax': [
43650 'kron(x, y)'
43651 ],
43652 'description': 'Calculates the kronecker product of 2 matrices or vectors.',
43653 'examples': [
43654 'kron([[1, 0], [0, 1]], [[1, 2], [3, 4]])',
43655 'kron([1,1], [2,3,4])'
43656 ],
43657 'seealso': [
43658 'multiply', 'dot', 'cross'
43659 ]
43660};
43661
43662
43663/***/ }),
43664/* 299 */
43665/***/ (function(module, exports) {
43666
43667module.exports = {
43668 'name': 'map',
43669 'category': 'Matrix',
43670 'syntax': [
43671 'map(x, callback)'
43672 ],
43673 'description': 'Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array.',
43674 'examples': [
43675 'map([1, 2, 3], square)'
43676 ],
43677 'seealso': ['filter', 'forEach']
43678};
43679
43680
43681/***/ }),
43682/* 300 */
43683/***/ (function(module, exports) {
43684
43685module.exports = {
43686 'name': 'ones',
43687 'category': 'Matrix',
43688 'syntax': [
43689 'ones(m)',
43690 'ones(m, n)',
43691 'ones(m, n, p, ...)',
43692 'ones([m])',
43693 'ones([m, n])',
43694 'ones([m, n, p, ...])'
43695 ],
43696 'description': 'Create a matrix containing ones.',
43697 'examples': [
43698 'ones(3)',
43699 'ones(3, 5)',
43700 'ones([2,3]) * 4.5',
43701 'a = [1, 2, 3; 4, 5, 6]',
43702 'ones(size(a))'
43703 ],
43704 'seealso': [
43705 'concat', 'det', 'diag', 'eye', 'inv', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'
43706 ]
43707};
43708
43709
43710/***/ }),
43711/* 301 */
43712/***/ (function(module, exports) {
43713
43714module.exports = {
43715 'name': 'partitionSelect',
43716 'category': 'Matrix',
43717 'syntax': [
43718 'partitionSelect(x, k)',
43719 'partitionSelect(x, k, compare)'
43720 ],
43721 'description': 'Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect.',
43722 'examples': [
43723 'partitionSelect([5, 10, 1], 2)',
43724 'partitionSelect(["C", "B", "A", "D"], 1)'
43725 ],
43726 'seealso': ['sort']
43727};
43728
43729
43730/***/ }),
43731/* 302 */
43732/***/ (function(module, exports) {
43733
43734module.exports = {
43735 'name': 'range',
43736 'category': 'Type',
43737 'syntax': [
43738 'start:end',
43739 'start:step:end',
43740 'range(start, end)',
43741 'range(start, end, step)',
43742 'range(string)'
43743 ],
43744 'description':
43745 'Create a range. Lower bound of the range is included, upper bound is excluded.',
43746 'examples': [
43747 '1:5',
43748 '3:-1:-3',
43749 'range(3, 7)',
43750 'range(0, 12, 2)',
43751 'range("4:10")',
43752 'a = [1, 2, 3, 4; 5, 6, 7, 8]',
43753 'a[1:2, 1:2]'
43754 ],
43755 'seealso': [
43756 'concat', 'det', 'diag', 'eye', 'inv', 'ones', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'
43757 ]
43758};
43759
43760
43761/***/ }),
43762/* 303 */
43763/***/ (function(module, exports) {
43764
43765module.exports = {
43766 'name': 'resize',
43767 'category': 'Matrix',
43768 'syntax': [
43769 'resize(x, size)',
43770 'resize(x, size, defaultValue)'
43771 ],
43772 'description': 'Resize a matrix.',
43773 'examples': [
43774 'resize([1,2,3,4,5], [3])',
43775 'resize([1,2,3], [5])',
43776 'resize([1,2,3], [5], -1)',
43777 'resize(2, [2, 3])',
43778 'resize("hello", [8], "!")'
43779 ],
43780 'seealso': [
43781 'size', 'subset', 'squeeze', 'reshape'
43782 ]
43783};
43784
43785
43786/***/ }),
43787/* 304 */
43788/***/ (function(module, exports) {
43789
43790module.exports = {
43791 'name': 'reshape',
43792 'category': 'Matrix',
43793 'syntax': [
43794 'reshape(x, sizes)'
43795 ],
43796 'description': 'Reshape a multi dimensional array to fit the specified dimensions.',
43797 'examples': [
43798 'reshape([1, 2, 3, 4, 5, 6], [2, 3])',
43799 'reshape([[1, 2], [3, 4]], [1, 4])',
43800 'reshape([[1, 2], [3, 4]], [4])'
43801 ],
43802 'seealso': [
43803 'size', 'squeeze', 'resize'
43804 ]
43805};
43806
43807
43808/***/ }),
43809/* 305 */
43810/***/ (function(module, exports) {
43811
43812module.exports = {
43813 'name': 'size',
43814 'category': 'Matrix',
43815 'syntax': [
43816 'size(x)'
43817 ],
43818 'description': 'Calculate the size of a matrix.',
43819 'examples': [
43820 'size(2.3)',
43821 'size("hello world")',
43822 'a = [1, 2; 3, 4; 5, 6]',
43823 'size(a)',
43824 'size(1:6)'
43825 ],
43826 'seealso': [
43827 'concat', 'det', 'diag', 'eye', 'inv', 'ones', 'range', 'squeeze', 'subset', 'trace', 'transpose', 'zeros'
43828 ]
43829};
43830
43831
43832/***/ }),
43833/* 306 */
43834/***/ (function(module, exports) {
43835
43836module.exports = {
43837 'name': 'sort',
43838 'category': 'Matrix',
43839 'syntax': [
43840 'sort(x)',
43841 'sort(x, compare)'
43842 ],
43843 'description': 'Sort the items in a matrix. Compare can be a string "asc", "desc", "natural", or a custom sort function.',
43844 'examples': [
43845 'sort([5, 10, 1])',
43846 'sort(["C", "B", "A", "D"])',
43847 'sortByLength(a, b) = size(a)[1] - size(b)[1]',
43848 'sort(["Langdon", "Tom", "Sara"], sortByLength)',
43849 'sort(["10", "1", "2"], "natural")'
43850 ],
43851 'seealso': ['map', 'filter', 'forEach']
43852};
43853
43854
43855/***/ }),
43856/* 307 */
43857/***/ (function(module, exports) {
43858
43859module.exports = {
43860 'name': 'squeeze',
43861 'category': 'Matrix',
43862 'syntax': [
43863 'squeeze(x)'
43864 ],
43865 'description': 'Remove inner and outer singleton dimensions from a matrix.',
43866 'examples': [
43867 'a = zeros(3,2,1)',
43868 'size(squeeze(a))',
43869 'b = zeros(1,1,3)',
43870 'size(squeeze(b))'
43871 ],
43872 'seealso': [
43873 'concat', 'det', 'diag', 'eye', 'inv', 'ones', 'range', 'size', 'subset', 'trace', 'transpose', 'zeros'
43874 ]
43875};
43876
43877
43878/***/ }),
43879/* 308 */
43880/***/ (function(module, exports) {
43881
43882module.exports = {
43883 'name': 'subset',
43884 'category': 'Matrix',
43885 'syntax': [
43886 'value(index)',
43887 'value(index) = replacement',
43888 'subset(value, [index])',
43889 'subset(value, [index], replacement)'
43890 ],
43891 'description': 'Get or set a subset of a matrix or string. ' +
43892 'Indexes are one-based. ' +
43893 'Both the ranges lower-bound and upper-bound are included.',
43894 'examples': [
43895 'd = [1, 2; 3, 4]',
43896 'e = []',
43897 'e[1, 1:2] = [5, 6]',
43898 'e[2, :] = [7, 8]',
43899 'f = d * e',
43900 'f[2, 1]',
43901 'f[:, 1]'
43902 ],
43903 'seealso': [
43904 'concat', 'det', 'diag', 'eye', 'inv', 'ones', 'range', 'size', 'squeeze', 'trace', 'transpose', 'zeros'
43905 ]
43906};
43907
43908
43909/***/ }),
43910/* 309 */
43911/***/ (function(module, exports) {
43912
43913module.exports = {
43914 'name': 'trace',
43915 'category': 'Matrix',
43916 'syntax': [
43917 'trace(A)'
43918 ],
43919 'description': 'Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix.',
43920 'examples': [
43921 'A = [1, 2, 3; -1, 2, 3; 2, 0, 3]',
43922 'trace(A)'
43923 ],
43924 'seealso': [
43925 'concat', 'det', 'diag', 'eye', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'transpose', 'zeros'
43926 ]
43927};
43928
43929
43930/***/ }),
43931/* 310 */
43932/***/ (function(module, exports) {
43933
43934module.exports = {
43935 'name': 'transpose',
43936 'category': 'Matrix',
43937 'syntax': [
43938 'x\'',
43939 'transpose(x)'
43940 ],
43941 'description': 'Transpose a matrix',
43942 'examples': [
43943 'a = [1, 2, 3; 4, 5, 6]',
43944 'a\'',
43945 'transpose(a)'
43946 ],
43947 'seealso': [
43948 'concat', 'det', 'diag', 'eye', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'zeros'
43949 ]
43950};
43951
43952
43953/***/ }),
43954/* 311 */
43955/***/ (function(module, exports) {
43956
43957module.exports = {
43958 'name': 'zeros',
43959 'category': 'Matrix',
43960 'syntax': [
43961 'zeros(m)',
43962 'zeros(m, n)',
43963 'zeros(m, n, p, ...)',
43964 'zeros([m])',
43965 'zeros([m, n])',
43966 'zeros([m, n, p, ...])'
43967 ],
43968 'description': 'Create a matrix containing zeros.',
43969 'examples': [
43970 'zeros(3)',
43971 'zeros(3, 5)',
43972 'a = [1, 2, 3; 4, 5, 6]',
43973 'zeros(size(a))'
43974 ],
43975 'seealso': [
43976 'concat', 'det', 'diag', 'eye', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose'
43977 ]
43978};
43979
43980
43981/***/ }),
43982/* 312 */
43983/***/ (function(module, exports) {
43984
43985module.exports = {
43986 'name': 'combinations',
43987 'category': 'Probability',
43988 'syntax': [
43989 'combinations(n, k)'
43990 ],
43991 'description': 'Compute the number of combinations of n items taken k at a time',
43992 'examples': [
43993 'combinations(7, 5)'
43994 ],
43995 'seealso': ['permutations', 'factorial']
43996};
43997
43998
43999/***/ }),
44000/* 313 */
44001/***/ (function(module, exports) {
44002
44003module.exports = {
44004 'name': 'factorial',
44005 'category': 'Probability',
44006 'syntax': [
44007 'n!',
44008 'factorial(n)'
44009 ],
44010 'description': 'Compute the factorial of a value',
44011 'examples': [
44012 '5!',
44013 '5 * 4 * 3 * 2 * 1',
44014 '3!'
44015 ],
44016 'seealso': ['combinations', 'permutations', 'gamma']
44017};
44018
44019
44020/***/ }),
44021/* 314 */
44022/***/ (function(module, exports) {
44023
44024module.exports = {
44025 'name': 'gamma',
44026 'category': 'Probability',
44027 'syntax': [
44028 'gamma(n)'
44029 ],
44030 'description': 'Compute the gamma function. For small values, the Lanczos approximation is used, and for large values the extended Stirling approximation.',
44031 'examples': [
44032 'gamma(4)',
44033 '3!',
44034 'gamma(1/2)',
44035 'sqrt(pi)'
44036 ],
44037 'seealso': ['factorial']
44038};
44039
44040
44041/***/ }),
44042/* 315 */
44043/***/ (function(module, exports) {
44044
44045module.exports = {
44046 'name': 'kldivergence',
44047 'category': 'Probability',
44048 'syntax': [
44049 'kldivergence(x, y)'
44050 ],
44051 'description': 'Calculate the Kullback-Leibler (KL) divergence between two distributions.',
44052 'examples': [
44053 'kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5])'
44054 ],
44055 'seealso': []
44056};
44057
44058
44059/***/ }),
44060/* 316 */
44061/***/ (function(module, exports) {
44062
44063module.exports = {
44064 'name': 'multinomial',
44065 'category': 'Probability',
44066 'syntax': [
44067 'multinomial(A)'
44068 ],
44069 '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.',
44070 'examples': [
44071 'multinomial([1, 2, 1])'
44072 ],
44073 'seealso': ['combinations', 'factorial']
44074};
44075
44076/***/ }),
44077/* 317 */
44078/***/ (function(module, exports) {
44079
44080module.exports = {
44081 'name': 'permutations',
44082 'category': 'Probability',
44083 'syntax': [
44084 'permutations(n)',
44085 'permutations(n, k)'
44086 ],
44087 'description': 'Compute the number of permutations of n items taken k at a time',
44088 'examples': [
44089 'permutations(5)',
44090 'permutations(5, 3)'
44091 ],
44092 'seealso': ['combinations', 'factorial']
44093};
44094
44095
44096/***/ }),
44097/* 318 */
44098/***/ (function(module, exports) {
44099
44100module.exports = {
44101 'name': 'pickRandom',
44102 'category': 'Probability',
44103 'syntax': [
44104 'pickRandom(array)',
44105 'pickRandom(array, number)',
44106 'pickRandom(array, weights)',
44107 'pickRandom(array, number, weights)',
44108 'pickRandom(array, weights, number)'
44109 ],
44110 'description':
44111 'Pick a random entry from a given array.',
44112 'examples': [
44113 'pickRandom(0:10)',
44114 'pickRandom([1, 3, 1, 6])',
44115 'pickRandom([1, 3, 1, 6], 2)',
44116 'pickRandom([1, 3, 1, 6], [2, 3, 2, 1])',
44117 'pickRandom([1, 3, 1, 6], 2, [2, 3, 2, 1])',
44118 'pickRandom([1, 3, 1, 6], [2, 3, 2, 1], 2)'
44119 ],
44120 'seealso': ['random', 'randomInt']
44121};
44122
44123
44124/***/ }),
44125/* 319 */
44126/***/ (function(module, exports) {
44127
44128module.exports = {
44129 'name': 'random',
44130 'category': 'Probability',
44131 'syntax': [
44132 'random()',
44133 'random(max)',
44134 'random(min, max)',
44135 'random(size)',
44136 'random(size, max)',
44137 'random(size, min, max)'
44138 ],
44139 'description':
44140 'Return a random number.',
44141 'examples': [
44142 'random()',
44143 'random(10, 20)',
44144 'random([2, 3])'
44145 ],
44146 'seealso': ['pickRandom', 'randomInt']
44147};
44148
44149
44150/***/ }),
44151/* 320 */
44152/***/ (function(module, exports) {
44153
44154module.exports = {
44155 'name': 'randomInt',
44156 'category': 'Probability',
44157 'syntax': [
44158 'randomInt(max)',
44159 'randomInt(min, max)',
44160 'randomInt(size)',
44161 'randomInt(size, max)',
44162 'randomInt(size, min, max)'
44163 ],
44164 'description':
44165 'Return a random integer number',
44166 'examples': [
44167 'randomInt(10, 20)',
44168 'randomInt([2, 3], 10)'
44169 ],
44170 'seealso': ['pickRandom', 'random']
44171};
44172
44173/***/ }),
44174/* 321 */
44175/***/ (function(module, exports) {
44176
44177module.exports = {
44178 'name': 'compare',
44179 'category': 'Relational',
44180 'syntax': [
44181 'compare(x, y)'
44182 ],
44183 'description':
44184 'Compare two values. Returns 1 if x is larger than y, -1 if x is smaller than y, and 0 if x and y are equal.',
44185 'examples': [
44186 'compare(2, 3)',
44187 'compare(3, 2)',
44188 'compare(2, 2)',
44189 'compare(5cm, 40mm)',
44190 'compare(2, [1, 2, 3])'
44191 ],
44192 'seealso': [
44193 'equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compareNatural'
44194 ]
44195};
44196
44197
44198/***/ }),
44199/* 322 */
44200/***/ (function(module, exports) {
44201
44202module.exports = {
44203 'name': 'compareNatural',
44204 'category': 'Relational',
44205 'syntax': [
44206 'compareNatural(x, y)'
44207 ],
44208 'description': 'Compare two values of any type in a deterministic, natural way.',
44209 'examples': [
44210 'compareNatural(2, 3)',
44211 'compareNatural(3, 2)',
44212 'compareNatural(2, 2)',
44213 'compareNatural(5cm, 40mm)',
44214 'compareNatural("2", "10")',
44215 'compareNatural(2 + 3i, 2 + 4i)',
44216 'compareNatural([1, 2, 4], [1, 2, 3])',
44217 'compareNatural([1, 5], [1, 2, 3])',
44218 'compareNatural([1, 2], [1, 2])',
44219 'compareNatural({a: 2}, {a: 4})'
44220 ],
44221 'seealso': [
44222 'equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compare'
44223 ]
44224};
44225
44226
44227/***/ }),
44228/* 323 */
44229/***/ (function(module, exports) {
44230
44231module.exports = {
44232 'name': 'deepEqual',
44233 'category': 'Relational',
44234 'syntax': [
44235 'deepEqual(x, y)'
44236 ],
44237 'description':
44238 '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.',
44239 'examples': [
44240 'deepEqual([1,3,4], [1,3,4])',
44241 'deepEqual([1,3,4], [1,3])'
44242 ],
44243 'seealso': [
44244 'equal', 'unequal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare'
44245 ]
44246};
44247
44248
44249/***/ }),
44250/* 324 */
44251/***/ (function(module, exports) {
44252
44253module.exports = {
44254 'name': 'equal',
44255 'category': 'Relational',
44256 'syntax': [
44257 'x == y',
44258 'equal(x, y)'
44259 ],
44260 'description':
44261 'Check equality of two values. Returns true if the values are equal, and false if not.',
44262 'examples': [
44263 '2+2 == 3',
44264 '2+2 == 4',
44265 'a = 3.2',
44266 'b = 6-2.8',
44267 'a == b',
44268 '50cm == 0.5m'
44269 ],
44270 'seealso': [
44271 'unequal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare', 'deepEqual'
44272 ]
44273};
44274
44275
44276/***/ }),
44277/* 325 */
44278/***/ (function(module, exports) {
44279
44280module.exports = {
44281 'name': 'larger',
44282 'category': 'Relational',
44283 'syntax': [
44284 'x > y',
44285 'larger(x, y)'
44286 ],
44287 'description':
44288 'Check if value x is larger than y. Returns true if x is larger than y, and false if not.',
44289 'examples': [
44290 '2 > 3',
44291 '5 > 2*2',
44292 'a = 3.3',
44293 'b = 6-2.8',
44294 '(a > b)',
44295 '(b < a)',
44296 '5 cm > 2 inch'
44297 ],
44298 'seealso': [
44299 'equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compare'
44300 ]
44301};
44302
44303
44304/***/ }),
44305/* 326 */
44306/***/ (function(module, exports) {
44307
44308module.exports = {
44309 'name': 'largerEq',
44310 'category': 'Relational',
44311 'syntax': [
44312 'x >= y',
44313 'largerEq(x, y)'
44314 ],
44315 'description':
44316 'Check if value x is larger or equal to y. Returns true if x is larger or equal to y, and false if not.',
44317 'examples': [
44318 '2 >= 1+1',
44319 '2 > 1+1',
44320 'a = 3.2',
44321 'b = 6-2.8',
44322 '(a >= b)'
44323 ],
44324 'seealso': [
44325 'equal', 'unequal', 'smallerEq', 'smaller', 'compare'
44326 ]
44327};
44328
44329
44330/***/ }),
44331/* 327 */
44332/***/ (function(module, exports) {
44333
44334module.exports = {
44335 'name': 'smaller',
44336 'category': 'Relational',
44337 'syntax': [
44338 'x < y',
44339 'smaller(x, y)'
44340 ],
44341 'description':
44342 'Check if value x is smaller than value y. Returns true if x is smaller than y, and false if not.',
44343 'examples': [
44344 '2 < 3',
44345 '5 < 2*2',
44346 'a = 3.3',
44347 'b = 6-2.8',
44348 '(a < b)',
44349 '5 cm < 2 inch'
44350 ],
44351 'seealso': [
44352 'equal', 'unequal', 'larger', 'smallerEq', 'largerEq', 'compare'
44353 ]
44354};
44355
44356
44357/***/ }),
44358/* 328 */
44359/***/ (function(module, exports) {
44360
44361module.exports = {
44362 'name': 'smallerEq',
44363 'category': 'Relational',
44364 'syntax': [
44365 'x <= y',
44366 'smallerEq(x, y)'
44367 ],
44368 'description':
44369 'Check if value x is smaller or equal to value y. Returns true if x is smaller than y, and false if not.',
44370 'examples': [
44371 '2 <= 1+1',
44372 '2 < 1+1',
44373 'a = 3.2',
44374 'b = 6-2.8',
44375 '(a <= b)'
44376 ],
44377 'seealso': [
44378 'equal', 'unequal', 'larger', 'smaller', 'largerEq', 'compare'
44379 ]
44380};
44381
44382
44383/***/ }),
44384/* 329 */
44385/***/ (function(module, exports) {
44386
44387module.exports = {
44388 'name': 'unequal',
44389 'category': 'Relational',
44390 'syntax': [
44391 'x != y',
44392 'unequal(x, y)'
44393 ],
44394 'description':
44395 'Check unequality of two values. Returns true if the values are unequal, and false if they are equal.',
44396 'examples': [
44397 '2+2 != 3',
44398 '2+2 != 4',
44399 'a = 3.2',
44400 'b = 6-2.8',
44401 'a != b',
44402 '50cm != 0.5m',
44403 '5 cm != 2 inch'
44404 ],
44405 'seealso': [
44406 'equal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare', 'deepEqual'
44407 ]
44408};
44409
44410
44411/***/ }),
44412/* 330 */
44413/***/ (function(module, exports) {
44414
44415module.exports = {
44416 'name': 'setCartesian',
44417 'category': 'Set',
44418 'syntax': [
44419 'setCartesian(set1, set2)'
44420 ],
44421 'description':
44422 'Create the cartesian product of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
44423 'examples': [
44424 'setCartesian([1, 2], [3, 4])'
44425 ],
44426 'seealso': [
44427 'setUnion', 'setIntersect', 'setDifference', 'setPowerset'
44428 ]
44429};
44430
44431
44432/***/ }),
44433/* 331 */
44434/***/ (function(module, exports) {
44435
44436module.exports = {
44437 'name': 'setDifference',
44438 'category': 'Set',
44439 'syntax': [
44440 'setDifference(set1, set2)'
44441 ],
44442 'description':
44443 '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.',
44444 'examples': [
44445 'setDifference([1, 2, 3, 4], [3, 4, 5, 6])',
44446 'setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])'
44447 ],
44448 'seealso': [
44449 'setUnion', 'setIntersect', 'setSymDifference'
44450 ]
44451};
44452
44453
44454/***/ }),
44455/* 332 */
44456/***/ (function(module, exports) {
44457
44458module.exports = {
44459 'name': 'setDistinct',
44460 'category': 'Set',
44461 'syntax': [
44462 'setDistinct(set)'
44463 ],
44464 'description':
44465 'Collect the distinct elements of a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.',
44466 'examples': [
44467 'setDistinct([1, 1, 1, 2, 2, 3])'
44468 ],
44469 'seealso': [
44470 'setMultiplicity'
44471 ]
44472};
44473
44474
44475/***/ }),
44476/* 333 */
44477/***/ (function(module, exports) {
44478
44479module.exports = {
44480 'name': 'setIntersect',
44481 'category': 'Set',
44482 'syntax': [
44483 'setIntersect(set1, set2)'
44484 ],
44485 'description':
44486 'Create the intersection of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
44487 'examples': [
44488 'setIntersect([1, 2, 3, 4], [3, 4, 5, 6])',
44489 'setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]])'
44490 ],
44491 'seealso': [
44492 'setUnion', 'setDifference'
44493 ]
44494};
44495
44496
44497/***/ }),
44498/* 334 */
44499/***/ (function(module, exports) {
44500
44501module.exports = {
44502 'name': 'setIsSubset',
44503 'category': 'Set',
44504 'syntax': [
44505 'setIsSubset(set1, set2)'
44506 ],
44507 'description':
44508 '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.',
44509 'examples': [
44510 'setIsSubset([1, 2], [3, 4, 5, 6])',
44511 'setIsSubset([3, 4], [3, 4, 5, 6])'
44512 ],
44513 'seealso': [
44514 'setUnion', 'setIntersect', 'setDifference'
44515 ]
44516};
44517
44518
44519/***/ }),
44520/* 335 */
44521/***/ (function(module, exports) {
44522
44523module.exports = {
44524 'name': 'setMultiplicity',
44525 'category': 'Set',
44526 'syntax': [
44527 'setMultiplicity(element, set)'
44528 ],
44529 'description':
44530 'Count the multiplicity of an element in a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.',
44531 'examples': [
44532 'setMultiplicity(1, [1, 2, 2, 4])',
44533 'setMultiplicity(2, [1, 2, 2, 4])'
44534 ],
44535 'seealso': [
44536 'setDistinct', 'setSize'
44537 ]
44538};
44539
44540
44541/***/ }),
44542/* 336 */
44543/***/ (function(module, exports) {
44544
44545module.exports = {
44546 'name': 'setPowerset',
44547 'category': 'Set',
44548 'syntax': [
44549 'setPowerset(set)'
44550 ],
44551 'description':
44552 '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.',
44553 'examples': [
44554 'setPowerset([1, 2, 3])'
44555 ],
44556 'seealso': [
44557 'setCartesian'
44558 ]
44559};
44560
44561
44562/***/ }),
44563/* 337 */
44564/***/ (function(module, exports) {
44565
44566module.exports = {
44567 'name': 'setSize',
44568 'category': 'Set',
44569 'syntax': [
44570 'setSize(set)',
44571 'setSize(set, unique)'
44572 ],
44573 'description':
44574 '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.',
44575 'examples': [
44576 'setSize([1, 2, 2, 4])',
44577 'setSize([1, 2, 2, 4], true)'
44578 ],
44579 'seealso': [
44580 'setUnion', 'setIntersect', 'setDifference'
44581 ]
44582};
44583
44584
44585/***/ }),
44586/* 338 */
44587/***/ (function(module, exports) {
44588
44589module.exports = {
44590 'name': 'setSymDifference',
44591 'category': 'Set',
44592 'syntax': [
44593 'setSymDifference(set1, set2)'
44594 ],
44595 'description':
44596 'Create the symmetric difference of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
44597 'examples': [
44598 'setSymDifference([1, 2, 3, 4], [3, 4, 5, 6])',
44599 'setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])'
44600 ],
44601 'seealso': [
44602 'setUnion', 'setIntersect', 'setDifference'
44603 ]
44604};
44605
44606
44607/***/ }),
44608/* 339 */
44609/***/ (function(module, exports) {
44610
44611module.exports = {
44612 'name': 'setUnion',
44613 'category': 'Set',
44614 'syntax': [
44615 'setUnion(set1, set2)'
44616 ],
44617 'description':
44618 'Create the union of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
44619 'examples': [
44620 'setUnion([1, 2, 3, 4], [3, 4, 5, 6])',
44621 'setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]])'
44622 ],
44623 'seealso': [
44624 'setIntersect', 'setDifference'
44625 ]
44626};
44627
44628
44629/***/ }),
44630/* 340 */
44631/***/ (function(module, exports) {
44632
44633module.exports = {
44634 'name': 'erf',
44635 'category': 'Special',
44636 'syntax': [
44637 'erf(x)'
44638 ],
44639 'description': 'Compute the erf function of a value using a rational Chebyshev approximations for different intervals of x',
44640 'examples': [
44641 'erf(0.2)',
44642 'erf(-0.5)',
44643 'erf(4)'
44644 ],
44645 'seealso': []
44646};
44647
44648
44649/***/ }),
44650/* 341 */
44651/***/ (function(module, exports) {
44652
44653module.exports = {
44654 'name': 'mad',
44655 'category': 'Statistics',
44656 'syntax': [
44657 'mad(a, b, c, ...)',
44658 'mad(A)'
44659 ],
44660 '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.',
44661 'examples': [
44662 'mad(10, 20, 30)',
44663 'mad([1, 2, 3])'
44664 ],
44665 'seealso': [
44666 'mean',
44667 'median',
44668 'std',
44669 'abs'
44670 ]
44671};
44672
44673
44674/***/ }),
44675/* 342 */
44676/***/ (function(module, exports) {
44677
44678module.exports = {
44679 'name': 'max',
44680 'category': 'Statistics',
44681 'syntax': [
44682 'max(a, b, c, ...)',
44683 'max(A)',
44684 'max(A, dim)'
44685 ],
44686 'description': 'Compute the maximum value of a list of values.',
44687 'examples': [
44688 'max(2, 3, 4, 1)',
44689 'max([2, 3, 4, 1])',
44690 'max([2, 5; 4, 3])',
44691 'max([2, 5; 4, 3], 1)',
44692 'max([2, 5; 4, 3], 2)',
44693 'max(2.7, 7.1, -4.5, 2.0, 4.1)',
44694 'min(2.7, 7.1, -4.5, 2.0, 4.1)'
44695 ],
44696 'seealso': [
44697 'mean',
44698 'median',
44699 'min',
44700 'prod',
44701 'std',
44702 'sum',
44703 'var'
44704 ]
44705};
44706
44707
44708/***/ }),
44709/* 343 */
44710/***/ (function(module, exports) {
44711
44712module.exports = {
44713 'name': 'mean',
44714 'category': 'Statistics',
44715 'syntax': [
44716 'mean(a, b, c, ...)',
44717 'mean(A)',
44718 'mean(A, dim)'
44719 ],
44720 'description': 'Compute the arithmetic mean of a list of values.',
44721 'examples': [
44722 'mean(2, 3, 4, 1)',
44723 'mean([2, 3, 4, 1])',
44724 'mean([2, 5; 4, 3])',
44725 'mean([2, 5; 4, 3], 1)',
44726 'mean([2, 5; 4, 3], 2)',
44727 'mean([1.0, 2.7, 3.2, 4.0])'
44728 ],
44729 'seealso': [
44730 'max',
44731 'median',
44732 'min',
44733 'prod',
44734 'std',
44735 'sum',
44736 'var'
44737 ]
44738};
44739
44740
44741/***/ }),
44742/* 344 */
44743/***/ (function(module, exports) {
44744
44745module.exports = {
44746 'name': 'median',
44747 'category': 'Statistics',
44748 'syntax': [
44749 'median(a, b, c, ...)',
44750 'median(A)'
44751 ],
44752 '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.',
44753 'examples': [
44754 'median(5, 2, 7)',
44755 'median([3, -1, 5, 7])'
44756 ],
44757 'seealso': [
44758 'max',
44759 'mean',
44760 'min',
44761 'prod',
44762 'std',
44763 'sum',
44764 'var',
44765 'quantileSeq'
44766 ]
44767};
44768
44769
44770/***/ }),
44771/* 345 */
44772/***/ (function(module, exports) {
44773
44774module.exports = {
44775 'name': 'min',
44776 'category': 'Statistics',
44777 'syntax': [
44778 'min(a, b, c, ...)',
44779 'min(A)',
44780 'min(A, dim)'
44781 ],
44782 'description': 'Compute the minimum value of a list of values.',
44783 'examples': [
44784 'min(2, 3, 4, 1)',
44785 'min([2, 3, 4, 1])',
44786 'min([2, 5; 4, 3])',
44787 'min([2, 5; 4, 3], 1)',
44788 'min([2, 5; 4, 3], 2)',
44789 'min(2.7, 7.1, -4.5, 2.0, 4.1)',
44790 'max(2.7, 7.1, -4.5, 2.0, 4.1)'
44791 ],
44792 'seealso': [
44793 'max',
44794 'mean',
44795 'median',
44796 'prod',
44797 'std',
44798 'sum',
44799 'var'
44800 ]
44801};
44802
44803
44804/***/ }),
44805/* 346 */
44806/***/ (function(module, exports) {
44807
44808module.exports = {
44809 'name': 'mode',
44810 'category': 'Statistics',
44811 'syntax': [
44812 'mode(a, b, c, ...)',
44813 'mode(A)',
44814 'mode(A, a, b, B, c, ...)'
44815 ],
44816 'description': 'Computes the mode of all values as an array. In case mode being more than one, multiple values are returned in an array.',
44817 'examples': [
44818 'mode(2, 1, 4, 3, 1)',
44819 'mode([1, 2.7, 3.2, 4, 2.7])',
44820 'mode(1, 4, 6, 1, 6)'
44821 ],
44822 'seealso': [
44823 'max',
44824 'mean',
44825 'min',
44826 'median',
44827 'prod',
44828 'std',
44829 'sum',
44830 'var'
44831 ]
44832};
44833
44834
44835/***/ }),
44836/* 347 */
44837/***/ (function(module, exports) {
44838
44839module.exports = {
44840 'name': 'prod',
44841 'category': 'Statistics',
44842 'syntax': [
44843 'prod(a, b, c, ...)',
44844 'prod(A)'
44845 ],
44846 'description': 'Compute the product of all values.',
44847 'examples': [
44848 'prod(2, 3, 4)',
44849 'prod([2, 3, 4])',
44850 'prod([2, 5; 4, 3])'
44851 ],
44852 'seealso': [
44853 'max',
44854 'mean',
44855 'min',
44856 'median',
44857 'min',
44858 'std',
44859 'sum',
44860 'var'
44861 ]
44862};
44863
44864
44865/***/ }),
44866/* 348 */
44867/***/ (function(module, exports) {
44868
44869module.exports = {
44870 'name': 'quantileSeq',
44871 'category': 'Statistics',
44872 'syntax': [
44873 'quantileSeq(A, prob[, sorted])',
44874 'quantileSeq(A, [prob1, prob2, ...][, sorted])',
44875 'quantileSeq(A, N[, sorted])'
44876 ],
44877 '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.',
44878 'examples': [
44879 'quantileSeq([3, -1, 5, 7], 0.5)',
44880 'quantileSeq([3, -1, 5, 7], [1/3, 2/3])',
44881 'quantileSeq([3, -1, 5, 7], 2)',
44882 'quantileSeq([-1, 3, 5, 7], 0.5, true)'
44883 ],
44884 'seealso': [
44885 'mean',
44886 'median',
44887 'min',
44888 'max',
44889 'prod',
44890 'std',
44891 'sum',
44892 'var'
44893 ]
44894};
44895
44896/***/ }),
44897/* 349 */
44898/***/ (function(module, exports) {
44899
44900module.exports = {
44901 'name': 'std',
44902 'category': 'Statistics',
44903 'syntax': [
44904 'std(a, b, c, ...)',
44905 'std(A)',
44906 'std(A, normalization)'
44907 ],
44908 'description': 'Compute the standard deviation of all values, defined as std(A) = sqrt(var(A)). Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',
44909 'examples': [
44910 'std(2, 4, 6)',
44911 'std([2, 4, 6, 8])',
44912 'std([2, 4, 6, 8], "uncorrected")',
44913 'std([2, 4, 6, 8], "biased")',
44914 'std([1, 2, 3; 4, 5, 6])'
44915 ],
44916 'seealso': [
44917 'max',
44918 'mean',
44919 'min',
44920 'median',
44921 'min',
44922 'prod',
44923 'sum',
44924 'var'
44925 ]
44926};
44927
44928
44929/***/ }),
44930/* 350 */
44931/***/ (function(module, exports) {
44932
44933module.exports = {
44934 'name': 'sum',
44935 'category': 'Statistics',
44936 'syntax': [
44937 'sum(a, b, c, ...)',
44938 'sum(A)'
44939 ],
44940 'description': 'Compute the sum of all values.',
44941 'examples': [
44942 'sum(2, 3, 4, 1)',
44943 'sum([2, 3, 4, 1])',
44944 'sum([2, 5; 4, 3])'
44945 ],
44946 'seealso': [
44947 'max',
44948 'mean',
44949 'median',
44950 'min',
44951 'prod',
44952 'std',
44953 'sum',
44954 'var'
44955 ]
44956};
44957
44958
44959/***/ }),
44960/* 351 */
44961/***/ (function(module, exports) {
44962
44963module.exports = {
44964 'name': 'var',
44965 'category': 'Statistics',
44966 'syntax': [
44967 'var(a, b, c, ...)',
44968 'var(A)',
44969 'var(A, normalization)'
44970 ],
44971 'description': 'Compute the variance of all values. Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',
44972 'examples': [
44973 'var(2, 4, 6)',
44974 'var([2, 4, 6, 8])',
44975 'var([2, 4, 6, 8], "uncorrected")',
44976 'var([2, 4, 6, 8], "biased")',
44977 'var([1, 2, 3; 4, 5, 6])'
44978 ],
44979 'seealso': [
44980 'max',
44981 'mean',
44982 'min',
44983 'median',
44984 'min',
44985 'prod',
44986 'std',
44987 'sum'
44988 ]
44989};
44990
44991
44992/***/ }),
44993/* 352 */
44994/***/ (function(module, exports) {
44995
44996module.exports = {
44997 'name': 'acos',
44998 'category': 'Trigonometry',
44999 'syntax': [
45000 'acos(x)'
45001 ],
45002 'description': 'Compute the inverse cosine of a value in radians.',
45003 'examples': [
45004 'acos(0.5)',
45005 'acos(cos(2.3))'
45006 ],
45007 'seealso': [
45008 'cos',
45009 'atan',
45010 'asin'
45011 ]
45012};
45013
45014
45015/***/ }),
45016/* 353 */
45017/***/ (function(module, exports) {
45018
45019module.exports = {
45020 'name': 'acosh',
45021 'category': 'Trigonometry',
45022 'syntax': [
45023 'acosh(x)'
45024 ],
45025 'description': 'Calculate the hyperbolic arccos of a value, defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.',
45026 'examples': [
45027 'acosh(1.5)'
45028 ],
45029 'seealso': [
45030 'cosh',
45031 'asinh',
45032 'atanh'
45033 ]
45034};
45035
45036/***/ }),
45037/* 354 */
45038/***/ (function(module, exports) {
45039
45040module.exports = {
45041 'name': 'acot',
45042 'category': 'Trigonometry',
45043 'syntax': [
45044 'acot(x)'
45045 ],
45046 'description': 'Calculate the inverse cotangent of a value.',
45047 'examples': [
45048 'acot(0.5)',
45049 'acot(cot(0.5))',
45050 'acot(2)'
45051 ],
45052 'seealso': [
45053 'cot',
45054 'atan'
45055 ]
45056};
45057
45058
45059/***/ }),
45060/* 355 */
45061/***/ (function(module, exports) {
45062
45063module.exports = {
45064 'name': 'acoth',
45065 'category': 'Trigonometry',
45066 'syntax': [
45067 'acoth(x)'
45068 ],
45069 'description': 'Calculate the hyperbolic arccotangent of a value, defined as `acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.',
45070 'examples': [
45071 'acoth(2)',
45072 'acoth(0.5)'
45073 ],
45074 'seealso': [
45075 'acsch',
45076 'asech'
45077 ]
45078};
45079
45080/***/ }),
45081/* 356 */
45082/***/ (function(module, exports) {
45083
45084module.exports = {
45085 'name': 'acsc',
45086 'category': 'Trigonometry',
45087 'syntax': [
45088 'acsc(x)'
45089 ],
45090 'description': 'Calculate the inverse cotangent of a value.',
45091 'examples': [
45092 'acsc(2)',
45093 'acsc(csc(0.5))',
45094 'acsc(0.5)'
45095 ],
45096 'seealso': [
45097 'csc',
45098 'asin',
45099 'asec'
45100 ]
45101};
45102
45103
45104/***/ }),
45105/* 357 */
45106/***/ (function(module, exports) {
45107
45108module.exports = {
45109 'name': 'acsch',
45110 'category': 'Trigonometry',
45111 'syntax': [
45112 'acsch(x)'
45113 ],
45114 'description': 'Calculate the hyperbolic arccosecant of a value, defined as `acsch(x) = ln(1/x + sqrt(1/x^2 + 1))`.',
45115 'examples': [
45116 'acsch(0.5)'
45117 ],
45118 'seealso': [
45119 'asech',
45120 'acoth'
45121 ]
45122};
45123
45124
45125/***/ }),
45126/* 358 */
45127/***/ (function(module, exports) {
45128
45129module.exports = {
45130 'name': 'asec',
45131 'category': 'Trigonometry',
45132 'syntax': [
45133 'asec(x)'
45134 ],
45135 'description': 'Calculate the inverse secant of a value.',
45136 'examples': [
45137 'asec(0.5)',
45138 'asec(sec(0.5))',
45139 'asec(2)'
45140 ],
45141 'seealso': [
45142 'acos',
45143 'acot',
45144 'acsc'
45145 ]
45146};
45147
45148
45149/***/ }),
45150/* 359 */
45151/***/ (function(module, exports) {
45152
45153module.exports = {
45154 'name': 'asech',
45155 'category': 'Trigonometry',
45156 'syntax': [
45157 'asech(x)'
45158 ],
45159 'description': 'Calculate the inverse secant of a value.',
45160 'examples': [
45161 'asech(0.5)'
45162 ],
45163 'seealso': [
45164 'acsch',
45165 'acoth'
45166 ]
45167};
45168
45169
45170/***/ }),
45171/* 360 */
45172/***/ (function(module, exports) {
45173
45174module.exports = {
45175 'name': 'asin',
45176 'category': 'Trigonometry',
45177 'syntax': [
45178 'asin(x)'
45179 ],
45180 'description': 'Compute the inverse sine of a value in radians.',
45181 'examples': [
45182 'asin(0.5)',
45183 'asin(sin(0.5))'
45184 ],
45185 'seealso': [
45186 'sin',
45187 'acos',
45188 'atan'
45189 ]
45190};
45191
45192
45193/***/ }),
45194/* 361 */
45195/***/ (function(module, exports) {
45196
45197module.exports = {
45198 'name': 'asinh',
45199 'category': 'Trigonometry',
45200 'syntax': [
45201 'asinh(x)'
45202 ],
45203 'description': 'Calculate the hyperbolic arcsine of a value, defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.',
45204 'examples': [
45205 'asinh(0.5)'
45206 ],
45207 'seealso': [
45208 'acosh',
45209 'atanh'
45210 ]
45211};
45212
45213
45214/***/ }),
45215/* 362 */
45216/***/ (function(module, exports) {
45217
45218module.exports = {
45219 'name': 'atan',
45220 'category': 'Trigonometry',
45221 'syntax': [
45222 'atan(x)'
45223 ],
45224 'description': 'Compute the inverse tangent of a value in radians.',
45225 'examples': [
45226 'atan(0.5)',
45227 'atan(tan(0.5))'
45228 ],
45229 'seealso': [
45230 'tan',
45231 'acos',
45232 'asin'
45233 ]
45234};
45235
45236
45237/***/ }),
45238/* 363 */
45239/***/ (function(module, exports) {
45240
45241module.exports = {
45242 'name': 'atanh',
45243 'category': 'Trigonometry',
45244 'syntax': [
45245 'atanh(x)'
45246 ],
45247 'description': 'Calculate the hyperbolic arctangent of a value, defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.',
45248 'examples': [
45249 'atanh(0.5)'
45250 ],
45251 'seealso': [
45252 'acosh',
45253 'asinh'
45254 ]
45255};
45256
45257
45258/***/ }),
45259/* 364 */
45260/***/ (function(module, exports) {
45261
45262module.exports = {
45263 'name': 'atan2',
45264 'category': 'Trigonometry',
45265 'syntax': [
45266 'atan2(y, x)'
45267 ],
45268 'description':
45269 'Computes the principal value of the arc tangent of y/x in radians.',
45270 'examples': [
45271 'atan2(2, 2) / pi',
45272 'angle = 60 deg in rad',
45273 'x = cos(angle)',
45274 'y = sin(angle)',
45275 'atan2(y, x)'
45276 ],
45277 'seealso': [
45278 'sin',
45279 'cos',
45280 'tan'
45281 ]
45282};
45283
45284
45285/***/ }),
45286/* 365 */
45287/***/ (function(module, exports) {
45288
45289module.exports = {
45290 'name': 'cos',
45291 'category': 'Trigonometry',
45292 'syntax': [
45293 'cos(x)'
45294 ],
45295 'description': 'Compute the cosine of x in radians.',
45296 'examples': [
45297 'cos(2)',
45298 'cos(pi / 4) ^ 2',
45299 'cos(180 deg)',
45300 'cos(60 deg)',
45301 'sin(0.2)^2 + cos(0.2)^2'
45302 ],
45303 'seealso': [
45304 'acos',
45305 'sin',
45306 'tan'
45307 ]
45308};
45309
45310
45311/***/ }),
45312/* 366 */
45313/***/ (function(module, exports) {
45314
45315module.exports = {
45316 'name': 'cosh',
45317 'category': 'Trigonometry',
45318 'syntax': [
45319 'cosh(x)'
45320 ],
45321 'description': 'Compute the hyperbolic cosine of x in radians.',
45322 'examples': [
45323 'cosh(0.5)'
45324 ],
45325 'seealso': [
45326 'sinh',
45327 'tanh',
45328 'coth'
45329 ]
45330};
45331
45332
45333/***/ }),
45334/* 367 */
45335/***/ (function(module, exports) {
45336
45337module.exports = {
45338 'name': 'cot',
45339 'category': 'Trigonometry',
45340 'syntax': [
45341 'cot(x)'
45342 ],
45343 'description': 'Compute the cotangent of x in radians. Defined as 1/tan(x)',
45344 'examples': [
45345 'cot(2)',
45346 '1 / tan(2)'
45347 ],
45348 'seealso': [
45349 'sec',
45350 'csc',
45351 'tan'
45352 ]
45353};
45354
45355
45356/***/ }),
45357/* 368 */
45358/***/ (function(module, exports) {
45359
45360module.exports = {
45361 'name': 'coth',
45362 'category': 'Trigonometry',
45363 'syntax': [
45364 'coth(x)'
45365 ],
45366 'description': 'Compute the hyperbolic cotangent of x in radians.',
45367 'examples': [
45368 'coth(2)',
45369 '1 / tanh(2)'
45370 ],
45371 'seealso': [
45372 'sech',
45373 'csch',
45374 'tanh'
45375 ]
45376};
45377
45378
45379/***/ }),
45380/* 369 */
45381/***/ (function(module, exports) {
45382
45383module.exports = {
45384 'name': 'csc',
45385 'category': 'Trigonometry',
45386 'syntax': [
45387 'csc(x)'
45388 ],
45389 'description': 'Compute the cosecant of x in radians. Defined as 1/sin(x)',
45390 'examples': [
45391 'csc(2)',
45392 '1 / sin(2)'
45393 ],
45394 'seealso': [
45395 'sec',
45396 'cot',
45397 'sin'
45398 ]
45399};
45400
45401
45402/***/ }),
45403/* 370 */
45404/***/ (function(module, exports) {
45405
45406module.exports = {
45407 'name': 'csch',
45408 'category': 'Trigonometry',
45409 'syntax': [
45410 'csch(x)'
45411 ],
45412 'description': 'Compute the hyperbolic cosecant of x in radians. Defined as 1/sinh(x)',
45413 'examples': [
45414 'csch(2)',
45415 '1 / sinh(2)'
45416 ],
45417 'seealso': [
45418 'sech',
45419 'coth',
45420 'sinh'
45421 ]
45422};
45423
45424
45425/***/ }),
45426/* 371 */
45427/***/ (function(module, exports) {
45428
45429module.exports = {
45430 'name': 'sec',
45431 'category': 'Trigonometry',
45432 'syntax': [
45433 'sec(x)'
45434 ],
45435 'description': 'Compute the secant of x in radians. Defined as 1/cos(x)',
45436 'examples': [
45437 'sec(2)',
45438 '1 / cos(2)'
45439 ],
45440 'seealso': [
45441 'cot',
45442 'csc',
45443 'cos'
45444 ]
45445};
45446
45447
45448/***/ }),
45449/* 372 */
45450/***/ (function(module, exports) {
45451
45452module.exports = {
45453 'name': 'sech',
45454 'category': 'Trigonometry',
45455 'syntax': [
45456 'sech(x)'
45457 ],
45458 'description': 'Compute the hyperbolic secant of x in radians. Defined as 1/cosh(x)',
45459 'examples': [
45460 'sech(2)',
45461 '1 / cosh(2)'
45462 ],
45463 'seealso': [
45464 'coth',
45465 'csch',
45466 'cosh'
45467 ]
45468};
45469
45470
45471/***/ }),
45472/* 373 */
45473/***/ (function(module, exports) {
45474
45475module.exports = {
45476 'name': 'sin',
45477 'category': 'Trigonometry',
45478 'syntax': [
45479 'sin(x)'
45480 ],
45481 'description': 'Compute the sine of x in radians.',
45482 'examples': [
45483 'sin(2)',
45484 'sin(pi / 4) ^ 2',
45485 'sin(90 deg)',
45486 'sin(30 deg)',
45487 'sin(0.2)^2 + cos(0.2)^2'
45488 ],
45489 'seealso': [
45490 'asin',
45491 'cos',
45492 'tan'
45493 ]
45494};
45495
45496
45497/***/ }),
45498/* 374 */
45499/***/ (function(module, exports) {
45500
45501module.exports = {
45502 'name': 'sinh',
45503 'category': 'Trigonometry',
45504 'syntax': [
45505 'sinh(x)'
45506 ],
45507 'description': 'Compute the hyperbolic sine of x in radians.',
45508 'examples': [
45509 'sinh(0.5)'
45510 ],
45511 'seealso': [
45512 'cosh',
45513 'tanh'
45514 ]
45515};
45516
45517
45518/***/ }),
45519/* 375 */
45520/***/ (function(module, exports) {
45521
45522module.exports = {
45523 'name': 'tan',
45524 'category': 'Trigonometry',
45525 'syntax': [
45526 'tan(x)'
45527 ],
45528 'description': 'Compute the tangent of x in radians.',
45529 'examples': [
45530 'tan(0.5)',
45531 'sin(0.5) / cos(0.5)',
45532 'tan(pi / 4)',
45533 'tan(45 deg)'
45534 ],
45535 'seealso': [
45536 'atan',
45537 'sin',
45538 'cos'
45539 ]
45540};
45541
45542
45543/***/ }),
45544/* 376 */
45545/***/ (function(module, exports) {
45546
45547module.exports = {
45548 'name': 'tanh',
45549 'category': 'Trigonometry',
45550 'syntax': [
45551 'tanh(x)'
45552 ],
45553 'description': 'Compute the hyperbolic tangent of x in radians.',
45554 'examples': [
45555 'tanh(0.5)',
45556 'sinh(0.5) / cosh(0.5)'
45557 ],
45558 'seealso': [
45559 'sinh',
45560 'cosh'
45561 ]
45562};
45563
45564
45565/***/ }),
45566/* 377 */
45567/***/ (function(module, exports) {
45568
45569module.exports = {
45570 'name': 'to',
45571 'category': 'Units',
45572 'syntax': [
45573 'x to unit',
45574 'to(x, unit)'
45575 ],
45576 'description': 'Change the unit of a value.',
45577 'examples': [
45578 '5 inch to cm',
45579 '3.2kg to g',
45580 '16 bytes in bits'
45581 ],
45582 'seealso': []
45583};
45584
45585
45586/***/ }),
45587/* 378 */
45588/***/ (function(module, exports) {
45589
45590module.exports = {
45591 'name': 'clone',
45592 'category': 'Utils',
45593 'syntax': [
45594 'clone(x)'
45595 ],
45596 'description': 'Clone a variable. Creates a copy of primitive variables,and a deep copy of matrices',
45597 'examples': [
45598 'clone(3.5)',
45599 'clone(2 - 4i)',
45600 'clone(45 deg)',
45601 'clone([1, 2; 3, 4])',
45602 'clone("hello world")'
45603 ],
45604 'seealso': []
45605};
45606
45607
45608/***/ }),
45609/* 379 */
45610/***/ (function(module, exports) {
45611
45612module.exports = {
45613 'name': 'format',
45614 'category': 'Utils',
45615 'syntax': [
45616 'format(value)',
45617 'format(value, precision)'
45618 ],
45619 'description': 'Format a value of any type as string.',
45620 'examples': [
45621 'format(2.3)',
45622 'format(3 - 4i)',
45623 'format([])',
45624 'format(pi, 3)'
45625 ],
45626 'seealso': ['print']
45627};
45628
45629
45630/***/ }),
45631/* 380 */
45632/***/ (function(module, exports) {
45633
45634module.exports = {
45635 'name': 'isNaN',
45636 'category': 'Utils',
45637 'syntax': [
45638 'isNaN(x)'
45639 ],
45640 'description': 'Test whether a value is NaN (not a number)',
45641 'examples': [
45642 'isNaN(2)',
45643 'isNaN(0 / 0)',
45644 'isNaN(NaN)',
45645 'isNaN(Infinity)'
45646 ],
45647 'seealso': ['isNegative', 'isNumeric', 'isPositive', 'isZero']
45648};
45649
45650
45651/***/ }),
45652/* 381 */
45653/***/ (function(module, exports) {
45654
45655module.exports = {
45656 'name': 'isInteger',
45657 'category': 'Utils',
45658 'syntax': [
45659 'isInteger(x)'
45660 ],
45661 'description': 'Test whether a value is an integer number.',
45662 'examples': [
45663 'isInteger(2)',
45664 'isInteger(3.5)',
45665 'isInteger([3, 0.5, -2])'
45666 ],
45667 'seealso': ['isNegative', 'isNumeric', 'isPositive', 'isZero']
45668};
45669
45670
45671/***/ }),
45672/* 382 */
45673/***/ (function(module, exports) {
45674
45675module.exports = {
45676 'name': 'isNegative',
45677 'category': 'Utils',
45678 'syntax': [
45679 'isNegative(x)'
45680 ],
45681 'description': 'Test whether a value is negative: smaller than zero.',
45682 'examples': [
45683 'isNegative(2)',
45684 'isNegative(0)',
45685 'isNegative(-4)',
45686 'isNegative([3, 0.5, -2])'
45687 ],
45688 'seealso': ['isInteger', 'isNumeric', 'isPositive', 'isZero']
45689};
45690
45691
45692/***/ }),
45693/* 383 */
45694/***/ (function(module, exports) {
45695
45696module.exports = {
45697 'name': 'isNumeric',
45698 'category': 'Utils',
45699 'syntax': [
45700 'isNumeric(x)'
45701 ],
45702 'description': 'Test whether a value is a numeric value. ' +
45703 'Returns true when the input is a number, BigNumber, Fraction, or boolean.',
45704 'examples': [
45705 'isNumeric(2)',
45706 'isNumeric(0)',
45707 'isNumeric(bignumber(500))',
45708 'isNumeric(fraction(0.125))',
45709 'isNumeric("3")',
45710 'isNumeric(2 + 3i)',
45711 'isNumeric([2.3, "foo", false])'
45712 ],
45713 'seealso': ['isInteger', 'isZero', 'isNegative', 'isPositive', 'isNaN']
45714};
45715
45716
45717/***/ }),
45718/* 384 */
45719/***/ (function(module, exports) {
45720
45721module.exports = {
45722 'name': 'isPositive',
45723 'category': 'Utils',
45724 'syntax': [
45725 'isPositive(x)'
45726 ],
45727 'description': 'Test whether a value is positive: larger than zero.',
45728 'examples': [
45729 'isPositive(2)',
45730 'isPositive(0)',
45731 'isPositive(-4)',
45732 'isPositive([3, 0.5, -2])'
45733 ],
45734 'seealso': ['isInteger', 'isNumeric', 'isNegative', 'isZero']
45735};
45736
45737
45738/***/ }),
45739/* 385 */
45740/***/ (function(module, exports) {
45741
45742module.exports = {
45743 'name': 'isPrime',
45744 'category': 'Utils',
45745 'syntax': [
45746 'isPrime(x)'
45747 ],
45748 'description': 'Test whether a value is prime: has no divisors other than itself and one.',
45749 'examples': [
45750 'isPrime(3)',
45751 'isPrime(-2)',
45752 'isPrime([2, 17, 100])'
45753 ],
45754 'seealso': ['isInteger', 'isNumeric', 'isNegative', 'isZero']
45755};
45756
45757/***/ }),
45758/* 386 */
45759/***/ (function(module, exports) {
45760
45761module.exports = {
45762 'name': 'isZero',
45763 'category': 'Utils',
45764 'syntax': [
45765 'isZero(x)'
45766 ],
45767 'description': 'Test whether a value is zero.',
45768 'examples': [
45769 'isZero(2)',
45770 'isZero(0)',
45771 'isZero(-4)',
45772 'isZero([3, 0, -2, 0])'
45773 ],
45774 'seealso': ['isInteger', 'isNumeric', 'isNegative', 'isPositive']
45775};
45776
45777
45778/***/ }),
45779/* 387 */
45780/***/ (function(module, exports) {
45781
45782module.exports = {
45783 'name': 'typeof',
45784 'category': 'Utils',
45785 'syntax': [
45786 'typeof(x)'
45787 ],
45788 'description': 'Get the type of a variable.',
45789 'examples': [
45790 'typeof(3.5)',
45791 'typeof(2 - 4i)',
45792 'typeof(45 deg)',
45793 'typeof("hello world")'
45794 ],
45795 'seealso': []
45796};
45797
45798
45799/***/ }),
45800/* 388 */
45801/***/ (function(module, exports, __webpack_require__) {
45802
45803module.exports = [
45804 __webpack_require__(389),
45805 __webpack_require__(391),
45806 __webpack_require__(392),
45807 __webpack_require__(111),
45808 __webpack_require__(112)
45809];
45810
45811
45812/***/ }),
45813/* 389 */
45814/***/ (function(module, exports, __webpack_require__) {
45815
45816"use strict";
45817
45818
45819var deepMap = __webpack_require__(1);
45820
45821function factory (type, config, load, typed) {
45822 var parse = load(__webpack_require__(41));
45823
45824 /**
45825 * Parse and compile an expression.
45826 * Returns a an object with a function `eval([scope])` to evaluate the
45827 * compiled expression.
45828 *
45829 * Syntax:
45830 *
45831 * math.compile(expr) // returns one node
45832 * math.compile([expr1, expr2, expr3, ...]) // returns an array with nodes
45833 *
45834 * Examples:
45835 *
45836 * var code = math.compile('sqrt(3^2 + 4^2)');
45837 * code.eval(); // 5
45838 *
45839 * var scope = {a: 3, b: 4}
45840 * var code = math.compile('a * b'); // 12
45841 * code.eval(scope); // 12
45842 * scope.a = 5;
45843 * code.eval(scope); // 20
45844 *
45845 * var nodes = math.compile(['a = 3', 'b = 4', 'a * b']);
45846 * nodes[2].eval(); // 12
45847 *
45848 * See also:
45849 *
45850 * parse, eval
45851 *
45852 * @param {string | string[] | Array | Matrix} expr
45853 * The expression to be compiled
45854 * @return {{eval: Function} | Array.<{eval: Function}>} code
45855 * An object with the compiled expression
45856 * @throws {Error}
45857 */
45858 return typed('compile', {
45859 'string': function (expr) {
45860 return parse(expr).compile();
45861 },
45862
45863 'Array | Matrix': function (expr) {
45864 return deepMap(expr, function (entry) {
45865 return parse(entry).compile();
45866 });
45867 }
45868 });
45869}
45870
45871exports.name = 'compile';
45872exports.factory = factory;
45873
45874
45875/***/ }),
45876/* 390 */
45877/***/ (function(module, exports, __webpack_require__) {
45878
45879"use strict";
45880
45881
45882var errorTransform = __webpack_require__(42).transform;
45883var setSafeProperty = __webpack_require__(13).setSafeProperty;
45884
45885function factory (type, config, load, typed) {
45886 var subset = load(__webpack_require__(23));
45887 var matrix = load(__webpack_require__(0));
45888
45889 /**
45890 * Replace part of an object:
45891 *
45892 * - Assign a property to an object
45893 * - Replace a part of a string
45894 * - Replace a matrix subset
45895 *
45896 * @param {Object | Array | Matrix | string} object
45897 * @param {Index} index
45898 * @param {*} value
45899 * @return {Object | Array | Matrix | string} Returns the original object
45900 * except in case of a string
45901 */
45902 // TODO: change assign to return the value instead of the object
45903 return function assign(object, index, value) {
45904 try {
45905 if (Array.isArray(object)) {
45906 return matrix(object).subset(index, value).valueOf();
45907 }
45908 else if (object && typeof object.subset === 'function') { // Matrix
45909 return object.subset(index, value);
45910 }
45911 else if (typeof object === 'string') {
45912 // TODO: move setStringSubset into a separate util file, use that
45913 return subset(object, index, value);
45914 }
45915 else if (typeof object === 'object') {
45916 if (!index.isObjectProperty()) {
45917 throw TypeError('Cannot apply a numeric index as object property');
45918 }
45919 setSafeProperty(object, index.getObjectProperty(), value);
45920 return object;
45921 }
45922 else {
45923 throw new TypeError('Cannot apply index: unsupported type of object');
45924 }
45925 }
45926 catch (err) {
45927 throw errorTransform(err);
45928 }
45929 }
45930}
45931
45932exports.factory = factory;
45933
45934
45935/***/ }),
45936/* 391 */
45937/***/ (function(module, exports, __webpack_require__) {
45938
45939"use strict";
45940
45941
45942var deepMap = __webpack_require__(1);
45943
45944function factory (type, config, load, typed) {
45945 var parse = load(__webpack_require__(41));
45946
45947 /**
45948 * Evaluate an expression.
45949 *
45950 * Note the evaluating arbitrary expressions may involve security risks,
45951 * see [http://mathjs.org/docs/expressions/security.html](http://mathjs.org/docs/expressions/security.html) for more information.
45952 *
45953 * Syntax:
45954 *
45955 * math.eval(expr)
45956 * math.eval(expr, scope)
45957 * math.eval([expr1, expr2, expr3, ...])
45958 * math.eval([expr1, expr2, expr3, ...], scope)
45959 *
45960 * Example:
45961 *
45962 * math.eval('(2+3)/4'); // 1.25
45963 * math.eval('sqrt(3^2 + 4^2)'); // 5
45964 * math.eval('sqrt(-4)'); // 2i
45965 * math.eval(['a=3', 'b=4', 'a*b']);, // [3, 4, 12]
45966 *
45967 * var scope = {a:3, b:4};
45968 * math.eval('a * b', scope); // 12
45969 *
45970 * See also:
45971 *
45972 * parse, compile
45973 *
45974 * @param {string | string[] | Matrix} expr The expression to be evaluated
45975 * @param {Object} [scope] Scope to read/write variables
45976 * @return {*} The result of the expression
45977 * @throws {Error}
45978 */
45979 return typed('compile', {
45980 'string': function (expr) {
45981 var scope = {};
45982 return parse(expr).compile().eval(scope);
45983 },
45984
45985 'string, Object': function (expr, scope) {
45986 return parse(expr).compile().eval(scope);
45987 },
45988
45989 'Array | Matrix': function (expr) {
45990 var scope = {};
45991 return deepMap(expr, function (entry) {
45992 return parse(entry).compile().eval(scope);
45993 });
45994 },
45995
45996 'Array | Matrix, Object': function (expr, scope) {
45997 return deepMap(expr, function (entry) {
45998 return parse(entry).compile().eval(scope);
45999 });
46000 }
46001 });
46002}
46003
46004exports.name = 'eval';
46005exports.factory = factory;
46006
46007/***/ }),
46008/* 392 */
46009/***/ (function(module, exports, __webpack_require__) {
46010
46011"use strict";
46012
46013
46014var getSafeProperty = __webpack_require__(13).getSafeProperty;
46015
46016function factory (type, config, load, typed, math) {
46017 var docs = load(__webpack_require__(100));
46018
46019 /**
46020 * Retrieve help on a function or data type.
46021 * Help files are retrieved from the documentation in math.expression.docs.
46022 *
46023 * Syntax:
46024 *
46025 * math.help(search)
46026 *
46027 * Examples:
46028 *
46029 * console.log(math.help('sin').toString());
46030 * console.log(math.help(math.add).toString());
46031 * console.log(math.help(math.add).toJSON());
46032 *
46033 * @param {Function | string | Object} search A function or function name
46034 * for which to get help
46035 * @return {Help} A help object
46036 */
46037 return typed('help', {
46038 'any': function (search) {
46039 var prop;
46040 var name = search;
46041
46042 if (typeof search !== 'string') {
46043 for (prop in math) {
46044 // search in functions and constants
46045 if (math.hasOwnProperty(prop) && (search === math[prop])) {
46046 name = prop;
46047 break;
46048 }
46049 }
46050
46051 /* TODO: implement help for data types
46052 if (!text) {
46053 // search data type
46054 for (prop in math.type) {
46055 if (math.type.hasOwnProperty(prop)) {
46056 if (search === math.type[prop]) {
46057 text = prop;
46058 break;
46059 }
46060 }
46061 }
46062 }
46063 */
46064 }
46065
46066 var doc = getSafeProperty(docs, name);
46067 if (!doc) {
46068 throw new Error('No documentation found on "' + name + '"');
46069 }
46070 return new type.Help(doc);
46071 }
46072 });
46073}
46074
46075exports.math = true; // request access to the math namespace as 5th argument of the factory function
46076exports.name = 'help';
46077exports.factory = factory;
46078
46079
46080/***/ }),
46081/* 393 */
46082/***/ (function(module, exports, __webpack_require__) {
46083
46084module.exports = [
46085 __webpack_require__(103),
46086 __webpack_require__(80),
46087 __webpack_require__(105),
46088 __webpack_require__(106),
46089 __webpack_require__(107),
46090 __webpack_require__(47),
46091 __webpack_require__(78),
46092 __webpack_require__(108),
46093 __webpack_require__(56),
46094 __webpack_require__(15),
46095 __webpack_require__(110),
46096 __webpack_require__(55),
46097 __webpack_require__(63),
46098 __webpack_require__(79),
46099 __webpack_require__(36),
46100 __webpack_require__(394)
46101];
46102
46103
46104/***/ }),
46105/* 394 */
46106/***/ (function(module, exports, __webpack_require__) {
46107
46108"use strict";
46109
46110
46111function factory (type, config, load, typed) {
46112 /**
46113 * @constructor UpdateNode
46114 */
46115 function UpdateNode() {
46116 // TODO: deprecated since v3. Cleanup some day
46117 throw new Error('UpdateNode is deprecated. Use AssignmentNode instead.');
46118 }
46119
46120 return UpdateNode;
46121}
46122
46123exports.name = 'UpdateNode';
46124exports.path = 'expression.node';
46125exports.factory = factory;
46126
46127
46128/***/ }),
46129/* 395 */
46130/***/ (function(module, exports, __webpack_require__) {
46131
46132module.exports = [
46133 __webpack_require__(396),
46134 __webpack_require__(397),
46135 __webpack_require__(398),
46136 __webpack_require__(399),
46137 __webpack_require__(400),
46138 __webpack_require__(401),
46139 __webpack_require__(402),
46140 __webpack_require__(403),
46141 __webpack_require__(404),
46142 __webpack_require__(405)
46143];
46144
46145
46146/***/ }),
46147/* 396 */
46148/***/ (function(module, exports, __webpack_require__) {
46149
46150"use strict";
46151
46152
46153var errorTransform = __webpack_require__(42).transform;
46154
46155/**
46156 * Attach a transform function to math.range
46157 * Adds a property transform containing the transform function.
46158 *
46159 * This transform changed the last `dim` parameter of function concat
46160 * from one-based to zero based
46161 */
46162function factory (type, config, load, typed) {
46163 var concat = load(__webpack_require__(64));
46164
46165 // @see: comment of concat itself
46166 return typed('concat', {
46167 '...any': function (args) {
46168 // change last argument from one-based to zero-based
46169 var lastIndex = args.length - 1;
46170 var last = args[lastIndex];
46171 if (type.isNumber(last)) {
46172 args[lastIndex] = last - 1;
46173 }
46174 else if (type.isBigNumber(last)) {
46175 args[lastIndex] = last.minus(1);
46176 }
46177
46178 try {
46179 return concat.apply(null, args);
46180 }
46181 catch (err) {
46182 throw errorTransform(err);
46183 }
46184 }
46185 });
46186}
46187
46188exports.name = 'concat';
46189exports.path = 'expression.transform';
46190exports.factory = factory;
46191
46192
46193/***/ }),
46194/* 397 */
46195/***/ (function(module, exports, __webpack_require__) {
46196
46197"use strict";
46198
46199
46200var filter = __webpack_require__(2).filter;
46201var filterRegExp = __webpack_require__(2).filterRegExp;
46202var maxArgumentCount = __webpack_require__(32).maxArgumentCount;
46203
46204/**
46205 * Attach a transform function to math.filter
46206 * Adds a property transform containing the transform function.
46207 *
46208 * This transform adds support for equations as test function for math.filter,
46209 * so you can do something like 'filter([3, -2, 5], x > 0)'.
46210 */
46211function factory (type, config, load, typed) {
46212 var compileInlineExpression = load(__webpack_require__(81));
46213 var matrix = load(__webpack_require__(0));
46214
46215 function filterTransform(args, math, scope) {
46216 var x, callback;
46217
46218 if (args[0]) {
46219 x = args[0].compile().eval(scope);
46220 }
46221
46222 if (args[1]) {
46223 if (type.isSymbolNode(args[1]) || type.isFunctionAssignmentNode(args[1])) {
46224 // a function pointer, like filter([3, -2, 5], myTestFunction);
46225 callback = args[1].compile().eval(scope);
46226 }
46227 else {
46228 // an expression like filter([3, -2, 5], x > 0)
46229 callback = compileInlineExpression(args[1], math, scope);
46230 }
46231 }
46232
46233 return filter(x, callback);
46234 }
46235 filterTransform.rawArgs = true;
46236
46237 // one based version of function filter
46238 var filter = typed('filter', {
46239 'Array, function': _filter,
46240
46241 'Matrix, function': function (x, test) {
46242 return matrix(_filter(x.toArray(), test));
46243 },
46244
46245 'Array, RegExp': filterRegExp,
46246
46247 'Matrix, RegExp': function (x, test) {
46248 return matrix(filterRegExp(x.toArray(), test));
46249 }
46250 });
46251
46252 filter.toTex = undefined; // use default template
46253
46254 return filterTransform;
46255}
46256
46257/**
46258 * Filter values in a callback given a callback function
46259 *
46260 * !!! Passes a one-based index !!!
46261 *
46262 * @param {Array} x
46263 * @param {Function} callback
46264 * @return {Array} Returns the filtered array
46265 * @private
46266 */
46267function _filter (x, callback) {
46268 // figure out what number of arguments the callback function expects
46269 var args = maxArgumentCount(callback);
46270
46271 return filter(x, function (value, index, array) {
46272 // invoke the callback function with the right number of arguments
46273 if (args === 1) {
46274 return callback(value);
46275 }
46276 else if (args === 2) {
46277 return callback(value, [index + 1]);
46278 }
46279 else { // 3 or -1
46280 return callback(value, [index + 1], array);
46281 }
46282 });
46283}
46284
46285exports.name = 'filter';
46286exports.path = 'expression.transform';
46287exports.factory = factory;
46288
46289
46290/***/ }),
46291/* 398 */
46292/***/ (function(module, exports, __webpack_require__) {
46293
46294"use strict";
46295
46296
46297var maxArgumentCount = __webpack_require__(32).maxArgumentCount;
46298var forEach = __webpack_require__(2).forEach;
46299
46300/**
46301 * Attach a transform function to math.forEach
46302 * Adds a property transform containing the transform function.
46303 *
46304 * This transform creates a one-based index instead of a zero-based index
46305 */
46306function factory (type, config, load, typed) {
46307 var compileInlineExpression = load(__webpack_require__(81));
46308
46309 function forEachTransform(args, math, scope) {
46310 var x, callback;
46311
46312 if (args[0]) {
46313 x = args[0].compile().eval(scope);
46314 }
46315
46316 if (args[1]) {
46317 if (type.isSymbolNode(args[1]) || type.isFunctionAssignmentNode(args[1])) {
46318 // a function pointer, like forEach([3, -2, 5], myTestFunction);
46319 callback = args[1].compile().eval(scope);
46320 }
46321 else {
46322 // an expression like forEach([3, -2, 5], x > 0 ? callback1(x) : callback2(x) )
46323 callback = compileInlineExpression(args[1], math, scope);
46324 }
46325 }
46326
46327 return _forEach(x, callback);
46328 }
46329 forEachTransform.rawArgs = true;
46330
46331 // one-based version of forEach
46332 var _forEach = typed('forEach', {
46333 'Array | Matrix, function': function (array, callback) {
46334 // figure out what number of arguments the callback function expects
46335 var args = maxArgumentCount(callback);
46336
46337 var recurse = function (value, index) {
46338 if (Array.isArray(value)) {
46339 forEach(value, function (child, i) {
46340 // we create a copy of the index array and append the new index value
46341 recurse(child, index.concat(i + 1)); // one based index, hence i+1
46342 });
46343 }
46344 else {
46345 // invoke the callback function with the right number of arguments
46346 if (args === 1) {
46347 callback(value);
46348 }
46349 else if (args === 2) {
46350 callback(value, index);
46351 }
46352 else { // 3 or -1
46353 callback(value, index, array);
46354 }
46355 }
46356 };
46357 recurse(array.valueOf(), []); // pass Array
46358 }
46359 });
46360
46361 return forEachTransform;
46362}
46363
46364exports.name = 'forEach';
46365exports.path = 'expression.transform';
46366exports.factory = factory;
46367
46368
46369/***/ }),
46370/* 399 */
46371/***/ (function(module, exports, __webpack_require__) {
46372
46373"use strict";
46374
46375
46376/**
46377 * Attach a transform function to math.index
46378 * Adds a property transform containing the transform function.
46379 *
46380 * This transform creates a one-based index instead of a zero-based index
46381 */
46382function factory (type, config, load) {
46383
46384 return function indexTransform() {
46385 var args = [];
46386 for (var i = 0, ii = arguments.length; i < ii; i++) {
46387 var arg = arguments[i];
46388
46389 // change from one-based to zero based, and convert BigNumber to number
46390 if (type.isRange(arg)) {
46391 arg.start--;
46392 arg.end -= (arg.step > 0 ? 0 : 2);
46393 }
46394 else if (arg && arg.isSet === true) {
46395 arg = arg.map(function (v) { return v - 1; });
46396 }
46397 else if (type.isArray(arg) || type.isMatrix(arg)) {
46398 arg = arg.map(function (v) { return v - 1; });
46399 }
46400 else if (type.isNumber(arg)) {
46401 arg--;
46402 }
46403 else if (type.isBigNumber(arg)) {
46404 arg = arg.toNumber() - 1;
46405 }
46406 else if (typeof arg === 'string') {
46407 // leave as is
46408 }
46409 else {
46410 throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range');
46411 }
46412
46413 args[i] = arg;
46414 }
46415
46416 var res = new type.Index();
46417 type.Index.apply(res, args);
46418 return res;
46419 };
46420}
46421
46422exports.name = 'index';
46423exports.path = 'expression.transform';
46424exports.factory = factory;
46425
46426
46427/***/ }),
46428/* 400 */
46429/***/ (function(module, exports, __webpack_require__) {
46430
46431"use strict";
46432
46433
46434var maxArgumentCount = __webpack_require__(32).maxArgumentCount;
46435var map = __webpack_require__(2).map;
46436
46437/**
46438 * Attach a transform function to math.map
46439 * Adds a property transform containing the transform function.
46440 *
46441 * This transform creates a one-based index instead of a zero-based index
46442 */
46443function factory (type, config, load, typed) {
46444 var compileInlineExpression = load(__webpack_require__(81));
46445 var matrix = load(__webpack_require__(0));
46446
46447 function mapTransform(args, math, scope) {
46448 var x, callback;
46449
46450 if (args[0]) {
46451 x = args[0].compile().eval(scope);
46452 }
46453
46454 if (args[1]) {
46455 if (type.isSymbolNode(args[1]) || type.isFunctionAssignmentNode(args[1])) {
46456 // a function pointer, like filter([3, -2, 5], myTestFunction);
46457 callback = args[1].compile().eval(scope);
46458 }
46459 else {
46460 // an expression like filter([3, -2, 5], x > 0)
46461 callback = compileInlineExpression(args[1], math, scope);
46462 }
46463 }
46464
46465 return map(x, callback);
46466 }
46467 mapTransform.rawArgs = true;
46468
46469 // one-based version of map function
46470 var map = typed('map', {
46471 'Array, function': function (x, callback) {
46472 return _map(x, callback, x);
46473 },
46474
46475 'Matrix, function': function (x, callback) {
46476 return matrix(_map(x.valueOf(), callback, x));
46477 }
46478 });
46479
46480 return mapTransform;
46481}
46482
46483/**
46484 * Map for a multi dimensional array. One-based indexes
46485 * @param {Array} array
46486 * @param {function} callback
46487 * @param {Array} orig
46488 * @return {Array}
46489 * @private
46490 */
46491function _map (array, callback, orig) {
46492 // figure out what number of arguments the callback function expects
46493 var argsCount = maxArgumentCount(callback);
46494
46495 function recurse(value, index) {
46496 if (Array.isArray(value)) {
46497 return map(value, function (child, i) {
46498 // we create a copy of the index array and append the new index value
46499 return recurse(child, index.concat(i + 1)); // one based index, hence i + 1
46500 });
46501 }
46502 else {
46503 // invoke the (typed) callback function with the right number of arguments
46504 if (argsCount === 1) {
46505 return callback(value);
46506 }
46507 else if (argsCount === 2) {
46508 return callback(value, index);
46509 }
46510 else { // 3 or -1
46511 return callback(value, index, orig);
46512 }
46513 }
46514 }
46515
46516 return recurse(array, []);
46517}
46518
46519exports.name = 'map';
46520exports.path = 'expression.transform';
46521exports.factory = factory;
46522
46523
46524/***/ }),
46525/* 401 */
46526/***/ (function(module, exports, __webpack_require__) {
46527
46528"use strict";
46529
46530
46531var errorTransform = __webpack_require__(42).transform;
46532var isCollection = __webpack_require__(48);
46533
46534/**
46535 * Attach a transform function to math.max
46536 * Adds a property transform containing the transform function.
46537 *
46538 * This transform changed the last `dim` parameter of function max
46539 * from one-based to zero based
46540 */
46541function factory (type, config, load, typed) {
46542 var max = load(__webpack_require__(114));
46543
46544 return typed('max', {
46545 '...any': function (args) {
46546 // change last argument dim from one-based to zero-based
46547 if (args.length == 2 && isCollection(args[0])) {
46548 var dim = args[1];
46549 if (type.isNumber(dim)) {
46550 args[1] = dim - 1;
46551 }
46552 else if (type.isBigNumber(dim)) {
46553 args[1] = dim.minus(1);
46554 }
46555 }
46556
46557 try {
46558 return max.apply(null, args);
46559 }
46560 catch (err) {
46561 throw errorTransform(err);
46562 }
46563 }
46564 });
46565}
46566
46567exports.name = 'max';
46568exports.path = 'expression.transform';
46569exports.factory = factory;
46570
46571
46572/***/ }),
46573/* 402 */
46574/***/ (function(module, exports, __webpack_require__) {
46575
46576"use strict";
46577
46578
46579var errorTransform = __webpack_require__(42).transform;
46580var isCollection = __webpack_require__(48);
46581
46582/**
46583 * Attach a transform function to math.mean
46584 * Adds a property transform containing the transform function.
46585 *
46586 * This transform changed the last `dim` parameter of function mean
46587 * from one-based to zero based
46588 */
46589function factory (type, config, load, typed) {
46590 var mean = load(__webpack_require__(115));
46591
46592 return typed('mean', {
46593 '...any': function (args) {
46594 // change last argument dim from one-based to zero-based
46595 if (args.length == 2 && isCollection(args[0])) {
46596 var dim = args[1];
46597 if (type.isNumber(dim)) {
46598 args[1] = dim - 1;
46599 }
46600 else if (type.isBigNumber(dim)) {
46601 args[1] = dim.minus(1);
46602 }
46603 }
46604
46605 try {
46606 return mean.apply(null, args);
46607 }
46608 catch (err) {
46609 throw errorTransform(err);
46610 }
46611 }
46612 });
46613}
46614
46615exports.name = 'mean';
46616exports.path = 'expression.transform';
46617exports.factory = factory;
46618
46619
46620/***/ }),
46621/* 403 */
46622/***/ (function(module, exports, __webpack_require__) {
46623
46624"use strict";
46625
46626
46627var errorTransform = __webpack_require__(42).transform;
46628var isCollection = __webpack_require__(48);
46629
46630/**
46631 * Attach a transform function to math.min
46632 * Adds a property transform containing the transform function.
46633 *
46634 * This transform changed the last `dim` parameter of function min
46635 * from one-based to zero based
46636 */
46637function factory (type, config, load, typed) {
46638 var min = load(__webpack_require__(118));
46639
46640 return typed('min', {
46641 '...any': function (args) {
46642 // change last argument dim from one-based to zero-based
46643 if (args.length == 2 && isCollection(args[0])) {
46644 var dim = args[1];
46645 if (type.isNumber(dim)) {
46646 args[1] = dim - 1;
46647 }
46648 else if (type.isBigNumber(dim)) {
46649 args[1] = dim.minus(1);
46650 }
46651 }
46652
46653 try {
46654 return min.apply(null, args);
46655 }
46656 catch (err) {
46657 throw errorTransform(err);
46658 }
46659 }
46660 });
46661}
46662
46663exports.name = 'min';
46664exports.path = 'expression.transform';
46665exports.factory = factory;
46666
46667
46668/***/ }),
46669/* 404 */
46670/***/ (function(module, exports, __webpack_require__) {
46671
46672"use strict";
46673
46674
46675/**
46676 * Attach a transform function to math.range
46677 * Adds a property transform containing the transform function.
46678 *
46679 * This transform creates a range which includes the end value
46680 */
46681function factory (type, config, load, typed) {
46682 var range = load(__webpack_require__(119));
46683
46684 return typed('range', {
46685 '...any': function (args) {
46686 var lastIndex = args.length - 1;
46687 var last = args[lastIndex];
46688 if (typeof last !== 'boolean') {
46689 // append a parameter includeEnd=true
46690 args.push(true);
46691 }
46692
46693 return range.apply(null, args);
46694 }
46695 });
46696}
46697
46698exports.name = 'range';
46699exports.path = 'expression.transform';
46700exports.factory = factory;
46701
46702
46703/***/ }),
46704/* 405 */
46705/***/ (function(module, exports, __webpack_require__) {
46706
46707"use strict";
46708
46709
46710var errorTransform = __webpack_require__(42).transform;
46711
46712/**
46713 * Attach a transform function to math.subset
46714 * Adds a property transform containing the transform function.
46715 *
46716 * This transform creates a range which includes the end value
46717 */
46718function factory (type, config, load, typed) {
46719 var subset = load(__webpack_require__(23));
46720
46721 return typed('subset', {
46722 '...any': function (args) {
46723 try {
46724 return subset.apply(null, args);
46725 }
46726 catch (err) {
46727 throw errorTransform(err);
46728 }
46729 }
46730 });
46731}
46732
46733exports.name = 'subset';
46734exports.path = 'expression.transform';
46735exports.factory = factory;
46736
46737
46738/***/ }),
46739/* 406 */
46740/***/ (function(module, exports, __webpack_require__) {
46741
46742"use strict";
46743
46744
46745var object = __webpack_require__(5);
46746var string = __webpack_require__(9);
46747
46748function factory (type, config, load, typed) {
46749 var parser = load(__webpack_require__(112))();
46750
46751 /**
46752 * Documentation object
46753 * @param {Object} doc Object containing properties:
46754 * {string} name
46755 * {string} category
46756 * {string} description
46757 * {string[]} syntax
46758 * {string[]} examples
46759 * {string[]} seealso
46760 * @constructor
46761 */
46762 function Help(doc) {
46763 if (!(this instanceof Help)) {
46764 throw new SyntaxError('Constructor must be called with the new operator');
46765 }
46766
46767 if (!doc) throw new Error('Argument "doc" missing');
46768
46769 this.doc = doc;
46770 }
46771
46772 /**
46773 * Attach type information
46774 */
46775 Help.prototype.type = 'Help';
46776 Help.prototype.isHelp = true;
46777
46778 /**
46779 * Generate a string representation of the Help object
46780 * @return {string} Returns a string
46781 * @private
46782 */
46783 Help.prototype.toString = function () {
46784 var doc = this.doc || {};
46785 var desc = '\n';
46786
46787 if (doc.name) {
46788 desc += 'Name: ' + doc.name + '\n\n';
46789 }
46790 if (doc.category) {
46791 desc += 'Category: ' + doc.category + '\n\n';
46792 }
46793 if (doc.description) {
46794 desc += 'Description:\n ' + doc.description + '\n\n';
46795 }
46796 if (doc.syntax) {
46797 desc += 'Syntax:\n ' + doc.syntax.join('\n ') + '\n\n';
46798 }
46799 if (doc.examples) {
46800 desc += 'Examples:\n';
46801 for (var i = 0; i < doc.examples.length; i++) {
46802 var expr = doc.examples[i];
46803 desc += ' ' + expr + '\n';
46804
46805 var res;
46806 try {
46807 // note: res can be undefined when `expr` is an empty string
46808 res = parser.eval(expr);
46809 }
46810 catch (e) {
46811 res = e;
46812 }
46813 if (res !== undefined && !type.isHelp(res)) {
46814 desc += ' ' + string.format(res, {precision: 14}) + '\n';
46815 }
46816 }
46817 desc += '\n';
46818 }
46819 if (doc.seealso && doc.seealso.length) {
46820 desc += 'See also: ' + doc.seealso.join(', ') + '\n';
46821 }
46822
46823 return desc;
46824 };
46825
46826 /**
46827 * Export the help object to JSON
46828 */
46829 Help.prototype.toJSON = function () {
46830 var obj = object.clone(this.doc);
46831 obj.mathjs = 'Help';
46832 return obj;
46833 };
46834
46835 /**
46836 * Instantiate a Help object from a JSON object
46837 * @param {Object} json
46838 * @returns {Help} Returns a new Help object
46839 */
46840 Help.fromJSON = function (json) {
46841 var doc = {};
46842 for (var prop in json) {
46843 if (prop !== 'mathjs') { // ignore mathjs field
46844 doc[prop] = json[prop];
46845 }
46846 }
46847 return new Help(doc);
46848 };
46849
46850 /**
46851 * Returns a string representation of the Help object
46852 */
46853 Help.prototype.valueOf = Help.prototype.toString;
46854
46855 return Help;
46856}
46857
46858exports.name = 'Help';
46859exports.path = 'type';
46860exports.factory = factory;
46861
46862
46863/***/ }),
46864/* 407 */
46865/***/ (function(module, exports, __webpack_require__) {
46866
46867module.exports = [
46868 __webpack_require__(408),
46869 __webpack_require__(428),
46870 __webpack_require__(447),
46871 __webpack_require__(460),
46872 __webpack_require__(464),
46873 __webpack_require__(468),
46874 __webpack_require__(471),
46875 __webpack_require__(475),
46876 __webpack_require__(488),
46877 __webpack_require__(498),
46878 __webpack_require__(501),
46879 __webpack_require__(509),
46880 __webpack_require__(511),
46881 __webpack_require__(517),
46882 __webpack_require__(519),
46883 __webpack_require__(544),
46884 __webpack_require__(546)
46885];
46886
46887
46888/***/ }),
46889/* 408 */
46890/***/ (function(module, exports, __webpack_require__) {
46891
46892module.exports = [
46893 __webpack_require__(409),
46894
46895 // simplify
46896 __webpack_require__(82),
46897
46898 // polynomial
46899 __webpack_require__(411),
46900
46901
46902 // decomposition
46903 __webpack_require__(412),
46904 __webpack_require__(127),
46905 __webpack_require__(128),
46906
46907 // solver
46908 __webpack_require__(133),
46909 __webpack_require__(426),
46910 __webpack_require__(134)
46911];
46912
46913
46914/***/ }),
46915/* 409 */
46916/***/ (function(module, exports, __webpack_require__) {
46917
46918"use strict";
46919
46920
46921function factory (type, config, load, typed) {
46922 var parse = load(__webpack_require__(41));
46923 var simplify = load(__webpack_require__(82));
46924 var ConstantNode = load(__webpack_require__(47));
46925 var FunctionNode = load(__webpack_require__(56));
46926 var OperatorNode = load(__webpack_require__(55));
46927 var ParenthesisNode = load(__webpack_require__(63));
46928 var SymbolNode = load(__webpack_require__(36));
46929
46930 /**
46931 * Takes the derivative of an expression expressed in parser Nodes.
46932 * The derivative will be taken over the supplied variable in the
46933 * second parameter. If there are multiple variables in the expression,
46934 * it will return a partial derivative.
46935 *
46936 * This uses rules of differentiation which can be found here:
46937 *
46938 * - [Differentiation rules (Wikipedia)](http://en.wikipedia.org/wiki/Differentiation_rules)
46939 *
46940 * Syntax:
46941 *
46942 * derivative(expr, variable)
46943 * derivative(expr, variable, options)
46944 *
46945 * Examples:
46946 *
46947 * math.derivative('x^2', 'x'); // Node {2 * x}
46948 * math.derivative('x^2', 'x', {simplify: false}); // Node {2 * 1 * x ^ (2 - 1)
46949 * math.derivative('sin(2x)', 'x')); // Node {2 * cos(2 * x)}
46950 * math.derivative('2*x', 'x').eval(); // number 2
46951 * math.derivative('x^2', 'x').eval({x: 4}); // number 8
46952 * var f = math.parse('x^2');
46953 * var x = math.parse('x');
46954 * math.derivative(f, x); // Node {2 * x}
46955 *
46956 * See also:
46957 *
46958 * simplify, parse, eval
46959 *
46960 * @param {Node | string} expr The expression to differentiate
46961 * @param {SymbolNode | string} variable The variable over which to differentiate
46962 * @param {{simplify: boolean}} [options]
46963 * There is one option available, `simplify`, which
46964 * is true by default. When false, output will not
46965 * be simplified.
46966 * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The derivative of `expr`
46967 */
46968 var derivative = typed('derivative', {
46969 'Node, SymbolNode, Object': function (expr, variable, options) {
46970 var constNodes = {};
46971 constTag(constNodes, expr, variable.name);
46972 var res = _derivative(expr, constNodes);
46973 return options.simplify ? simplify(res) : res;
46974 },
46975 'Node, SymbolNode': function (expr, variable) {
46976 return derivative(expr, variable, {simplify: true})
46977 },
46978
46979 'string, SymbolNode': function (expr, variable) {
46980 return derivative(parse(expr), variable)
46981 },
46982 'string, SymbolNode, Object': function (expr, variable, options) {
46983 return derivative(parse(expr), variable, options)
46984 },
46985
46986 'string, string': function (expr, variable) {
46987 return derivative(parse(expr), parse(variable))
46988 },
46989 'string, string, Object': function (expr, variable, options) {
46990 return derivative(parse(expr), parse(variable), options)
46991 },
46992
46993 'Node, string': function (expr, variable) {
46994 return derivative(expr, parse(variable))
46995 },
46996 'Node, string, Object': function (expr, variable, options) {
46997 return derivative(expr, parse(variable), options)
46998 }
46999
47000 // TODO: replace the 8 signatures above with 4 as soon as typed-function supports optional arguments
47001
47002 /* TODO: implement and test syntax with order of derivatives -> implement as an option {order: number}
47003 'Node, SymbolNode, ConstantNode': function (expr, variable, {order}) {
47004 var res = expr;
47005 for (var i = 0; i < order; i++) {
47006 var constNodes = {};
47007 constTag(constNodes, expr, variable.name);
47008 res = _derivative(res, constNodes);
47009 }
47010 return res;
47011 }
47012 */
47013 });
47014
47015 derivative._simplify = true
47016
47017 derivative.toTex = function(deriv) {
47018 return _derivTex.apply(null, deriv.args);
47019 }
47020
47021 var _derivTex = typed('_derivTex', {
47022 'Node, SymbolNode': function (expr, x) {
47023 return _derivTex(expr.toString(), x.toString(), 1);
47024 },
47025 'Node, SymbolNode, ConstantNode': function (expr, x, order) {
47026 return _derivTex(expr.toString(), x.name, order.value);
47027 },
47028 'string, string, number': function (expr, x, order) {
47029 var d;
47030 if (order === 1) {
47031 d = "{d\\over d" + x + "}";
47032 }
47033 else {
47034 d = "{d^{" + order + "}\\over d" + x + "^{" + order + "}}";
47035 }
47036 return d + "\\left[" + expr + "\\right]"
47037 }
47038 });
47039
47040 /**
47041 * Does a depth-first search on the expression tree to identify what Nodes
47042 * are constants (e.g. 2 + 2), and stores the ones that are constants in
47043 * constNodes. Classification is done as follows:
47044 *
47045 * 1. ConstantNodes are constants.
47046 * 2. If there exists a SymbolNode, of which we are differentiating over,
47047 * in the subtree it is not constant.
47048 *
47049 * @param {Object} constNodes Holds the nodes that are constant
47050 * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
47051 * @param {string} varName Variable that we are differentiating
47052 * @return {boolean} if node is constant
47053 */
47054 // TODO: can we rewrite constTag into a pure function?
47055 var constTag = typed('constTag', {
47056 'Object, ConstantNode, string': function (constNodes, node) {
47057 return constNodes[node] = true;
47058 },
47059
47060 'Object, SymbolNode, string': function (constNodes, node, varName) {
47061 // Treat other variables like constants. For reasoning, see:
47062 // https://en.wikipedia.org/wiki/Partial_derivative
47063 if (node.name != varName) {
47064 return constNodes[node] = true;
47065 }
47066 return false;
47067 },
47068
47069 'Object, ParenthesisNode, string': function (constNodes, node, varName) {
47070 return constTag(constNodes, node.content, varName);
47071 },
47072
47073 'Object, FunctionAssignmentNode, string': function (constNodes, node, varName) {
47074 if (node.params.indexOf(varName) == -1) {
47075 return constNodes[node] = true;
47076 }
47077 return constTag(constNodes, node.expr, varName);
47078 },
47079
47080 'Object, FunctionNode | OperatorNode, string': function (constNodes, node, varName) {
47081 if (node.args.length != 0) {
47082 var isConst = constTag(constNodes, node.args[0], varName);
47083 for (var i = 1; i < node.args.length; ++i) {
47084 isConst = constTag(constNodes, node.args[i], varName) && isConst;
47085 }
47086
47087 if (isConst) {
47088 return constNodes[node] = true;
47089 }
47090 }
47091 return false;
47092 }
47093 });
47094
47095 /**
47096 * Applies differentiation rules.
47097 *
47098 * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
47099 * @param {Object} constNodes Holds the nodes that are constant
47100 * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The derivative of `expr`
47101 */
47102 var _derivative = typed('_derivative', {
47103 'ConstantNode, Object': function (node) {
47104 return new ConstantNode('0', node.valueType);
47105 },
47106
47107 'SymbolNode, Object': function (node, constNodes) {
47108 if (constNodes[node] !== undefined) {
47109 return new ConstantNode('0', config.number);
47110 }
47111 return new ConstantNode('1', config.number);
47112 },
47113
47114 'ParenthesisNode, Object': function (node, constNodes) {
47115 return new ParenthesisNode(_derivative(node.content, constNodes));
47116 },
47117
47118 'FunctionAssignmentNode, Object': function (node, constNodes) {
47119 if (constNodes[node] !== undefined) {
47120 return new ConstantNode('0', config.number);
47121 }
47122 return _derivative(node.expr, constNodes);
47123 },
47124
47125 'FunctionNode, Object': function (node, constNodes) {
47126 if (node.args.length != 1) {
47127 funcArgsCheck(node);
47128 }
47129
47130 if (constNodes[node] !== undefined) {
47131 return new ConstantNode('0', config.number);
47132 }
47133
47134 var arg1 = node.args[0];
47135 var arg2;
47136
47137 var div = false; // is output a fraction?
47138 var negative = false; // is output negative?
47139
47140 var funcDerivative;
47141 switch (node.name) {
47142 case 'cbrt':
47143 // d/dx(cbrt(x)) = 1 / (3x^(2/3))
47144 div = true;
47145 funcDerivative = new OperatorNode('*', 'multiply', [
47146 new ConstantNode('3', config.number),
47147 new OperatorNode('^', 'pow', [
47148 arg1,
47149 new OperatorNode('/', 'divide', [
47150 new ConstantNode('2', config.number),
47151 new ConstantNode('3', config.number)
47152 ])
47153 ])
47154 ]);
47155 break;
47156 case 'sqrt':
47157 case 'nthRoot':
47158 // d/dx(sqrt(x)) = 1 / (2*sqrt(x))
47159 if (node.args.length == 1) {
47160 div = true;
47161 funcDerivative = new OperatorNode('*', 'multiply', [
47162 new ConstantNode('2', config.number),
47163 new FunctionNode('sqrt', [arg1])
47164 ]);
47165 break;
47166 }
47167
47168 // Rearrange from nthRoot(x, a) -> x^(1/a)
47169 arg2 = new OperatorNode('/', 'divide', [
47170 new ConstantNode('1', config.number),
47171 node.args[1]
47172 ]);
47173
47174 // Is a variable?
47175 constNodes[arg2] = constNodes[node.args[1]];
47176
47177 return _derivative(new OperatorNode('^', 'pow', [arg1, arg2]), constNodes);
47178 case 'log10':
47179 arg2 = new ConstantNode('10', config.number);
47180 case 'log':
47181 if (!arg2 && node.args.length == 1) {
47182 // d/dx(log(x)) = 1 / x
47183 funcDerivative = arg1.clone();
47184 } else if (arg2 || constNodes[node.args[1]] !== undefined) {
47185 // d/dx(log(x, c)) = 1 / (x*ln(c))
47186 funcDerivative = new OperatorNode('*', 'multiply', [
47187 arg1.clone(),
47188 new FunctionNode('log', [arg2 || node.args[1]])
47189 ]);
47190 } else {
47191 // d/dx(log(f(x), g(x))) = d/dx(log(f(x)) / log(g(x)))
47192 return _derivative(new OperatorNode('/', 'divide', [
47193 new FunctionNode('log', [arg1]),
47194 new FunctionNode('log', [node.args[1]])
47195 ]), constNodes);
47196 }
47197
47198 div = true;
47199 break;
47200 case 'exp':
47201 // d/dx(e^x) = e^x
47202 funcDerivative = new FunctionNode('exp', [arg1.clone()]);
47203 break;
47204 case 'sin':
47205 // d/dx(sin(x)) = cos(x)
47206 funcDerivative = new FunctionNode('cos', [arg1.clone()]);
47207 break;
47208 case 'cos':
47209 // d/dx(cos(x)) = -sin(x)
47210 funcDerivative = new OperatorNode('-', 'unaryMinus', [
47211 new FunctionNode('sin', [arg1.clone()])
47212 ]);
47213 break;
47214 case 'tan':
47215 // d/dx(tan(x)) = sec(x)^2
47216 funcDerivative = new OperatorNode('^', 'pow', [
47217 new FunctionNode('sec', [arg1.clone()]),
47218 new ConstantNode('2', config.number)
47219 ]);
47220 break;
47221 case 'sec':
47222 // d/dx(sec(x)) = sec(x)tan(x)
47223 funcDerivative = new OperatorNode('*', 'multiply', [
47224 node,
47225 new FunctionNode('tan', [arg1.clone()])
47226 ]);
47227 break;
47228 case 'csc':
47229 // d/dx(csc(x)) = -csc(x)cot(x)
47230 negative = true;
47231 funcDerivative = new OperatorNode('*', 'multiply', [
47232 node,
47233 new FunctionNode('cot', [arg1.clone()])
47234 ]);
47235 break;
47236 case 'cot':
47237 // d/dx(cot(x)) = -csc(x)^2
47238 negative = true;
47239 funcDerivative = new OperatorNode('^', 'pow', [
47240 new FunctionNode('csc', [arg1.clone()]),
47241 new ConstantNode('2', config.number)
47242 ]);
47243 break;
47244 case 'asin':
47245 // d/dx(asin(x)) = 1 / sqrt(1 - x^2)
47246 div = true;
47247 funcDerivative = new FunctionNode('sqrt', [
47248 new OperatorNode('-', 'subtract', [
47249 new ConstantNode('1', config.number),
47250 new OperatorNode('^', 'pow', [
47251 arg1.clone(),
47252 new ConstantNode('2', config.number)
47253 ])
47254 ])
47255 ]);
47256 break;
47257 case 'acos':
47258 // d/dx(acos(x)) = -1 / sqrt(1 - x^2)
47259 div = true;
47260 negative = true;
47261 funcDerivative = new FunctionNode('sqrt', [
47262 new OperatorNode('-', 'subtract', [
47263 new ConstantNode('1', config.number),
47264 new OperatorNode('^', 'pow', [
47265 arg1.clone(),
47266 new ConstantNode('2', config.number)
47267 ])
47268 ])
47269 ]);
47270 break;
47271 case 'atan':
47272 // d/dx(atan(x)) = 1 / (x^2 + 1)
47273 div = true;
47274 funcDerivative = new OperatorNode('+', 'add', [
47275 new OperatorNode('^', 'pow', [
47276 arg1.clone(),
47277 new ConstantNode('2', config.number)
47278 ]),
47279 new ConstantNode('1', config.number)
47280 ]);
47281 break;
47282 case 'asec':
47283 // d/dx(asec(x)) = 1 / (|x|*sqrt(x^2 - 1))
47284 div = true;
47285 funcDerivative = new OperatorNode('*', 'multiply', [
47286 new FunctionNode('abs', [arg1.clone()]),
47287 new FunctionNode('sqrt', [
47288 new OperatorNode('-', 'subtract', [
47289 new OperatorNode('^', 'pow', [
47290 arg1.clone(),
47291 new ConstantNode('2', config.number)
47292 ]),
47293 new ConstantNode('1', config.number)
47294 ])
47295 ])
47296 ]);
47297 break;
47298 case 'acsc':
47299 // d/dx(acsc(x)) = -1 / (|x|*sqrt(x^2 - 1))
47300 div = true;
47301 negative = true;
47302 funcDerivative = new OperatorNode('*', 'multiply', [
47303 new FunctionNode('abs', [arg1.clone()]),
47304 new FunctionNode('sqrt', [
47305 new OperatorNode('-', 'subtract', [
47306 new OperatorNode('^', 'pow', [
47307 arg1.clone(),
47308 new ConstantNode('2', config.number)
47309 ]),
47310 new ConstantNode('1', config.number)
47311 ])
47312 ])
47313 ]);
47314 break;
47315 case 'acot':
47316 // d/dx(acot(x)) = -1 / (x^2 + 1)
47317 div = true;
47318 negative = true;
47319 funcDerivative = new OperatorNode('+', 'add', [
47320 new OperatorNode('^', 'pow', [
47321 arg1.clone(),
47322 new ConstantNode('2', config.number)
47323 ]),
47324 new ConstantNode('1', config.number)
47325 ]);
47326 break;
47327 case 'sinh':
47328 // d/dx(sinh(x)) = cosh(x)
47329 funcDerivative = new FunctionNode('cosh', [arg1.clone()]);
47330 break;
47331 case 'cosh':
47332 // d/dx(cosh(x)) = sinh(x)
47333 funcDerivative = new FunctionNode('sinh', [arg1.clone()]);
47334 break;
47335 case 'tanh':
47336 // d/dx(tanh(x)) = sech(x)^2
47337 funcDerivative = new OperatorNode('^', 'pow', [
47338 new FunctionNode('sech', [arg1.clone()]),
47339 new ConstantNode('2', config.number)
47340 ]);
47341 break;
47342 case 'sech':
47343 // d/dx(sech(x)) = -sech(x)tanh(x)
47344 negative = true;
47345 funcDerivative = new OperatorNode('*', 'multiply', [
47346 node,
47347 new FunctionNode('tanh', [arg1.clone()])
47348 ]);
47349 break;
47350 case 'csch':
47351 // d/dx(csch(x)) = -csch(x)coth(x)
47352 negative = true;
47353 funcDerivative = new OperatorNode('*', 'multiply', [
47354 node,
47355 new FunctionNode('coth', [arg1.clone()])
47356 ]);
47357 break;
47358 case 'coth':
47359 // d/dx(coth(x)) = -csch(x)^2
47360 negative = true;
47361 funcDerivative = new OperatorNode('^', 'pow', [
47362 new FunctionNode('csch', [arg1.clone()]),
47363 new ConstantNode('2', config.number)
47364 ]);
47365 break;
47366 case 'asinh':
47367 // d/dx(asinh(x)) = 1 / sqrt(x^2 + 1)
47368 div = true;
47369 funcDerivative = new FunctionNode('sqrt', [
47370 new OperatorNode('+', 'add', [
47371 new OperatorNode('^', 'pow', [
47372 arg1.clone(),
47373 new ConstantNode('2', config.number)
47374 ]),
47375 new ConstantNode('1', config.number)
47376 ])
47377 ]);
47378 break;
47379 case 'acosh':
47380 // d/dx(acosh(x)) = 1 / sqrt(x^2 - 1); XXX potentially only for x >= 1 (the real spectrum)
47381 div = true;
47382 funcDerivative = new FunctionNode('sqrt', [
47383 new OperatorNode('-', 'subtract', [
47384 new OperatorNode('^', 'pow', [
47385 arg1.clone(),
47386 new ConstantNode('2', config.number)
47387 ]),
47388 new ConstantNode('1', config.number),
47389 ])
47390 ]);
47391 break;
47392 case 'atanh':
47393 // d/dx(atanh(x)) = 1 / (1 - x^2)
47394 div = true;
47395 funcDerivative = new OperatorNode('-', 'subtract', [
47396 new ConstantNode('1', config.number),
47397 new OperatorNode('^', 'pow', [
47398 arg1.clone(),
47399 new ConstantNode('2', config.number)
47400 ])
47401 ]);
47402 break;
47403 case 'asech':
47404 // d/dx(asech(x)) = -1 / (x*sqrt(1 - x^2))
47405 div = true;
47406 negative = true;
47407 funcDerivative = new OperatorNode('*', 'multiply', [
47408 arg1.clone(),
47409 new FunctionNode('sqrt', [
47410 new OperatorNode('-', 'subtract', [
47411 new ConstantNode('1', config.number),
47412 new OperatorNode('^', 'pow', [
47413 arg1.clone(),
47414 new ConstantNode('2', config.number)
47415 ])
47416 ])
47417 ])
47418 ]);
47419 break;
47420 case 'acsch':
47421 // d/dx(acsch(x)) = -1 / (|x|*sqrt(x^2 + 1))
47422 div = true;
47423 negative = true;
47424 funcDerivative = new OperatorNode('*', 'multiply', [
47425 new FunctionNode('abs', [arg1.clone()]),
47426 new FunctionNode('sqrt', [
47427 new OperatorNode('+', 'add', [
47428 new OperatorNode('^', 'pow', [
47429 arg1.clone(),
47430 new ConstantNode('2', config.number)
47431 ]),
47432 new ConstantNode('1', config.number)
47433 ])
47434 ])
47435 ]);
47436 break;
47437 case 'acoth':
47438 // d/dx(acoth(x)) = -1 / (1 - x^2)
47439 div = true;
47440 negative = true;
47441 funcDerivative = new OperatorNode('-', 'subtract', [
47442 new ConstantNode('1', config.number),
47443 new OperatorNode('^', 'pow', [
47444 arg1.clone(),
47445 new ConstantNode('2', config.number)
47446 ])
47447 ]);
47448 break;
47449 case 'abs':
47450 // d/dx(abs(x)) = abs(x)/x
47451 funcDerivative = new OperatorNode('/', 'divide', [
47452 new FunctionNode(new SymbolNode('abs'), [arg1.clone()]),
47453 arg1.clone()
47454 ]);
47455 break;
47456 case 'gamma': // Needs digamma function, d/dx(gamma(x)) = gamma(x)digamma(x)
47457 default: throw new Error('Function "' + node.name + '" not supported by derivative');
47458 }
47459
47460 var op, func;
47461 if (div) {
47462 op = '/';
47463 func = 'divide';
47464 } else {
47465 op = '*';
47466 func = 'multiply';
47467 }
47468
47469 /* Apply chain rule to all functions:
47470 F(x) = f(g(x))
47471 F'(x) = g'(x)*f'(g(x)) */
47472 var chainDerivative = _derivative(arg1, constNodes);
47473 if (negative) {
47474 chainDerivative = new OperatorNode('-', 'unaryMinus', [chainDerivative]);
47475 }
47476 return new OperatorNode(op, func, [chainDerivative, funcDerivative]);
47477 },
47478
47479 'OperatorNode, Object': function (node, constNodes) {
47480 if (constNodes[node] !== undefined) {
47481 return new ConstantNode('0', config.number);
47482 }
47483
47484 var arg1 = node.args[0];
47485 var arg2 = node.args[1];
47486
47487 switch (node.op) {
47488 case '+':
47489 // d/dx(sum(f(x)) = sum(f'(x))
47490 return new OperatorNode(node.op, node.fn, node.args.map(function(arg) {
47491 return _derivative(arg, constNodes);
47492 }));
47493 case '-':
47494 // d/dx(+/-f(x)) = +/-f'(x)
47495 if (node.args.length == 1) {
47496 return new OperatorNode(node.op, node.fn, [_derivative(arg1, constNodes)]);
47497 }
47498
47499 // Linearity of differentiation, d/dx(f(x) +/- g(x)) = f'(x) +/- g'(x)
47500 return new OperatorNode(node.op, node.fn, [
47501 _derivative(arg1, constNodes),
47502 _derivative(arg2, constNodes)
47503 ]);
47504 case '*':
47505 // d/dx(c*f(x)) = c*f'(x)
47506 var constantTerms = node.args.filter(function(arg) {
47507 return constNodes[arg] !== undefined;
47508 });
47509
47510 if (constantTerms.length > 0) {
47511 var nonConstantTerms = node.args.filter(function(arg) {
47512 return constNodes[arg] === undefined;
47513 });
47514
47515 var nonConstantNode = nonConstantTerms.length === 1
47516 ? nonConstantTerms[0]
47517 : new OperatorNode('*', 'multiply', nonConstantTerms);
47518
47519 var newArgs = constantTerms.concat(_derivative(nonConstantNode, constNodes));
47520
47521 return new OperatorNode('*', 'multiply', newArgs);
47522 }
47523
47524 // Product Rule, d/dx(f(x)*g(x)) = f'(x)*g(x) + f(x)*g'(x)
47525 return new OperatorNode('+', 'add', node.args.map(function(argOuter) {
47526 return new OperatorNode('*', 'multiply', node.args.map(function(argInner) {
47527 return (argInner === argOuter)
47528 ? _derivative(argInner, constNodes)
47529 : argInner.clone();
47530 }));
47531 }));
47532 case '/':
47533 // d/dx(f(x) / c) = f'(x) / c
47534 if (constNodes[arg2] !== undefined) {
47535 return new OperatorNode('/', 'divide', [_derivative(arg1, constNodes), arg2]);
47536 }
47537
47538 // Reciprocal Rule, d/dx(c / f(x)) = -c(f'(x)/f(x)^2)
47539 if (constNodes[arg1] !== undefined) {
47540 return new OperatorNode('*', 'multiply', [
47541 new OperatorNode('-', 'unaryMinus', [arg1]),
47542 new OperatorNode('/', 'divide', [
47543 _derivative(arg2, constNodes),
47544 new OperatorNode('^', 'pow', [arg2.clone(), new ConstantNode('2', config.number)])
47545 ])
47546 ]);
47547 }
47548
47549 // Quotient rule, d/dx(f(x) / g(x)) = (f'(x)g(x) - f(x)g'(x)) / g(x)^2
47550 return new OperatorNode('/', 'divide', [
47551 new OperatorNode('-', 'subtract', [
47552 new OperatorNode('*', 'multiply', [_derivative(arg1, constNodes), arg2.clone()]),
47553 new OperatorNode('*', 'multiply', [arg1.clone(), _derivative(arg2, constNodes)])
47554 ]),
47555 new OperatorNode('^', 'pow', [arg2.clone(), new ConstantNode('2', config.number)])
47556 ]);
47557 case '^':
47558 if (constNodes[arg1] !== undefined) {
47559 // If is secretly constant; 0^f(x) = 1 (in JS), 1^f(x) = 1
47560 if (type.isConstantNode(arg1) && (arg1.value === '0' || arg1.value === '1')) {
47561 return new ConstantNode('0', config.number);
47562 }
47563
47564 // d/dx(c^f(x)) = c^f(x)*ln(c)*f'(x)
47565 return new OperatorNode('*', 'multiply', [
47566 node,
47567 new OperatorNode('*', 'multiply', [
47568 new FunctionNode('log', [arg1.clone()]),
47569 _derivative(arg2.clone(), constNodes)
47570 ])
47571 ]);
47572 }
47573
47574 if (constNodes[arg2] !== undefined) {
47575 if (type.isConstantNode(arg2)) {
47576 var expValue = arg2.value;
47577
47578 // If is secretly constant; f(x)^0 = 1 -> d/dx(1) = 0
47579 if (expValue === '0') {
47580 return new ConstantNode('0', config.number);
47581 }
47582 // Ignore exponent; f(x)^1 = f(x)
47583 if (expValue === '1') {
47584 return _derivative(arg1, constNodes);
47585 }
47586 }
47587
47588 // Elementary Power Rule, d/dx(f(x)^c) = c*f'(x)*f(x)^(c-1)
47589 var powMinusOne = new OperatorNode('^', 'pow', [
47590 arg1.clone(),
47591 new OperatorNode('-', 'subtract', [
47592 arg2,
47593 new ConstantNode('1', config.number)
47594 ])
47595 ]);
47596
47597 return new OperatorNode('*', 'multiply', [
47598 arg2.clone(),
47599 new OperatorNode('*', 'multiply', [
47600 _derivative(arg1, constNodes),
47601 powMinusOne
47602 ]),
47603 ]);
47604 }
47605
47606 // Functional Power Rule, d/dx(f^g) = f^g*[f'*(g/f) + g'ln(f)]
47607 return new OperatorNode('*', 'multiply', [
47608 new OperatorNode('^', 'pow', [arg1.clone(), arg2.clone()]),
47609 new OperatorNode('+', 'add', [
47610 new OperatorNode('*', 'multiply', [
47611 _derivative(arg1, constNodes),
47612 new OperatorNode('/', 'divide', [arg2.clone(), arg1.clone()])
47613 ]),
47614 new OperatorNode('*', 'multiply', [
47615 _derivative(arg2, constNodes),
47616 new FunctionNode('log', [arg1.clone()])
47617 ])
47618 ])
47619 ]);
47620 case '%':
47621 case 'mod':
47622 default: throw new Error('Operator "' + node.op + '" not supported by derivative');
47623 }
47624 }
47625 });
47626
47627 /**
47628 * Ensures the number of arguments for a function are correct,
47629 * and will throw an error otherwise.
47630 *
47631 * @param {FunctionNode} node
47632 */
47633 function funcArgsCheck(node) {
47634 //TODO add min, max etc
47635 if ((node.name == 'log' || node.name == 'nthRoot') && node.args.length == 2) {
47636 return;
47637 }
47638
47639 // There should be an incorrect number of arguments if we reach here
47640
47641 // Change all args to constants to avoid unidentified
47642 // symbol error when compiling function
47643 for (var i = 0; i < node.args.length; ++i) {
47644 node.args[i] = new ConstantNode(0);
47645 }
47646
47647 node.compile().eval();
47648 throw new Error('Expected TypeError, but none found');
47649 }
47650
47651
47652 return derivative;
47653}
47654
47655exports.name = 'derivative';
47656exports.factory = factory;
47657
47658
47659/***/ }),
47660/* 410 */
47661/***/ (function(module, exports, __webpack_require__) {
47662
47663"use strict";
47664
47665
47666function factory(type, config, load, typed, math) {
47667 var Node = math.expression.node.Node;
47668 var OperatorNode = math.expression.node.OperatorNode;
47669 var FunctionNode = math.expression.node.FunctionNode;
47670 var ParenthesisNode = math.expression.node.ParenthesisNode;
47671
47672 /**
47673 * resolve(expr, scope) replaces variable nodes with their scoped values
47674 *
47675 * Syntax:
47676 *
47677 * simplify.resolve(expr, scope)
47678 *
47679 * Examples:
47680 *
47681 * math.simplify.resolve('x + y', {x:1, y:2}) // Node {1 + 2}
47682 * math.simplify.resolve(math.parse('x+y'), {x:1, y:2}) // Node {1 + 2}
47683 * math.simplify('x+y', {x:2, y:'x+x'}).toString(); // "6"
47684 *
47685 * @param {Node} node
47686 * The expression tree to be simplified
47687 * @param {Object} scope with variables to be resolved
47688 */
47689 function resolve(node, scope) {
47690 if (!scope) {
47691 return node;
47692 }
47693 if (type.isSymbolNode(node)) {
47694 var value = scope[node.name];
47695 if (value instanceof Node) {
47696 return resolve(value, scope);
47697 } else if (typeof value === 'number') {
47698 return math.parse(String(value));
47699 }
47700 } else if (type.isOperatorNode(node)) {
47701 var args = node.args.map(function (arg) {
47702 return resolve(arg, scope)
47703 });
47704 return new OperatorNode(node.op, node.fn, args);
47705 } else if (type.isParenthesisNode(node)) {
47706 return new ParenthesisNode(resolve(node.content, scope));
47707 } else if (type.isFunctionNode(node)) {
47708 var args = node.args.map(function (arg) {
47709 return resolve(arg, scope)
47710 });
47711 return new FunctionNode(node.name, args);
47712 }
47713 return node;
47714 }
47715
47716 return resolve;
47717}
47718
47719exports.math = true;
47720exports.name = 'resolve';
47721exports.path = 'algebra.simplify';
47722exports.factory = factory;
47723
47724
47725/***/ }),
47726/* 411 */
47727/***/ (function(module, exports, __webpack_require__) {
47728
47729"use strict";
47730
47731
47732function factory (type, config, load, typed) {
47733 var simplify = load(__webpack_require__(82));
47734 var simplifyCore = load(__webpack_require__(122));
47735 var simplifyConstant = load(__webpack_require__(120));
47736 var ArgumentsError = __webpack_require__(44);
47737 var parse = load(__webpack_require__(111));
47738 var number = __webpack_require__(3)
47739 var ConstantNode = load(__webpack_require__(47));
47740 var OperatorNode = load(__webpack_require__(55));
47741 var SymbolNode = load(__webpack_require__(36));
47742
47743 /**
47744 * Transform a rationalizable expression in a rational fraction.
47745 * If rational fraction is one variable polynomial then converts
47746 * the numerator and denominator in canonical form, with decreasing
47747 * exponents, returning the coefficients of numerator.
47748 *
47749 * Syntax:
47750 *
47751 * rationalize(expr)
47752 * rationalize(expr, detailed)
47753 * rationalize(expr, scope)
47754 * rationalize(expr, scope, detailed)
47755 *
47756 * Examples:
47757 *
47758 * math.rationalize('sin(x)+y') // Error: There is an unsolved function call
47759 * math.rationalize('2x/y - y/(x+1)') // (2*x^2-y^2+2*x)/(x*y+y)
47760 * math.rationalize('(2x+1)^6')
47761 * // 64*x^6+192*x^5+240*x^4+160*x^3+60*x^2+12*x+1
47762 * math.rationalize('2x/( (2x-1) / (3x+2) ) - 5x/ ( (3x+4) / (2x^2-5) ) + 3')
47763 * // -20*x^4+28*x^3+104*x^2+6*x-12)/(6*x^2+5*x-4)
47764 * math.rationalize('x/(1-x)/(x-2)/(x-3)/(x-4) + 2x/ ( (1-2x)/(2-3x) )/ ((3-4x)/(4-5x) )') =
47765 * // (-30*x^7+344*x^6-1506*x^5+3200*x^4-3472*x^3+1846*x^2-381*x)/
47766 * // (-8*x^6+90*x^5-383*x^4+780*x^3-797*x^2+390*x-72)
47767 *
47768 * math.rationalize('x+x+x+y',{y:1}) // 3*x+1
47769 * math.rationalize('x+x+x+y',{}) // 3*x+y
47770 * ret = math.rationalize('x+x+x+y',{},true)
47771 * // ret.expression=3*x+y, ret.variables = ["x","y"]
47772 * ret = math.rationalize('-2+5x^2',{},true)
47773 * // ret.expression=5*x^2-2, ret.variables = ["x"], ret.coefficients=[-2,0,5]
47774 *
47775 * See also:
47776 *
47777 * simplify
47778 *
47779 * @param {Node|string} expr The expression to check if is a polynomial expression
47780 * @param {Object|boolean} optional scope of expression or true for already evaluated rational expression at input
47781 * @param {Boolean} detailed optional True if return an object, false if return expression node (default)
47782 *
47783 * @return {Object | Expression Node} The rational polynomial of `expr` or na object
47784 * {Object}
47785 * {Expression Node} expression: node simplified expression
47786 * {Expression Node} numerator: simplified numerator of expression
47787 * {Expression Node | boolean} denominator: simplified denominator or false (if there is no denominator)
47788 * {Array} variables: variable names
47789 * {Array} coefficients: coefficients of numerator sorted by increased exponent
47790 * {Expression Node} node simplified expression
47791 *
47792 */
47793 var rationalize = typed('rationalize', {
47794 'string': function (expr) {
47795 return rationalize(parse(expr), {}, false);
47796 },
47797
47798 'string, boolean': function (expr, detailed) {
47799 return rationalize(parse(expr), {} , detailed);
47800 },
47801
47802 'string, Object': function (expr, scope) {
47803 return rationalize(parse(expr), scope, false);
47804 },
47805
47806 'string, Object, boolean': function (expr, scope, detailed) {
47807 return rationalize(parse(expr), scope, detailed);
47808 },
47809
47810 'Node': function (expr) {
47811 return rationalize(expr, {}, false);
47812 },
47813
47814 'Node, boolean': function (expr, detailed) {
47815 return rationalize(expr, {}, detailed);
47816 },
47817
47818 'Node, Object': function (expr, scope) {
47819 return rationalize(expr, scope, false);
47820 },
47821
47822 'Node, Object, boolean': function (expr, scope, detailed) {
47823
47824 var polyRet = polynomial(expr, scope, true) // Check if expression is a rationalizable polynomial
47825 var nVars = polyRet.variables.length;
47826 var expr = polyRet.expression;
47827
47828 if (nVars>=1) { // If expression in not a constant
47829 var setRules = rulesRationalize(); // Rules for change polynomial in near canonical form
47830 expr = expandPower(expr); // First expand power of polynomials (cannot be made from rules!)
47831 var redoInic = true; // If has change after start, redo the beginning
47832 var s = ""; // New expression
47833 var sBefore; // Previous expression
47834 var rules;
47835 var eDistrDiv = true
47836
47837 expr = simplify(expr, setRules.firstRules); // Apply the initial rules, including succ div rules
47838 s = expr.toString();
47839
47840
47841 while (true) { // Apply alternately successive division rules and distr.div.rules
47842 rules = eDistrDiv ? setRules.distrDivRules : setRules.sucDivRules
47843 expr = simplify(expr,rules); // until no more changes
47844 eDistrDiv = ! eDistrDiv; // Swap between Distr.Div and Succ. Div. Rules
47845
47846 s = expr.toString();
47847 if (s===sBefore) break // No changes : end of the loop
47848
47849 redoInic = true;
47850 sBefore = s;
47851 }
47852
47853 if (redoInic) { // Apply first rules again without succ div rules (if there are changes)
47854 expr = simplify(expr,setRules.firstRulesAgain);
47855 }
47856 expr = simplify(expr,setRules.finalRules); // Aplly final rules
47857
47858 } // NVars >= 1
47859
47860 var coefficients=[];
47861 var retRationalize = {};
47862
47863 if (expr.type==='OperatorNode' && expr.op==='/') { // Separate numerator from denominator
47864 if (nVars==1) {
47865 expr.args[0] = polyToCanonical(expr.args[0],coefficients);
47866 expr.args[1] = polyToCanonical(expr.args[1]);
47867 }
47868 if (detailed) {
47869 retRationalize.numerator = expr.args[0];
47870 retRationalize.denominator = expr.args[1];
47871 }
47872 } else {
47873 if (nVars==1) expr = polyToCanonical(expr,coefficients);
47874 if (detailed) {
47875 retRationalize.numerator = expr;
47876 retRationalize.denominator = null
47877 }
47878 }
47879 // nVars
47880
47881 if (! detailed) return expr;
47882 retRationalize.coefficients = coefficients;
47883 retRationalize.variables = polyRet.variables;
47884 retRationalize.expression = expr;
47885 return retRationalize;
47886 } // ^^^^^^^ end of rationalize ^^^^^^^^
47887 }); // end of typed rationalize
47888
47889 /**
47890 * Function to simplify an expression using an optional scope and
47891 * return it if the expression is a polynomial expression, i.e.
47892 * an expression with one or more variables and the operators
47893 * +, -, *, and ^, where the exponent can only be a positive integer.
47894 *
47895 * Syntax:
47896 *
47897 * polynomial(expr,scope,extended)
47898 *
47899 * @param {Node | string} expr The expression to simplify and check if is polynomial expression
47900 * @param {object} scope Optional scope for expression simplification
47901 * @param {boolean} extended Optional. Default is false. When true allows divide operator.
47902 *
47903 *
47904 * @return {Object}
47905 * {Object} node: node simplified expression
47906 * {Array} variables: variable names
47907 */
47908 function polynomial (expr, scope, extended) {
47909 var variables = [];
47910 var node = simplify(expr,scope); // Resolves any variables and functions with all defined parameters
47911 extended = !! extended
47912
47913 var oper = '+-*' + (extended ? '/' : '');
47914 recPoly(node)
47915 var retFunc ={};
47916 retFunc.expression = node;
47917 retFunc.variables = variables;
47918 return retFunc;
47919
47920 //-------------------------------------------------------------------------------------------------------
47921
47922 /**
47923 * Function to simplify an expression using an optional scope and
47924 * return it if the expression is a polynomial expression, i.e.
47925 * an expression with one or more variables and the operators
47926 * +, -, *, and ^, where the exponent can only be a positive integer.
47927 *
47928 * Syntax:
47929 *
47930 * recPoly(node)
47931 *
47932 *
47933 * @param {Node} node The current sub tree expression in recursion
47934 *
47935 * @return nothing, throw an exception if error
47936 */
47937 function recPoly(node) {
47938 var tp = node.type; // node type
47939 if (tp==='FunctionNode')
47940 throw new ArgumentsError('There is an unsolved function call') // No function call in polynomial expression
47941 else if (tp==='OperatorNode') {
47942 if (node.op==='^') {
47943 if (node.args[1].type!=='ConstantNode' || ! number.isInteger(parseFloat(node.args[1].value)))
47944 throw new ArgumentsError('There is a non-integer exponent');
47945 else
47946 recPoly(node.args[0]);
47947 } else {
47948 if (oper.indexOf(node.op) === -1) throw new ArgumentsError('Operator ' + node.op + ' invalid in polynomial expression');
47949 for (var i=0;i<node.args.length;i++) {
47950 recPoly(node.args[i]);
47951 }
47952 } // type of operator
47953
47954 } else if (tp==='SymbolNode') {
47955 var name = node.name; // variable name
47956 var pos = variables.indexOf(name);
47957 if (pos===-1) // new variable in expression
47958 variables.push(name);
47959
47960 } else if (tp==='ParenthesisNode')
47961 recPoly(node.content);
47962
47963 else if (tp!=='ConstantNode')
47964 throw new ArgumentsError('type ' + tp + ' is not allowed in polynomial expression')
47965
47966 } // end of recPoly
47967
47968 } // end of polynomial
47969
47970
47971 //---------------------------------------------------------------------------------------
47972 /**
47973 * Return a rule set to rationalize an polynomial expression in rationalize
47974 *
47975 * Syntax:
47976 *
47977 * rulesRationalize()
47978 *
47979 * @return {array} rule set to rationalize an polynomial expression
47980 */
47981 function rulesRationalize() {
47982 var oldRules = [simplifyCore, // sCore
47983 {l:"n+n",r:"2*n"},
47984 {l:"n+-n",r:"0"},
47985 simplifyConstant, // sConstant
47986 {l:"n*(n1^-1)",r:"n/n1"},
47987 {l:"n*n1^-n2",r:"n/n1^n2"},
47988 {l:"n1^-1",r:"1/n1"},
47989 {l:"n*(n1/n2)",r:"(n*n1)/n2"},
47990 {l:"1*n",r:"n"}]
47991
47992 var rulesFirst = [
47993 { l: '(-n1)/(-n2)', r: 'n1/n2' }, // Unary division
47994 { l: '(-n1)*(-n2)', r: 'n1*n2' }, // Unary multiplication
47995 { l: 'n1--n2', r:'n1+n2'}, // '--' elimination
47996 { l: 'n1-n2', r:'n1+(-n2)'} , // Subtraction turn into add with un�ry minus
47997 { l:'(n1+n2)*n3', r:'(n1*n3 + n2*n3)' }, // Distributive 1
47998 { l:'n1*(n2+n3)', r:'(n1*n2+n1*n3)' }, // Distributive 2
47999 { l: 'c1*n + c2*n', r:'(c1+c2)*n'} , // Joining constants
48000 { l: '-v*-c', r:'c*v'} , // Inversion constant and variable 1
48001 { l: '-v*c', r:'-c*v'} , // Inversion constant and variable 2
48002 { l: 'v*-c', r:'-c*v'} , // Inversion constant and variable 3
48003 { l: 'v*c', r:'c*v'} , // Inversion constant and variable 4
48004 { l: '-(-n1*n2)', r:'(n1*n2)'} , // Unary propagation
48005 { l: '-(n1*n2)', r:'(-n1*n2)'} , // Unary propagation
48006 { l: '-(-n1+n2)', r:'(n1-n2)'} , // Unary propagation
48007 { l: '-(n1+n2)', r:'(-n1-n2)'} , // Unary propagation
48008 { l: '(n1^n2)^n3', r:'(n1^(n2*n3))'} , // Power to Power
48009 { l: '-(-n1/n2)', r:'(n1/n2)'} , // Division and Unary
48010 { l: '-(n1/n2)', r:'(-n1/n2)'} ]; // Divisao and Unary
48011
48012 var rulesDistrDiv=[
48013 { l:'(n1/n2 + n3/n4)', r:'((n1*n4 + n3*n2)/(n2*n4))' }, // Sum of fractions
48014 { l:'(n1/n2 + n3)', r:'((n1 + n3*n2)/n2)' }, // Sum fraction with number 1
48015 { l:'(n1 + n2/n3)', r:'((n1*n3 + n2)/n3)' } ]; // Sum fraction with number 1
48016
48017 var rulesSucDiv=[
48018 { l:'(n1/(n2/n3))', r:'((n1*n3)/n2)'} , // Division simplification
48019 { l:'(n1/n2/n3)', r:'(n1/(n2*n3))' } ]
48020
48021 var setRules={}; // rules set in 4 steps.
48022
48023 // All rules => infinite loop
48024 // setRules.allRules =oldRules.concat(rulesFirst,rulesDistrDiv,rulesSucDiv);
48025
48026 setRules.firstRules =oldRules.concat(rulesFirst,rulesSucDiv); // First rule set
48027 setRules.distrDivRules = rulesDistrDiv; // Just distr. div. rules
48028 setRules.sucDivRules = rulesSucDiv; // Jus succ. div. rules
48029 setRules.firstRulesAgain = oldRules.concat(rulesFirst); // Last rules set without succ. div.
48030
48031 // Division simplification
48032
48033 // Second rule set.
48034 // There is no aggregate expression with parentesis, but the only variable can be scattered.
48035 setRules.finalRules=[ simplifyCore, // simplify.rules[0]
48036 { l: 'n*-n', r: '-n^2' }, // Joining multiply with power 1
48037 { l: 'n*n', r: 'n^2' }, // Joining multiply with power 2
48038 simplifyConstant, // simplify.rules[14] old 3rd index in oldRules
48039 { l: 'n*-n^n1', r: '-n^(n1+1)' }, // Joining multiply with power 3
48040 { l: 'n*n^n1', r: 'n^(n1+1)' }, // Joining multiply with power 4
48041 { l: 'n^n1*-n^n2', r: '-n^(n1+n2)' }, // Joining multiply with power 5
48042 { l: 'n^n1*n^n2', r: 'n^(n1+n2)' }, // Joining multiply with power 6
48043 { l: 'n^n1*-n', r: '-n^(n1+1)' }, // Joining multiply with power 7
48044 { l: 'n^n1*n', r: 'n^(n1+1)' }, // Joining multiply with power 8
48045 { l: 'n^n1/-n', r: '-n^(n1-1)' }, // Joining multiply with power 8
48046 { l: 'n^n1/n', r: 'n^(n1-1)' }, // Joining division with power 1
48047 { l: 'n/-n^n1', r: '-n^(1-n1)' }, // Joining division with power 2
48048 { l: 'n/n^n1', r: 'n^(1-n1)' }, // Joining division with power 3
48049 { l: 'n^n1/-n^n2', r: 'n^(n1-n2)' }, // Joining division with power 4
48050 { l: 'n^n1/n^n2', r: 'n^(n1-n2)' }, // Joining division with power 5
48051 { l: 'n1+(-n2*n3)', r: 'n1-n2*n3' }, // Solving useless parenthesis 1
48052 { l: 'v*(-c)', r: '-c*v' }, // Solving useless unary 2
48053 { l: 'n1+-n2', r: 'n1-n2' }, // Solving +- together (new!)
48054 { l: 'v*c', r: 'c*v' }, // inversion constant with variable
48055 { l: '(n1^n2)^n3', r:'(n1^(n2*n3))'}, // Power to Power
48056
48057 ];
48058 return setRules;
48059 } // End rulesRationalize
48060
48061 //---------------------------------------------------------------------------------------
48062 /**
48063 * Expand recursively a tree node for handling with expressions with exponents
48064 * (it's not for constants, symbols or functions with exponents)
48065 * PS: The other parameters are internal for recursion
48066 *
48067 * Syntax:
48068 *
48069 * expandPower(node)
48070 *
48071 * @param {Node} node Current expression node
48072 * @param {node} parent Parent current node inside the recursion
48073 * @param (int} Parent number of chid inside the rercursion
48074 *
48075 * @return {node} node expression with all powers expanded.
48076 */
48077 function expandPower(node,parent,indParent) {
48078 var tp = node.type;
48079 var internal = (arguments.length>1) // TRUE in internal calls
48080
48081 if (tp==='OperatorNode') {
48082 var does = false;
48083 if (node.op==='^') { // First operator: Parenthesis or UnaryMinus
48084 if ( ( node.args[0].type==='ParenthesisNode' ||
48085 node.args[0].type==='OperatorNode' )
48086 && (node.args[1].type==='ConstantNode') ) { // Second operator: Constant
48087 var val = parseFloat(node.args[1].value);
48088 does = (val>=2 && number.isInteger(val));
48089 }
48090 }
48091
48092 if (does) { // Exponent >= 2
48093 //Before:
48094 // operator A --> Subtree
48095 // parent pow
48096 // constant
48097 //
48098 if (val>2) { // Exponent > 2,
48099 //AFTER: (exponent > 2)
48100 // operator A --> Subtree
48101 // parent *
48102 // deep clone (operator A --> Subtree
48103 // pow
48104 // constant - 1
48105 //
48106 var nEsqTopo = node.args[0];
48107 var nDirTopo = new OperatorNode('^', 'pow', [node.args[0].cloneDeep(),new ConstantNode(val-1)]);
48108 node = new OperatorNode('*', 'multiply', [nEsqTopo, nDirTopo]);
48109 } else // Expo = 2 - no power
48110
48111 //AFTER: (exponent = 2)
48112 // operator A --> Subtree
48113 // parent oper
48114 // deep clone (operator A --> Subtree)
48115 //
48116 node = new OperatorNode('*', 'multiply', [node.args[0], node.args[0].cloneDeep()]);
48117
48118 if (internal) // Change parent references in internal recursive calls
48119 if (indParent==='content')
48120 parent.content = node;
48121 else
48122 parent.args[indParent] = node
48123 } // does
48124 } // Operator Node
48125
48126 if (tp==='ParenthesisNode' ) // Recursion
48127 expandPower(node.content,node,'content');
48128 else if (tp!=='ConstantNode' && tp!=='SymbolNode')
48129 for (var i=0;i<node.args.length;i++)
48130 expandPower(node.args[i],node,i);
48131
48132
48133 if (! internal ) return node // return the root node
48134
48135 } // End expandPower
48136
48137
48138 //---------------------------------------------------------------------------------------
48139 /**
48140 * Auxilary function for rationalize
48141 * Convert near canonical polynomial in one variable in a canonical polynomial
48142 * with one term for each exponent in decreasing order
48143 *
48144 * Syntax:
48145 *
48146 * polyToCanonical(node [, coefficients])
48147 *
48148 * @param {Node | string} expr The near canonical polynomial expression to convert in a a canonical polynomial expression
48149 *
48150 * The string or tree expression needs to be at below syntax, with free spaces:
48151 * ( (^(-)? | [+-]? )cte (*)? var (^expo)? | cte )+
48152 * Where 'var' is one variable with any valid name
48153 * 'cte' are real numeric constants with any value. It can be omitted if equal than 1
48154 * 'expo' are integers greater than 0. It can be omitted if equal than 1.
48155 *
48156 * @param {array} coefficients Optional returns coefficients sorted by increased exponent
48157 *
48158 *
48159 * @return {node} new node tree with one variable polynomial or string error.
48160 */
48161 function polyToCanonical(node,coefficients) {
48162 var i;
48163
48164 if (coefficients===undefined)
48165 coefficients = []; // coefficients.
48166
48167 coefficients[0] = 0; // index is the exponent
48168 var o = {};
48169 o.cte=1;
48170 o.oper='+';
48171
48172 // fire: mark with * or ^ when finds * or ^ down tree, reset to "" with + and -.
48173 // It is used to deduce the exponent: 1 for *, 0 for "".
48174 o.fire='';
48175
48176 var maxExpo=0; // maximum exponent
48177 var varname=''; // var name
48178
48179 recurPol(node,null,o);
48180 maxExpo = coefficients.length-1;
48181 var first=true;
48182
48183 for (i=maxExpo;i>=0 ;i--) {
48184 if (coefficients[i]===0) continue;
48185 var n1 = new ConstantNode(
48186 first ? coefficients[i] : Math.abs(coefficients[i]));
48187 var op = coefficients[i]<0 ? '-' : '+';
48188
48189 if (i>0) { // Is not a constant without variable
48190 var n2 = new SymbolNode(varname);
48191 if (i>1) {
48192 var n3 = new ConstantNode(i);
48193 n2 = new OperatorNode('^', 'pow', [n2, n3]);
48194 }
48195 if (coefficients[i]===-1 && first)
48196 n1 = new OperatorNode('-', 'unaryMinus', [n2]);
48197 else if (Math.abs(coefficients[i])===1)
48198 n1 = n2;
48199 else
48200 n1 = new OperatorNode('*', 'multiply', [n1, n2]);
48201 }
48202
48203 var no;
48204 if (first)
48205 no = n1;
48206 else if (op==='+')
48207 no = new OperatorNode('+', 'add', [no, n1]);
48208 else
48209 no = new OperatorNode('-', 'subtract', [no, n1]);
48210
48211 first = false;
48212 } // for
48213
48214 if (first)
48215 return new ConstantNode(0);
48216 else
48217 return no;
48218
48219 /**
48220 * Recursive auxilary function inside polyToCanonical for
48221 * converting expression in canonical form
48222 *
48223 * Syntax:
48224 *
48225 * recurPol(node, noPai, obj)
48226 *
48227 * @param {Node} node The current subpolynomial expression
48228 * @param {Node | Null} noPai The current parent node
48229 * @param {object} obj Object with many internal flags
48230 *
48231 * @return {} No return. If error, throws an exception
48232 */
48233 function recurPol(node,noPai,o) {
48234
48235 var tp = node.type;
48236 if (tp==='FunctionNode') // ***** FunctionName *****
48237 // No function call in polynomial expression
48238 throw new ArgumentsError('There is an unsolved function call')
48239
48240 else if (tp==='OperatorNode') { // ***** OperatorName *****
48241 if ('+-*^'.indexOf(node.op) === -1) throw new ArgumentsError('Operator ' + node.op + ' invalid');
48242
48243 if (noPai!==null) {
48244 // -(unary),^ : children of *,+,-
48245 if ( (node.fn==='unaryMinus' || node.fn==='pow') && noPai.fn !=='add' &&
48246 noPai.fn!=='subtract' && noPai.fn!=='multiply' )
48247 throw new ArgumentsError('Invalid ' + node.op + ' placing')
48248
48249 // -,+,* : children of +,-
48250 if ((node.fn==='subtract' || node.fn==='add' || node.fn==='multiply') &&
48251 noPai.fn!=='add' && noPai.fn!=='subtract' )
48252 throw new ArgumentsError('Invalid ' + node.op + ' placing');
48253
48254 // -,+ : first child
48255 if ((node.fn==='subtract' || node.fn==='add' ||
48256 node.fn==='unaryMinus' ) && o.noFil!==0 )
48257 throw new ArgumentsError('Invalid ' + node.op + ' placing')
48258 } // Has parent
48259
48260 // Firers: ^,* Old: ^,&,-(unary): firers
48261 if (node.op==='^' || node.op==='*') o.fire = node.op;
48262
48263 for (var i=0;i<node.args.length;i++) {
48264 // +,-: reset fire
48265 if (node.fn==='unaryMinus') o.oper='-';
48266 if (node.op==='+' || node.fn==='subtract' ) {
48267 o.fire = '';
48268 o.cte = 1; // default if there is no constant
48269 o.oper = (i===0 ? '+' : node.op);
48270 }
48271 o.noFil = i; // number of son
48272 recurPol(node.args[i],node,o);
48273 } // for in children
48274
48275 } else if (tp==='SymbolNode') { // ***** SymbolName *****
48276 if (node.name !== varname && varname!=='')
48277 throw new ArgumentsError('There is more than one variable')
48278 varname = node.name;
48279 if (noPai === null) {
48280 coefficients[1] = 1;
48281 return;
48282 }
48283
48284 // ^: Symbol is First child
48285 if (noPai.op==='^' && o.noFil!==0 )
48286 throw new ArgumentsError('In power the variable should be the first parameter')
48287
48288 // *: Symbol is Second child
48289 if (noPai.op==='*' && o.noFil!==1 )
48290 throw new ArgumentsError('In multiply the variable should be the second parameter')
48291
48292 // Symbol: firers '',* => it means there is no exponent above, so it's 1 (cte * var)
48293 if (o.fire==='' || o.fire==='*' ) {
48294 if (maxExpo<1) coefficients[1]=0;
48295 coefficients[1] += o.cte* (o.oper==='+' ? 1 : -1);
48296 maxExpo = Math.max(1,maxExpo);
48297 }
48298
48299 } else if (tp==='ConstantNode') {
48300 var valor = parseFloat(node.value);
48301 if (noPai === null) {
48302 coefficients[0] = valor;
48303 return;
48304 }
48305 if (noPai.op==='^') {
48306 // cte: second child of power
48307 if (o.noFil!==1) throw new ArgumentsError('Constant cannot be powered')
48308
48309 if (! number.isInteger(valor) || valor<=0 )
48310 throw new ArgumentsError('Non-integer exponent is not allowed');
48311
48312 for (var i=maxExpo+1;i<valor;i++) coefficients[i]=0;
48313 if (valor>maxExpo) coefficients[valor]=0;
48314 coefficients[valor] += o.cte * (o.oper==='+' ? 1 : -1)
48315 maxExpo = Math.max(valor,maxExpo);
48316 return;
48317 }
48318 o.cte = valor;
48319
48320 // Cte: firer '' => There is no exponent and no multiplication, so the exponent is 0.
48321 if (o.fire==='')
48322 coefficients[0] += o.cte * (o.oper==='+'? 1 : -1);
48323
48324
48325 } else
48326 throw new ArgumentsError('Type ' + tp + ' is not allowed');
48327 return;
48328 } // End of recurPol
48329
48330 } // End of polyToCanonical
48331
48332 return rationalize;
48333} // end of factory
48334
48335exports.name = 'rationalize';
48336exports.factory = factory;
48337
48338/***/ }),
48339/* 412 */
48340/***/ (function(module, exports, __webpack_require__) {
48341
48342"use strict";
48343
48344
48345function factory (type, config, load, typed) {
48346
48347 var matrix = load(__webpack_require__(0));
48348 var zeros = load(__webpack_require__(40));
48349 var eye = load(__webpack_require__(62));
48350 var clone = load(__webpack_require__(123));
48351
48352 var isZero = load(__webpack_require__(83));
48353 var isPositive = load(__webpack_require__(57));
48354 var unequal = load(__webpack_require__(124));
48355
48356 var abs = load(__webpack_require__(28));
48357 var sign = load(__webpack_require__(125));
48358 var sqrt = load(__webpack_require__(50));
48359 var conj = load(__webpack_require__(126));
48360
48361 var unaryMinus = load(__webpack_require__(35));
48362 var addScalar = load(__webpack_require__(16));
48363 var divideScalar = load(__webpack_require__(14));
48364 var multiplyScalar = load(__webpack_require__(22));
48365 var subtract = load(__webpack_require__(21));
48366
48367
48368 /**
48369 * Calculate the Matrix QR decomposition. Matrix `A` is decomposed in
48370 * two matrices (`Q`, `R`) where `Q` is an
48371 * orthogonal matrix and `R` is an upper triangular matrix.
48372 *
48373 * Syntax:
48374 *
48375 * math.qr(A);
48376 *
48377 * Example:
48378 *
48379 * var m = [
48380 * [1, -1, 4],
48381 * [1, 4, -2],
48382 * [1, 4, 2],
48383 * [1, -1, 0]
48384 * ];
48385 * var result = math.qr(m);
48386 * // r = {
48387 * // Q: [
48388 * // [0.5, -0.5, 0.5],
48389 * // [0.5, 0.5, -0.5],
48390 * // [0.5, 0.5, 0.5],
48391 * // [0.5, -0.5, -0.5],
48392 * // ],
48393 * // R: [
48394 * // [2, 3, 2],
48395 * // [0, 5, -2],
48396 * // [0, 0, 4],
48397 * // [0, 0, 0]
48398 * // ]
48399 * // }
48400 *
48401 * See also:
48402 *
48403 * lu
48404 *
48405 * @param {Matrix | Array} A A two dimensional matrix or array
48406 * for which to get the QR decomposition.
48407 *
48408 * @return {{Q: Array | Matrix, R: Array | Matrix}} Q: the orthogonal
48409 * matrix and R: the upper triangular matrix
48410 */
48411 var qr = typed('qr', {
48412
48413 'DenseMatrix': function (m) {
48414 return _denseQR(m);
48415 },
48416
48417 'SparseMatrix': function (m) {
48418 return _sparseQR(m);
48419 },
48420
48421 'Array': function (a) {
48422 // create dense matrix from array
48423 var m = matrix(a);
48424 // lup, use matrix implementation
48425 var r = _denseQR(m);
48426 // result
48427 return {
48428 Q: r.Q.valueOf(),
48429 R: r.R.valueOf()
48430 };
48431 }
48432 });
48433
48434 var _denseQR = function (m) {
48435
48436 // rows & columns (m x n)
48437 var rows = m._size[0]; // m
48438 var cols = m._size[1]; // n
48439
48440 var Q = eye([rows], 'dense');
48441 var Qdata = Q._data;
48442
48443 var R = m.clone();
48444 var Rdata = R._data;
48445
48446 // vars
48447 var i, j, k;
48448
48449 var w = zeros([rows], '');
48450
48451 for (k = 0; k < Math.min(cols, rows); ++k) {
48452
48453 /*
48454 * **k-th Household matrix**
48455 *
48456 * The matrix I - 2*v*transpose(v)
48457 * x = first column of A
48458 * x1 = first element of x
48459 * alpha = x1 / |x1| * |x|
48460 * e1 = tranpose([1, 0, 0, ...])
48461 * u = x - alpha * e1
48462 * v = u / |u|
48463 *
48464 * Household matrix = I - 2 * v * tranpose(v)
48465 *
48466 * * Initially Q = I and R = A.
48467 * * Household matrix is a reflection in a plane normal to v which
48468 * will zero out all but the top right element in R.
48469 * * Appplying reflection to both Q and R will not change product.
48470 * * Repeat this process on the (1,1) minor to get R as an upper
48471 * triangular matrix.
48472 * * Reflections leave the magnitude of the columns of Q unchanged
48473 * so Q remains othoganal.
48474 *
48475 */
48476
48477 var pivot = Rdata[k][k];
48478 var sgn = unaryMinus(sign(pivot));
48479 var conjSgn = conj(sgn);
48480
48481 var alphaSquared = 0;
48482
48483 for(i = k; i < rows; i++) {
48484 alphaSquared = addScalar(alphaSquared, multiplyScalar(Rdata[i][k], conj(Rdata[i][k])));
48485 }
48486
48487 var alpha = multiplyScalar(sgn, sqrt(alphaSquared));
48488
48489
48490 if (!isZero(alpha)) {
48491
48492 // first element in vector u
48493 var u1 = subtract(pivot, alpha);
48494
48495 // w = v * u1 / |u| (only elements k to (rows-1) are used)
48496 w[k] = 1;
48497
48498 for (i = k+1; i < rows; i++) {
48499 w[i] = divideScalar(Rdata[i][k], u1);
48500 }
48501
48502 // tau = - conj(u1 / alpha)
48503 var tau = unaryMinus(conj(divideScalar(u1, alpha)));
48504
48505 var s;
48506
48507 /*
48508 * tau and w have been choosen so that
48509 *
48510 * 2 * v * tranpose(v) = tau * w * tranpose(w)
48511 */
48512
48513 /*
48514 * -- calculate R = R - tau * w * tranpose(w) * R --
48515 * Only do calculation with rows k to (rows-1)
48516 * Additionally columns 0 to (k-1) will not be changed by this
48517 * multiplication so do not bother recalculating them
48518 */
48519 for (j = k; j < cols; j++) {
48520 s = 0.0;
48521
48522 // calculate jth element of [tranpose(w) * R]
48523 for (i = k; i < rows; i++) {
48524 s = addScalar(s, multiplyScalar(conj(w[i]), Rdata[i][j]));
48525 }
48526
48527 // calculate the jth element of [tau * transpose(w) * R]
48528 s = multiplyScalar(s, tau);
48529
48530 for (i = k; i < rows; i++) {
48531 Rdata[i][j] = multiplyScalar(
48532 subtract(Rdata[i][j], multiplyScalar(w[i], s)),
48533 conjSgn
48534 );
48535 }
48536 }
48537 /*
48538 * -- calculate Q = Q - tau * Q * w * transpose(w) --
48539 * Q is a square matrix (rows x rows)
48540 * Only do calculation with columns k to (rows-1)
48541 * Additionally rows 0 to (k-1) will not be changed by this
48542 * multiplication so do not bother recalculating them
48543 */
48544 for (i = 0; i < rows; i++) {
48545 s = 0.0;
48546
48547 // calculate ith element of [Q * w]
48548 for (j = k; j < rows; j++) {
48549 s = addScalar(s, multiplyScalar(Qdata[i][j], w[j]));
48550 }
48551
48552 // calculate the ith element of [tau * Q * w]
48553 s = multiplyScalar(s, tau);
48554
48555 for (j = k; j < rows; ++j) {
48556 Qdata[i][j] = divideScalar(
48557 subtract(Qdata[i][j], multiplyScalar(s, conj(w[j]))),
48558 conjSgn
48559 );
48560 }
48561
48562 }
48563 }
48564
48565 }
48566
48567 // coerse almost zero elements to zero
48568 // TODO I feel uneasy just zeroing these values
48569 for (i = 0; i < rows; ++i) {
48570 for (j = 0; j < i && j < cols; ++j) {
48571 if (unequal(0, divideScalar(Rdata[i][j], 1e5))) {
48572 throw new Error('math.qr(): unknown error - ' +
48573 'R is not lower triangular (element (' +
48574 i + ', ' + j + ') = ' + Rdata[i][j] + ')'
48575 );
48576 }
48577 Rdata[i][j] = multiplyScalar(Rdata[i][j], 0);
48578 }
48579 }
48580
48581 // return matrices
48582 return {
48583 Q: Q,
48584 R: R,
48585 toString: function () {
48586 return 'Q: ' + this.Q.toString() + '\nR: ' + this.R.toString();
48587 }
48588 };
48589 };
48590
48591 var _sparseQR = function (m) {
48592
48593 throw new Error('qr not implemented for sparse matrices yet');
48594
48595 };
48596
48597 return qr;
48598}
48599
48600exports.name = 'qr';
48601exports.factory = factory;
48602
48603
48604/***/ }),
48605/* 413 */
48606/***/ (function(module, exports, __webpack_require__) {
48607
48608"use strict";
48609
48610
48611function factory (type, config, load) {
48612
48613 var cs_amd = load(__webpack_require__(414));
48614 var cs_permute = load(__webpack_require__(416));
48615 var cs_etree = load(__webpack_require__(417));
48616 var cs_post = load(__webpack_require__(418));
48617 var cs_counts = load(__webpack_require__(419));
48618
48619 /**
48620 * Symbolic ordering and analysis for QR and LU decompositions.
48621 *
48622 * @param {Number} order The ordering strategy (see cs_amd for more details)
48623 * @param {Matrix} a The A matrix
48624 * @param {boolean} qr Symbolic ordering and analysis for QR decomposition (true) or
48625 * symbolic ordering and analysis for LU decomposition (false)
48626 *
48627 * @return {Object} The Symbolic ordering and analysis for matrix A
48628 *
48629 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
48630 */
48631 var cs_sqr = function (order, a, qr) {
48632 // a arrays
48633 var aptr = a._ptr;
48634 var asize = a._size;
48635 // columns
48636 var n = asize[1];
48637 // vars
48638 var k;
48639 // symbolic analysis result
48640 var s = {};
48641 // fill-reducing ordering
48642 s.q = cs_amd(order, a);
48643 // validate results
48644 if (order && !s.q)
48645 return null;
48646 // QR symbolic analysis
48647 if (qr) {
48648 // apply permutations if needed
48649 var c = order ? cs_permute(a, null, s.q, 0) : a;
48650 // etree of C'*C, where C=A(:,q)
48651 s.parent = cs_etree(c, 1);
48652 // post order elimination tree
48653 var post = cs_post (s.parent, n);
48654 // col counts chol(C'*C)
48655 s.cp = cs_counts(c, s.parent, post, 1);
48656 // check we have everything needed to calculate number of nonzero elements
48657 if (c && s.parent && s.cp && _vcount(c, s)) {
48658 // calculate number of nonzero elements
48659 for (s.unz = 0, k = 0; k < n; k++)
48660 s.unz += s.cp[k];
48661 }
48662 }
48663 else {
48664 // for LU factorization only, guess nnz(L) and nnz(U)
48665 s.unz = 4 * (aptr[n]) + n;
48666 s.lnz = s.unz;
48667 }
48668 // return result S
48669 return s;
48670 };
48671
48672 /**
48673 * Compute nnz(V) = s.lnz, s.pinv, s.leftmost, s.m2 from A and s.parent
48674 */
48675 var _vcount = function (a, s) {
48676 // a arrays
48677 var aptr = a._ptr;
48678 var aindex = a._index;
48679 var asize = a._size;
48680 // rows & columns
48681 var m = asize[0];
48682 var n = asize[1];
48683 // initialize s arrays
48684 s.pinv = []; // (m + n);
48685 s.leftmost = []; // (m);
48686 // vars
48687 var parent = s.parent;
48688 var pinv = s.pinv;
48689 var leftmost = s.leftmost;
48690 // workspace, next: first m entries, head: next n entries, tail: next n entries, nque: next n entries
48691 var w = []; // (m + 3 * n);
48692 var next = 0;
48693 var head = m;
48694 var tail = m + n;
48695 var nque = m + 2 * n;
48696 // vars
48697 var i, k, p, p0, p1;
48698 // initialize w
48699 for (k = 0; k < n; k++) {
48700 // queue k is empty
48701 w[head + k] = -1;
48702 w[tail + k] = -1;
48703 w[nque + k] = 0;
48704 }
48705 // initialize row arrays
48706 for (i = 0; i < m; i++)
48707 leftmost[i] = -1;
48708 // loop columns backwards
48709 for (k = n - 1; k >= 0; k--) {
48710 // values & index for column k
48711 for (p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) {
48712 // leftmost[i] = min(find(A(i,:)))
48713 leftmost[aindex[p]] = k;
48714 }
48715 }
48716 // scan rows in reverse order
48717 for (i = m - 1; i >= 0; i--) {
48718 // row i is not yet ordered
48719 pinv[i] = -1;
48720 k = leftmost[i];
48721 // check row i is empty
48722 if (k == -1)
48723 continue;
48724 // first row in queue k
48725 if (w[nque + k]++ === 0)
48726 w[tail + k] = i;
48727 // put i at head of queue k
48728 w[next + i] = w[head + k];
48729 w[head + k] = i;
48730 }
48731 s.lnz = 0;
48732 s.m2 = m;
48733 // find row permutation and nnz(V)
48734 for (k = 0; k < n; k++) {
48735 // remove row i from queue k
48736 i = w[head + k];
48737 // count V(k,k) as nonzero
48738 s.lnz++;
48739 // add a fictitious row
48740 if (i < 0)
48741 i = s.m2++;
48742 // associate row i with V(:,k)
48743 pinv[i] = k;
48744 // skip if V(k+1:m,k) is empty
48745 if (--nque[k] <= 0)
48746 continue;
48747 // nque[k] is nnz (V(k+1:m,k))
48748 s.lnz += w[nque + k];
48749 // move all rows to parent of k
48750 var pa = parent[k];
48751 if (pa != -1) {
48752 if (w[nque + pa] === 0)
48753 w[tail + pa] = w[tail + k];
48754 w[next + w[tail + k]] = w[head + pa];
48755 w[head + pa] = w[next + i];
48756 w[nque + pa] += w[nque + k];
48757 }
48758 }
48759 for (i = 0; i < m; i++) {
48760 if (pinv[i] < 0)
48761 pinv[i] = k++;
48762 }
48763 return true;
48764 };
48765
48766 return cs_sqr;
48767}
48768
48769exports.name = 'cs_sqr';
48770exports.path = 'sparse';
48771exports.factory = factory;
48772
48773
48774/***/ }),
48775/* 414 */
48776/***/ (function(module, exports, __webpack_require__) {
48777
48778"use strict";
48779
48780
48781function factory (type, config, load) {
48782
48783 var cs_flip = load(__webpack_require__(84));
48784 var cs_fkeep = load(__webpack_require__(415));
48785 var cs_tdfs = load(__webpack_require__(129));
48786
48787 var add = load(__webpack_require__(20));
48788 var multiply = load(__webpack_require__(12));
48789 var transpose = load(__webpack_require__(67));
48790
48791 /**
48792 * Approximate minimum degree ordering. The minimum degree algorithm is a widely used
48793 * heuristic for finding a permutation P so that P*A*P' has fewer nonzeros in its factorization
48794 * than A. It is a gready method that selects the sparsest pivot row and column during the course
48795 * of a right looking sparse Cholesky factorization.
48796 *
48797 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
48798 *
48799 * @param {Number} order 0: Natural, 1: Cholesky, 2: LU, 3: QR
48800 * @param {Matrix} m Sparse Matrix
48801 *
48802 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
48803 */
48804 var cs_amd = function (order, a) {
48805 // check input parameters
48806 if (!a || order <= 0 || order > 3)
48807 return null;
48808 // a matrix arrays
48809 var asize = a._size;
48810 // rows and columns
48811 var m = asize[0];
48812 var n = asize[1];
48813 // initialize vars
48814 var lemax = 0;
48815 // dense threshold
48816 var dense = Math.max(16, 10 * Math.sqrt(n));
48817 dense = Math.min(n - 2, dense);
48818 // create target matrix C
48819 var cm = _createTargetMatrix(order, a, m, n, dense);
48820 // drop diagonal entries
48821 cs_fkeep(cm, _diag, null);
48822 // C matrix arrays
48823 var cindex = cm._index;
48824 var cptr = cm._ptr;
48825
48826 // number of nonzero elements in C
48827 var cnz = cptr[n];
48828
48829 // allocate result (n+1)
48830 var P = [];
48831
48832 // create workspace (8 * (n + 1))
48833 var W = [];
48834 var len = 0; // first n + 1 entries
48835 var nv = n + 1; // next n + 1 entries
48836 var next = 2 * (n + 1); // next n + 1 entries
48837 var head = 3 * (n + 1); // next n + 1 entries
48838 var elen = 4 * (n + 1); // next n + 1 entries
48839 var degree = 5 * (n + 1); // next n + 1 entries
48840 var w = 6 * (n + 1); // next n + 1 entries
48841 var hhead = 7 * (n + 1); // last n + 1 entries
48842
48843 // use P as workspace for last
48844 var last = P;
48845
48846 // initialize quotient graph
48847 var mark = _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree);
48848
48849 // initialize degree lists
48850 var nel = _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next);
48851
48852 // minimum degree node
48853 var mindeg = 0;
48854
48855 // vars
48856 var i, j, k, k1, k2, e, pj, ln, nvi, pk, eln, p1, p2, pn, h, d;
48857
48858 // while (selecting pivots) do
48859 while (nel < n) {
48860 // select node of minimum approximate degree. amd() is now ready to start eliminating the graph. It first
48861 // finds a node k of minimum degree and removes it from its degree list. The variable nel keeps track of thow
48862 // many nodes have been eliminated.
48863 for (k = -1; mindeg < n && (k = W[head + mindeg]) == -1; mindeg++);
48864 if (W[next + k] != -1)
48865 last[W[next + k]] = -1;
48866 // remove k from degree list
48867 W[head + mindeg] = W[next + k];
48868 // elenk = |Ek|
48869 var elenk = W[elen + k];
48870 // # of nodes k represents
48871 var nvk = W[nv + k];
48872 // W[nv + k] nodes of A eliminated
48873 nel += nvk;
48874
48875 // Construct a new element. The new element Lk is constructed in place if |Ek| = 0. nv[i] is
48876 // negated for all nodes i in Lk to flag them as members of this set. Each node i is removed from the
48877 // degree lists. All elements e in Ek are absorved into element k.
48878 var dk = 0;
48879 // flag k as in Lk
48880 W[nv + k] = -nvk;
48881 var p = cptr[k];
48882 // do in place if W[elen + k] == 0
48883 var pk1 = (elenk === 0) ? p : cnz;
48884 var pk2 = pk1;
48885 for (k1 = 1; k1 <= elenk + 1; k1++) {
48886 if (k1 > elenk) {
48887 // search the nodes in k
48888 e = k;
48889 // list of nodes starts at cindex[pj]
48890 pj = p;
48891 // length of list of nodes in k
48892 ln = W[len + k] - elenk;
48893 }
48894 else {
48895 // search the nodes in e
48896 e = cindex[p++];
48897 pj = cptr[e];
48898 // length of list of nodes in e
48899 ln = W[len + e];
48900 }
48901 for (k2 = 1; k2 <= ln; k2++) {
48902 i = cindex[pj++];
48903 // check node i dead, or seen
48904 if ((nvi = W[nv + i]) <= 0)
48905 continue;
48906 // W[degree + Lk] += size of node i
48907 dk += nvi;
48908 // negate W[nv + i] to denote i in Lk
48909 W[nv + i] = -nvi;
48910 // place i in Lk
48911 cindex[pk2++] = i;
48912 if (W[next + i] != -1)
48913 last[W[next + i]] = last[i];
48914 // check we need to remove i from degree list
48915 if (last[i] != -1)
48916 W[next + last[i]] = W[next + i];
48917 else
48918 W[head + W[degree + i]] = W[next + i];
48919 }
48920 if (e != k) {
48921 // absorb e into k
48922 cptr[e] = cs_flip(k);
48923 // e is now a dead element
48924 W[w + e] = 0;
48925 }
48926 }
48927 // cindex[cnz...nzmax] is free
48928 if (elenk !== 0)
48929 cnz = pk2;
48930 // external degree of k - |Lk\i|
48931 W[degree + k] = dk;
48932 // element k is in cindex[pk1..pk2-1]
48933 cptr[k] = pk1;
48934 W[len + k] = pk2 - pk1;
48935 // k is now an element
48936 W[elen + k] = -2;
48937
48938 // Find set differences. The scan1 function now computes the set differences |Le \ Lk| for all elements e. At the start of the
48939 // scan, no entry in the w array is greater than or equal to mark.
48940
48941 // clear w if necessary
48942 mark = _wclear(mark, lemax, W, w, n);
48943 // scan 1: find |Le\Lk|
48944 for (pk = pk1; pk < pk2; pk++) {
48945 i = cindex[pk];
48946 // check if W[elen + i] empty, skip it
48947 if ((eln = W[elen + i]) <= 0)
48948 continue;
48949 // W[nv + i] was negated
48950 nvi = -W[nv + i];
48951 var wnvi = mark - nvi;
48952 // scan Ei
48953 for (p = cptr[i], p1 = cptr[i] + eln - 1; p <= p1; p++) {
48954 e = cindex[p];
48955 if (W[w + e] >= mark) {
48956 // decrement |Le\Lk|
48957 W[w + e] -= nvi;
48958 }
48959 else if (W[w + e] !== 0) {
48960 // ensure e is a live element, 1st time e seen in scan 1
48961 W[w + e] = W[degree + e] + wnvi;
48962 }
48963 }
48964 }
48965
48966 // degree update
48967 // The second pass computes the approximate degree di, prunes the sets Ei and Ai, and computes a hash
48968 // function h(i) for all nodes in Lk.
48969
48970 // scan2: degree update
48971 for (pk = pk1; pk < pk2; pk++) {
48972 // consider node i in Lk
48973 i = cindex[pk];
48974 p1 = cptr[i];
48975 p2 = p1 + W[elen + i] - 1;
48976 pn = p1;
48977 // scan Ei
48978 for (h = 0, d = 0, p = p1; p <= p2; p++) {
48979 e = cindex[p];
48980 // check e is an unabsorbed element
48981 if (W[w + e] !== 0) {
48982 // dext = |Le\Lk|
48983 var dext = W[w + e] - mark;
48984 if (dext > 0) {
48985 // sum up the set differences
48986 d += dext;
48987 // keep e in Ei
48988 cindex[pn++] = e;
48989 // compute the hash of node i
48990 h += e;
48991 }
48992 else {
48993 // aggressive absorb. e->k
48994 cptr[e] = cs_flip(k);
48995 // e is a dead element
48996 W[w + e] = 0;
48997 }
48998 }
48999 }
49000 // W[elen + i] = |Ei|
49001 W[elen + i] = pn - p1 + 1;
49002 var p3 = pn;
49003 var p4 = p1 + W[len + i];
49004 // prune edges in Ai
49005 for (p = p2 + 1; p < p4; p++) {
49006 j = cindex[p];
49007 // check node j dead or in Lk
49008 var nvj = W[nv + j];
49009 if (nvj <= 0)
49010 continue;
49011 // degree(i) += |j|
49012 d += nvj;
49013 // place j in node list of i
49014 cindex[pn++] = j;
49015 // compute hash for node i
49016 h += j;
49017 }
49018 // check for mass elimination
49019 if (d === 0) {
49020 // absorb i into k
49021 cptr[i] = cs_flip(k);
49022 nvi = -W[nv + i];
49023 // |Lk| -= |i|
49024 dk -= nvi;
49025 // |k| += W[nv + i]
49026 nvk += nvi;
49027 nel += nvi;
49028 W[nv + i] = 0;
49029 // node i is dead
49030 W[elen + i] = -1;
49031 }
49032 else {
49033 // update degree(i)
49034 W[degree + i] = Math.min(W[degree + i], d);
49035 // move first node to end
49036 cindex[pn] = cindex[p3];
49037 // move 1st el. to end of Ei
49038 cindex[p3] = cindex[p1];
49039 // add k as 1st element in of Ei
49040 cindex[p1] = k;
49041 // new len of adj. list of node i
49042 W[len + i] = pn - p1 + 1;
49043 // finalize hash of i
49044 h = (h < 0 ? -h : h) % n;
49045 // place i in hash bucket
49046 W[next + i] = W[hhead + h];
49047 W[hhead + h] = i;
49048 // save hash of i in last[i]
49049 last[i] = h;
49050 }
49051 }
49052 // finalize |Lk|
49053 W[degree + k] = dk;
49054 lemax = Math.max(lemax, dk);
49055 // clear w
49056 mark = _wclear(mark + lemax, lemax, W, w, n);
49057
49058 // Supernode detection. Supernode detection relies on the hash function h(i) computed for each node i.
49059 // If two nodes have identical adjacency lists, their hash functions wil be identical.
49060 for (pk = pk1; pk < pk2; pk++) {
49061 i = cindex[pk];
49062 // check i is dead, skip it
49063 if (W[nv + i] >= 0)
49064 continue;
49065 // scan hash bucket of node i
49066 h = last[i];
49067 i = W[hhead + h];
49068 // hash bucket will be empty
49069 W[hhead + h] = -1;
49070 for (; i != -1 && W[next + i] != -1; i = W[next + i], mark++) {
49071 ln = W[len + i];
49072 eln = W[elen + i];
49073 for (p = cptr[i] + 1; p <= cptr[i] + ln - 1; p++)
49074 W[w + cindex[p]] = mark;
49075 var jlast = i;
49076 // compare i with all j
49077 for (j = W[next + i]; j != -1; ) {
49078 var ok = W[len + j] === ln && W[elen + j] === eln;
49079 for (p = cptr[j] + 1; ok && p <= cptr[j] + ln - 1; p++) {
49080 // compare i and j
49081 if (W[w + cindex[p]] != mark)
49082 ok = 0;
49083 }
49084 // check i and j are identical
49085 if (ok) {
49086 // absorb j into i
49087 cptr[j] = cs_flip(i);
49088 W[nv + i] += W[nv + j];
49089 W[nv + j] = 0;
49090 // node j is dead
49091 W[elen + j] = -1;
49092 // delete j from hash bucket
49093 j = W[next + j];
49094 W[next + jlast] = j;
49095 }
49096 else {
49097 // j and i are different
49098 jlast = j;
49099 j = W[next + j];
49100 }
49101 }
49102 }
49103 }
49104
49105 // Finalize new element. The elimination of node k is nearly complete. All nodes i in Lk are scanned one last time.
49106 // Node i is removed from Lk if it is dead. The flagged status of nv[i] is cleared.
49107 for (p = pk1, pk = pk1; pk < pk2; pk++) {
49108 i = cindex[pk];
49109 // check i is dead, skip it
49110 if ((nvi = -W[nv + i]) <= 0)
49111 continue;
49112 // restore W[nv + i]
49113 W[nv + i] = nvi;
49114 // compute external degree(i)
49115 d = W[degree + i] + dk - nvi;
49116 d = Math.min(d, n - nel - nvi);
49117 if (W[head + d] != -1)
49118 last[W[head + d]] = i;
49119 // put i back in degree list
49120 W[next + i] = W[head + d];
49121 last[i] = -1;
49122 W[head + d] = i;
49123 // find new minimum degree
49124 mindeg = Math.min(mindeg, d);
49125 W[degree + i] = d;
49126 // place i in Lk
49127 cindex[p++] = i;
49128 }
49129 // # nodes absorbed into k
49130 W[nv + k] = nvk;
49131 // length of adj list of element k
49132 if ((W[len + k] = p - pk1) === 0) {
49133 // k is a root of the tree
49134 cptr[k] = -1;
49135 // k is now a dead element
49136 W[w + k] = 0;
49137 }
49138 if (elenk !== 0) {
49139 // free unused space in Lk
49140 cnz = p;
49141 }
49142 }
49143
49144 // Postordering. The elimination is complete, but no permutation has been computed. All that is left
49145 // of the graph is the assembly tree (ptr) and a set of dead nodes and elements (i is a dead node if
49146 // nv[i] is zero and a dead element if nv[i] > 0). It is from this information only that the final permutation
49147 // is computed. The tree is restored by unflipping all of ptr.
49148
49149 // fix assembly tree
49150 for (i = 0; i < n; i++)
49151 cptr[i] = cs_flip(cptr[i]);
49152 for (j = 0; j <= n; j++)
49153 W[head + j] = -1;
49154 // place unordered nodes in lists
49155 for (j = n; j >= 0; j--) {
49156 // skip if j is an element
49157 if (W[nv + j] > 0)
49158 continue;
49159 // place j in list of its parent
49160 W[next + j] = W[head + cptr[j]];
49161 W[head + cptr[j]] = j;
49162 }
49163 // place elements in lists
49164 for (e = n; e >= 0; e--) {
49165 // skip unless e is an element
49166 if (W[nv + e] <= 0)
49167 continue;
49168 if (cptr[e] != -1) {
49169 // place e in list of its parent
49170 W[next + e] = W[head + cptr[e]];
49171 W[head + cptr[e]] = e;
49172 }
49173 }
49174 // postorder the assembly tree
49175 for (k = 0, i = 0; i <= n; i++) {
49176 if (cptr[i] == -1)
49177 k = cs_tdfs(i, k, W, head, next, P, w);
49178 }
49179 // remove last item in array
49180 P.splice(P.length - 1, 1);
49181 // return P
49182 return P;
49183 };
49184
49185 /**
49186 * 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
49187 * vector P. The amd algorithm operates on a symmetrix matrix, so one of three symmetric matrices is formed.
49188 *
49189 * Order: 0
49190 * A natural ordering P=null matrix is returned.
49191 *
49192 * Order: 1
49193 * Matrix must be square. This is appropriate for a Cholesky or LU factorization.
49194 * P = M + M'
49195 *
49196 * Order: 2
49197 * Dense columns from M' are dropped, M recreated from M'. This is appropriatefor LU factorization of unsymmetric matrices.
49198 * P = M' * M
49199 *
49200 * Order: 3
49201 * 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.
49202 * P = M' * M
49203 */
49204 var _createTargetMatrix = function (order, a, m, n, dense) {
49205 // compute A'
49206 var at = transpose(a);
49207
49208 // check order = 1, matrix must be square
49209 if (order === 1 && n === m) {
49210 // C = A + A'
49211 return add(a, at);
49212 }
49213
49214 // check order = 2, drop dense columns from M'
49215 if (order == 2) {
49216 // transpose arrays
49217 var tindex = at._index;
49218 var tptr = at._ptr;
49219 // new column index
49220 var p2 = 0;
49221 // loop A' columns (rows)
49222 for (var j = 0; j < m; j++) {
49223 // column j of AT starts here
49224 var p = tptr[j];
49225 // new column j starts here
49226 tptr[j] = p2;
49227 // skip dense col j
49228 if (tptr[j + 1] - p > dense)
49229 continue;
49230 // map rows in column j of A
49231 for (var p1 = tptr[j + 1]; p < p1; p++)
49232 tindex[p2++] = tindex[p];
49233 }
49234 // finalize AT
49235 tptr[m] = p2;
49236 // recreate A from new transpose matrix
49237 a = transpose(at);
49238 // use A' * A
49239 return multiply(at, a);
49240 }
49241
49242 // use A' * A, square or rectangular matrix
49243 return multiply(at, a);
49244 };
49245
49246 /**
49247 * Initialize quotient graph. There are four kind of nodes and elements that must be represented:
49248 *
49249 * - 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.
49250 * - A dead node i is one that has been removed from the graph, having been absorved into r = flip(ptr[i]).
49251 * - A live element e is one that is in the graph, having been formed when node e was selected as the pivot.
49252 * - A dead element e is one that has benn absorved into a subsequent element s = flip(ptr[e]).
49253 */
49254 var _initializeQuotientGraph = function (n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree) {
49255 // Initialize quotient graph
49256 for (var k = 0; k < n; k++)
49257 W[len + k] = cptr[k + 1] - cptr[k];
49258 W[len + n] = 0;
49259 // initialize workspace
49260 for (var i = 0; i <= n; i++) {
49261 // degree list i is empty
49262 W[head + i] = -1;
49263 last[i] = -1;
49264 W[next + i] = -1;
49265 // hash list i is empty
49266 W[hhead + i] = -1;
49267 // node i is just one node
49268 W[nv + i] = 1;
49269 // node i is alive
49270 W[w + i] = 1;
49271 // Ek of node i is empty
49272 W[elen + i] = 0;
49273 // degree of node i
49274 W[degree + i] = W[len + i];
49275 }
49276 // clear w
49277 var mark = _wclear(0, 0, W, w, n);
49278 // n is a dead element
49279 W[elen + n] = -2;
49280 // n is a root of assembly tree
49281 cptr[n] = -1;
49282 // n is a dead element
49283 W[w + n] = 0;
49284 // return mark
49285 return mark;
49286 };
49287
49288 /**
49289 * Initialize degree lists. Each node is placed in its degree lists. Nodes of zero degree are eliminated immediately. Nodes with
49290 * degree >= dense are alsol eliminated and merged into a placeholder node n, a dead element. Thes nodes will appera last in the
49291 * output permutation p.
49292 */
49293 var _initializeDegreeLists = function (n, cptr, W, degree, elen, w, dense, nv, head, last, next) {
49294 // result
49295 var nel = 0;
49296 // loop columns
49297 for (var i = 0; i < n; i++) {
49298 // degree @ i
49299 var d = W[degree + i];
49300 // check node i is empty
49301 if (d === 0) {
49302 // element i is dead
49303 W[elen + i] = -2;
49304 nel++;
49305 // i is a root of assembly tree
49306 cptr[i] = -1;
49307 W[w + i] = 0;
49308 }
49309 else if (d > dense) {
49310 // absorb i into element n
49311 W[nv + i] = 0;
49312 // node i is dead
49313 W[elen + i] = -1;
49314 nel++;
49315 cptr[i] = cs_flip(n);
49316 W[nv + n]++;
49317 }
49318 else {
49319 var h = W[head + d];
49320 if (h != -1)
49321 last[h] = i;
49322 // put node i in degree list d
49323 W[next + i] = W[head + d];
49324 W[head + d] = i;
49325 }
49326 }
49327 return nel;
49328 };
49329
49330 var _wclear = function(mark, lemax, W, w, n) {
49331 if (mark < 2 || (mark + lemax < 0)) {
49332 for (var k = 0; k < n; k++) {
49333 if (W[w + k] !== 0)
49334 W[w + k] = 1;
49335 }
49336 mark = 2 ;
49337 }
49338 // at this point, W [0..n-1] < mark holds
49339 return mark;
49340 };
49341
49342 var _diag = function (i, j) {
49343 return i != j;
49344 };
49345
49346 return cs_amd;
49347}
49348
49349exports.name = 'cs_amd';
49350exports.path = 'sparse';
49351exports.factory = factory;
49352
49353
49354/***/ }),
49355/* 415 */
49356/***/ (function(module, exports, __webpack_require__) {
49357
49358"use strict";
49359
49360
49361function factory () {
49362
49363 /**
49364 * Keeps entries in the matrix when the callback function returns true, removes the entry otherwise
49365 *
49366 * @param {Matrix} a The sparse matrix
49367 * @param {function} callback The callback function, function will be invoked with the following args:
49368 * - The entry row
49369 * - The entry column
49370 * - The entry value
49371 * - The state parameter
49372 * @param {any} other The state
49373 *
49374 * @return The number of nonzero elements in the matrix
49375 *
49376 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49377 */
49378 var cs_fkeep = function (a, callback, other) {
49379 // a arrays
49380 var avalues = a._values;
49381 var aindex = a._index;
49382 var aptr = a._ptr;
49383 var asize = a._size;
49384 // columns
49385 var n = asize[1];
49386 // nonzero items
49387 var nz = 0;
49388 // loop columns
49389 for (var j = 0; j < n; j++) {
49390 // get current location of col j
49391 var p = aptr[j];
49392 // record new location of col j
49393 aptr[j] = nz;
49394 for (; p < aptr[j+1]; p++) {
49395 // check we need to keep this item
49396 if (callback(aindex[p], j, avalues ? avalues[p] : 1, other)) {
49397 // keep A(i,j)
49398 aindex[nz] = aindex[p];
49399 // check we need to process values (pattern only)
49400 if (avalues)
49401 avalues[nz] = avalues[p];
49402 // increment nonzero items
49403 nz++;
49404 }
49405 }
49406 }
49407 // finalize A
49408 aptr[n] = nz;
49409 // trim arrays
49410 aindex.splice(nz, aindex.length - nz);
49411 // check we need to process values (pattern only)
49412 if (avalues)
49413 avalues.splice(nz, avalues.length - nz);
49414 // return number of nonzero items
49415 return (nz);
49416 };
49417
49418 return cs_fkeep;
49419}
49420
49421exports.name = 'cs_fkeep';
49422exports.path = 'sparse';
49423exports.factory = factory;
49424
49425
49426/***/ }),
49427/* 416 */
49428/***/ (function(module, exports, __webpack_require__) {
49429
49430"use strict";
49431
49432
49433function factory (type) {
49434
49435 var SparseMatrix = type.SparseMatrix;
49436
49437 /**
49438 * Permutes a sparse matrix C = P * A * Q
49439 *
49440 * @param {Matrix} a The Matrix A
49441 * @param {Array} pinv The row permutation vector
49442 * @param {Array} q The column permutation vector
49443 * @param {boolean} values Create a pattern matrix (false), values and pattern otherwise
49444 *
49445 * @return {Matrix} C = P * A * Q, null on error
49446 *
49447 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49448 */
49449 var cs_permute = function (a, pinv, q, values) {
49450 // a arrays
49451 var avalues = a._values;
49452 var aindex = a._index;
49453 var aptr = a._ptr;
49454 var asize = a._size;
49455 var adt = a._datatype;
49456 // rows & columns
49457 var m = asize[0];
49458 var n = asize[1];
49459 // c arrays
49460 var cvalues = values && a._values ? [] : null;
49461 var cindex = []; // (aptr[n]);
49462 var cptr = []; // (n + 1);
49463 // initialize vars
49464 var nz = 0;
49465 // loop columns
49466 for (var k = 0; k < n; k++) {
49467 // column k of C is column q[k] of A
49468 cptr[k] = nz;
49469 // apply column permutation
49470 var j = q ? (q[k]) : k;
49471 // loop values in column j of A
49472 for (var t0 = aptr[j], t1 = aptr[j + 1], t = t0; t < t1; t++) {
49473 // row i of A is row pinv[i] of C
49474 var r = pinv ? pinv[aindex[t]] : aindex[t];
49475 // index
49476 cindex[nz] = r;
49477 // check we need to populate values
49478 if (cvalues)
49479 cvalues[nz] = avalues[t];
49480 // increment number of nonzero elements
49481 nz++;
49482 }
49483 }
49484 // finalize the last column of C
49485 cptr[n] = nz;
49486 // return C matrix
49487 return new SparseMatrix({
49488 values: cvalues,
49489 index: cindex,
49490 ptr: cptr,
49491 size: [m, n],
49492 datatype: adt
49493 });
49494 };
49495
49496 return cs_permute;
49497}
49498
49499exports.name = 'cs_permute';
49500exports.path = 'sparse';
49501exports.factory = factory;
49502
49503
49504/***/ }),
49505/* 417 */
49506/***/ (function(module, exports, __webpack_require__) {
49507
49508"use strict";
49509
49510
49511function factory () {
49512
49513 /**
49514 * Computes the elimination tree of Matrix A (using triu(A)) or the
49515 * elimination tree of A'A without forming A'A.
49516 *
49517 * @param {Matrix} a The A Matrix
49518 * @param {boolean} ata A value of true the function computes the etree of A'A
49519 *
49520 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49521 */
49522 var cs_etree = function (a, ata) {
49523 // check inputs
49524 if (!a)
49525 return null;
49526 // a arrays
49527 var aindex = a._index;
49528 var aptr = a._ptr;
49529 var asize = a._size;
49530 // rows & columns
49531 var m = asize[0];
49532 var n = asize[1];
49533
49534 // allocate result
49535 var parent = []; // (n)
49536
49537 // allocate workspace
49538 var w = []; // (n + (ata ? m : 0))
49539 var ancestor = 0; // first n entries in w
49540 var prev = n; // last m entries (ata = true)
49541
49542 var i, inext;
49543
49544 // check we are calculating A'A
49545 if (ata) {
49546 // initialize workspace
49547 for (i = 0; i < m; i++)
49548 w[prev + i] = -1;
49549 }
49550 // loop columns
49551 for (var k = 0; k < n; k++) {
49552 // node k has no parent yet
49553 parent[k] = -1;
49554 // nor does k have an ancestor
49555 w[ancestor + k] = -1;
49556 // values in column k
49557 for (var p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) {
49558 // row
49559 var r = aindex[p];
49560 // node
49561 i = ata ? (w[prev + r]) : r;
49562 // traverse from i to k
49563 for (; i != -1 && i < k; i = inext) {
49564 // inext = ancestor of i
49565 inext = w[ancestor + i];
49566 // path compression
49567 w[ancestor + i] = k;
49568 // check no anc., parent is k
49569 if (inext == -1)
49570 parent[i] = k;
49571 }
49572 if (ata)
49573 w[prev + r] = k;
49574 }
49575 }
49576 return parent;
49577 };
49578
49579 return cs_etree;
49580}
49581
49582exports.name = 'cs_etree';
49583exports.path = 'sparse';
49584exports.factory = factory;
49585
49586
49587/***/ }),
49588/* 418 */
49589/***/ (function(module, exports, __webpack_require__) {
49590
49591"use strict";
49592
49593
49594function factory (type, config, load) {
49595
49596 var cs_tdfs = load(__webpack_require__(129));
49597
49598 /**
49599 * Post order a tree of forest
49600 *
49601 * @param {Array} parent The tree or forest
49602 * @param {Number} n Number of columns
49603 *
49604 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49605 */
49606 var cs_post = function (parent, n) {
49607 // check inputs
49608 if (!parent)
49609 return null;
49610 // vars
49611 var k = 0;
49612 var j;
49613 // allocate result
49614 var post = []; // (n);
49615 // workspace, head: first n entries, next: next n entries, stack: last n entries
49616 var w = []; // (3 * n);
49617 var head = 0;
49618 var next = n;
49619 var stack = 2 * n;
49620 // initialize workspace
49621 for (j = 0; j < n; j++) {
49622 // empty linked lists
49623 w[head + j] = -1;
49624 }
49625 // traverse nodes in reverse order
49626 for (j = n-1; j >= 0; j--) {
49627 // check j is a root
49628 if (parent[j] == -1)
49629 continue;
49630 // add j to list of its parent
49631 w[next + j] = w[head + parent[j]];
49632 w[head + parent[j]] = j;
49633 }
49634 // loop nodes
49635 for (j = 0; j < n; j++) {
49636 // skip j if it is not a root
49637 if (parent[j] != -1)
49638 continue;
49639 // depth-first search
49640 k = cs_tdfs(j, k, w, head, next, post, stack);
49641 }
49642 return post;
49643 };
49644
49645 return cs_post;
49646}
49647
49648exports.name = 'cs_post';
49649exports.path = 'sparse';
49650exports.factory = factory;
49651
49652
49653/***/ }),
49654/* 419 */
49655/***/ (function(module, exports, __webpack_require__) {
49656
49657"use strict";
49658
49659
49660function factory (type, config, load) {
49661
49662 var transpose = load(__webpack_require__(67));
49663
49664 var cs_leaf = load(__webpack_require__(420));
49665
49666 /**
49667 * Computes the column counts using the upper triangular part of A.
49668 * It transposes A internally, none of the input parameters are modified.
49669 *
49670 * @param {Matrix} a The sparse matrix A
49671 *
49672 * @param {Matrix} ata Count the columns of A'A instead
49673 *
49674 * @return An array of size n of the column counts or null on error
49675 *
49676 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49677 */
49678 var cs_counts = function (a, parent, post, ata) {
49679 // check inputs
49680 if (!a || !parent || !post)
49681 return null;
49682 // a matrix arrays
49683 var asize = a._size;
49684 // rows and columns
49685 var m = asize[0];
49686 var n = asize[1];
49687 // variables
49688 var i, j, k, J, p, p0, p1;
49689
49690 // workspace size
49691 var s = 4 * n + (ata ? (n + m + 1) : 0);
49692 // allocate workspace
49693 var w = []; // (s)
49694 var ancestor = 0; // first n entries
49695 var maxfirst = n; // next n entries
49696 var prevleaf = 2 * n; // next n entries
49697 var first = 3 * n; // next n entries
49698 var head = 4 * n; // next n + 1 entries (used when ata is true)
49699 var next = 5 * n + 1; // last entries in workspace
49700 // clear workspace w[0..s-1]
49701 for (k = 0; k < s; k++)
49702 w[k] = -1;
49703
49704 // allocate result
49705 var colcount = []; // (n);
49706
49707 // AT = A'
49708 var at = transpose(a);
49709 // at arrays
49710 var tindex = at._index;
49711 var tptr = at._ptr;
49712
49713 // find w[first + j]
49714 for (k = 0; k < n; k++) {
49715 j = post[k];
49716 // colcount[j]=1 if j is a leaf
49717 colcount[j] = (w[first + j] == -1) ? 1 : 0;
49718 for (; j != -1 && w[first + j] == -1; j = parent[j])
49719 w[first + j] = k;
49720 }
49721
49722 // initialize ata if needed
49723 if (ata) {
49724 // invert post
49725 for (k = 0; k < n; k++)
49726 w[post[k]] = k;
49727 // loop rows (columns in AT)
49728 for (i = 0; i < m; i++) {
49729 // values in column i of AT
49730 for (k = n, p0 = tptr[i], p1 = tptr[i + 1], p = p0; p < p1; p++)
49731 k = Math.min(k, w[tindex[p]]);
49732 // place row i in linked list k
49733 w[next + i] = w[head + k];
49734 w[head + k] = i;
49735 }
49736 }
49737
49738 // each node in its own set
49739 for (i = 0; i < n; i++)
49740 w[ancestor + i] = i;
49741
49742 for (k = 0; k < n; k++) {
49743 // j is the kth node in postordered etree
49744 j = post[k];
49745 // check j is not a root
49746 if (parent[j] != -1)
49747 colcount[parent[j]]--;
49748
49749 // J=j for LL'=A case
49750 for (J = (ata ? w[head + k] : j); J != -1; J = (ata ? w[next + J] : -1)) {
49751 for (p = tptr[J]; p < tptr[J+1]; p++) {
49752 i = tindex[p];
49753 var r = cs_leaf(i, j, w, first, maxfirst, prevleaf, ancestor);
49754 // check A(i,j) is in skeleton
49755 if (r.jleaf >= 1)
49756 colcount[j]++;
49757 // check account for overlap in q
49758 if (r.jleaf == 2)
49759 colcount[r.q]--;
49760 }
49761 }
49762 if (parent[j] != -1)
49763 w[ancestor + j] = parent[j];
49764 }
49765 // sum up colcount's of each child
49766 for (j = 0; j < n; j++) {
49767 if (parent[j] != -1)
49768 colcount[parent[j]] += colcount[j];
49769 }
49770 return colcount;
49771 };
49772
49773 return cs_counts;
49774}
49775
49776exports.name = 'cs_counts';
49777exports.path = 'sparse';
49778exports.factory = factory;
49779
49780
49781/***/ }),
49782/* 420 */
49783/***/ (function(module, exports, __webpack_require__) {
49784
49785"use strict";
49786
49787
49788function factory () {
49789
49790 /**
49791 * This function determines if j is a leaf of the ith row subtree.
49792 * Consider A(i,j), node j in ith row subtree and return lca(jprev,j)
49793 *
49794 * @param {Number} i The ith row subtree
49795 * @param {Number} j The node to test
49796 * @param {Array} w The workspace array
49797 * @param {Number} first The index offset within the workspace for the first array
49798 * @param {Number} maxfirst The index offset within the workspace for the maxfirst array
49799 * @param {Number} prevleaf The index offset within the workspace for the prevleaf array
49800 * @param {Number} ancestor The index offset within the workspace for the ancestor array
49801 *
49802 * @return {Object}
49803 *
49804 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49805 */
49806 var cs_leaf = function (i, j, w, first, maxfirst, prevleaf, ancestor) {
49807
49808 var s, sparent, jprev;
49809
49810 // our result
49811 var jleaf = 0;
49812 var q;
49813
49814 // check j is a leaf
49815 if (i <= j || w[first + j] <= w[maxfirst + i])
49816 return (-1);
49817 // update max first[j] seen so far
49818 w[maxfirst + i] = w[first + j];
49819 // jprev = previous leaf of ith subtree
49820 jprev = w[prevleaf + i];
49821 w[prevleaf + i] = j;
49822
49823 // check j is first or subsequent leaf
49824 if (jprev === -1) {
49825 // 1st leaf, q = root of ith subtree
49826 jleaf = 1;
49827 q = i;
49828 }
49829 else {
49830 // update jleaf
49831 jleaf = 2;
49832 // q = least common ancester (jprev,j)
49833 for (q = jprev; q != w[ancestor + q]; q = w[ancestor + q]);
49834 for (s = jprev; s != q; s = sparent) {
49835 // path compression
49836 sparent = w[ancestor + s];
49837 w[ancestor + s] = q;
49838 }
49839 }
49840 return {
49841 jleaf: jleaf,
49842 q: q
49843 };
49844 };
49845
49846 return cs_leaf;
49847}
49848
49849exports.name = 'cs_leaf';
49850exports.path = 'sparse';
49851exports.factory = factory;
49852
49853
49854/***/ }),
49855/* 421 */
49856/***/ (function(module, exports, __webpack_require__) {
49857
49858"use strict";
49859
49860
49861function factory (type, config, load) {
49862
49863 var abs = load(__webpack_require__(28));
49864 var divideScalar = load(__webpack_require__(14));
49865 var multiply = load(__webpack_require__(12));
49866
49867 var larger = load(__webpack_require__(34));
49868 var largerEq = load(__webpack_require__(130));
49869
49870 var cs_spsolve = load(__webpack_require__(422));
49871
49872 var SparseMatrix = type.SparseMatrix;
49873
49874 /**
49875 * Computes the numeric LU factorization of the sparse matrix A. Implements a Left-looking LU factorization
49876 * algorithm that computes L and U one column at a tume. At the kth step, it access columns 1 to k-1 of L
49877 * and column k of A. Given the fill-reducing column ordering q (see parameter s) computes L, U and pinv so
49878 * L * U = A(p, q), where p is the inverse of pinv.
49879 *
49880 * @param {Matrix} m The A Matrix to factorize
49881 * @param {Object} s The symbolic analysis from cs_sqr(). Provides the fill-reducing
49882 * column ordering q
49883 * @param {Number} tol Partial pivoting threshold (1 for partial pivoting)
49884 *
49885 * @return {Number} The numeric LU factorization of A or null
49886 *
49887 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49888 */
49889 var cs_lu = function (m, s, tol) {
49890 // validate input
49891 if (!m)
49892 return null;
49893 // m arrays
49894 var size = m._size;
49895 // columns
49896 var n = size[1];
49897 // symbolic analysis result
49898 var q;
49899 var lnz = 100;
49900 var unz = 100;
49901 // update symbolic analysis parameters
49902 if (s) {
49903 q = s.q;
49904 lnz = s.lnz || lnz;
49905 unz = s.unz || unz;
49906 }
49907 // L arrays
49908 var lvalues = []; // (lnz)
49909 var lindex = []; // (lnz);
49910 var lptr = []; // (n + 1);
49911 // L
49912 var L = new SparseMatrix({
49913 values: lvalues,
49914 index: lindex,
49915 ptr: lptr,
49916 size: [n, n]
49917 });
49918 // U arrays
49919 var uvalues = []; // (unz);
49920 var uindex = []; // (unz);
49921 var uptr = []; // (n + 1);
49922 // U
49923 var U = new SparseMatrix({
49924 values: uvalues,
49925 index: uindex,
49926 ptr: uptr,
49927 size: [n, n]
49928 });
49929 // inverse of permutation vector
49930 var pinv = []; // (n);
49931 // vars
49932 var i, p;
49933 // allocate arrays
49934 var x = []; // (n);
49935 var xi = []; // (2 * n);
49936 // initialize variables
49937 for (i = 0; i < n; i++) {
49938 // clear workspace
49939 x[i] = 0;
49940 // no rows pivotal yet
49941 pinv[i] = -1;
49942 // no cols of L yet
49943 lptr[i + 1] = 0;
49944 }
49945 // reset number of nonzero elements in L and U
49946 lnz = 0;
49947 unz = 0;
49948 // compute L(:,k) and U(:,k)
49949 for (var k = 0; k < n; k++) {
49950 // update ptr
49951 lptr[k] = lnz;
49952 uptr[k] = unz;
49953 // apply column permutations if needed
49954 var col = q ? q[k] : k;
49955 // solve triangular system, x = L\A(:,col)
49956 var top = cs_spsolve(L, m, col, xi, x, pinv, 1);
49957 // find pivot
49958 var ipiv = -1;
49959 var a = -1;
49960 // loop xi[] from top -> n
49961 for (p = top; p < n; p++) {
49962 // x[i] is nonzero
49963 i = xi[p];
49964 // check row i is not yet pivotal
49965 if (pinv[i] < 0) {
49966 // absolute value of x[i]
49967 var xabs = abs(x[i]);
49968 // check absoulte value is greater than pivot value
49969 if (larger(xabs, a)) {
49970 // largest pivot candidate so far
49971 a = xabs;
49972 ipiv = i;
49973 }
49974 }
49975 else {
49976 // x(i) is the entry U(pinv[i],k)
49977 uindex[unz] = pinv[i];
49978 uvalues[unz++] = x[i];
49979 }
49980 }
49981 // validate we found a valid pivot
49982 if (ipiv == -1 || a <= 0)
49983 return null;
49984 // update actual pivot column, give preference to diagonal value
49985 if (pinv[col] < 0 && largerEq(abs(x[col]), multiply(a, tol)))
49986 ipiv = col;
49987 // the chosen pivot
49988 var pivot = x[ipiv];
49989 // last entry in U(:,k) is U(k,k)
49990 uindex[unz] = k;
49991 uvalues[unz++] = pivot;
49992 // ipiv is the kth pivot row
49993 pinv[ipiv] = k;
49994 // first entry in L(:,k) is L(k,k) = 1
49995 lindex[lnz] = ipiv;
49996 lvalues[lnz++] = 1;
49997 // L(k+1:n,k) = x / pivot
49998 for (p = top; p < n; p++) {
49999 // row
50000 i = xi[p];
50001 // check x(i) is an entry in L(:,k)
50002 if (pinv[i] < 0) {
50003 // save unpermuted row in L
50004 lindex[lnz] = i;
50005 // scale pivot column
50006 lvalues[lnz++] = divideScalar(x[i], pivot);
50007 }
50008 // x[0..n-1] = 0 for next k
50009 x[i] = 0;
50010 }
50011 }
50012 // update ptr
50013 lptr[n] = lnz;
50014 uptr[n] = unz;
50015 // fix row indices of L for final pinv
50016 for (p = 0; p < lnz; p++)
50017 lindex[p] = pinv[lindex[p]];
50018 // trim arrays
50019 lvalues.splice(lnz, lvalues.length - lnz);
50020 lindex.splice(lnz, lindex.length - lnz);
50021 uvalues.splice(unz, uvalues.length - unz);
50022 uindex.splice(unz, uindex.length - unz);
50023 // return LU factor
50024 return {
50025 L: L,
50026 U: U,
50027 pinv: pinv
50028 };
50029 };
50030
50031 return cs_lu;
50032}
50033
50034exports.name = 'cs_lu';
50035exports.path = 'sparse';
50036exports.factory = factory;
50037
50038
50039/***/ }),
50040/* 422 */
50041/***/ (function(module, exports, __webpack_require__) {
50042
50043"use strict";
50044
50045
50046function factory (type, config, load) {
50047
50048 var divideScalar = load(__webpack_require__(14));
50049 var multiply = load(__webpack_require__(12));
50050 var subtract = load(__webpack_require__(21));
50051
50052 var cs_reach = load(__webpack_require__(423));
50053
50054 /**
50055 * The function cs_spsolve() computes the solution to G * x = bk, where bk is the
50056 * kth column of B. When lo is true, the function assumes G = L is lower triangular with the
50057 * diagonal entry as the first entry in each column. When lo is true, the function assumes G = U
50058 * is upper triangular with the diagonal entry as the last entry in each column.
50059 *
50060 * @param {Matrix} g The G matrix
50061 * @param {Matrix} b The B matrix
50062 * @param {Number} k The kth column in B
50063 * @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n
50064 * The first n entries is the nonzero pattern, the last n entries is the stack
50065 * @param {Array} x The soluton to the linear system G * x = b
50066 * @param {Array} pinv The inverse row permutation vector, must be null for L * x = b
50067 * @param {boolean} lo The lower (true) upper triangular (false) flag
50068 *
50069 * @return {Number} The index for the nonzero pattern
50070 *
50071 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
50072 */
50073 var cs_spsolve = function (g, b, k, xi, x, pinv, lo) {
50074 // g arrays
50075 var gvalues = g._values;
50076 var gindex = g._index;
50077 var gptr = g._ptr;
50078 var gsize = g._size;
50079 // columns
50080 var n = gsize[1];
50081 // b arrays
50082 var bvalues = b._values;
50083 var bindex = b._index;
50084 var bptr = b._ptr;
50085 // vars
50086 var p, p0, p1, q;
50087 // xi[top..n-1] = cs_reach(B(:,k))
50088 var top = cs_reach(g, b, k, xi, pinv);
50089 // clear x
50090 for (p = top; p < n; p++)
50091 x[xi[p]] = 0;
50092 // scatter b
50093 for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++)
50094 x[bindex[p]] = bvalues[p];
50095 // loop columns
50096 for (var px = top; px < n; px++) {
50097 // x array index for px
50098 var j = xi[px];
50099 // apply permutation vector (U x = b), j maps to column J of G
50100 var J = pinv ? pinv[j] : j;
50101 // check column J is empty
50102 if (J < 0)
50103 continue;
50104 // column value indeces in G, p0 <= p < p1
50105 p0 = gptr[J];
50106 p1 = gptr[J + 1];
50107 // x(j) /= G(j,j)
50108 x[j] = divideScalar(x[j], gvalues[lo ? p0 : (p1 - 1)]);
50109 // first entry L(j,j)
50110 p = lo ? (p0 + 1) : p0;
50111 q = lo ? (p1) : (p1 - 1);
50112 // loop
50113 for ( ; p < q ; p++) {
50114 // row
50115 var i = gindex[p];
50116 // x(i) -= G(i,j) * x(j)
50117 x[i] = subtract(x[i], multiply(gvalues[p], x[j]));
50118 }
50119 }
50120 // return top of stack
50121 return top;
50122 };
50123
50124 return cs_spsolve;
50125}
50126
50127exports.name = 'cs_spsolve';
50128exports.path = 'sparse';
50129exports.factory = factory;
50130
50131
50132/***/ }),
50133/* 423 */
50134/***/ (function(module, exports, __webpack_require__) {
50135
50136"use strict";
50137
50138
50139function factory (type, config, load) {
50140
50141 var cs_dfs = load(__webpack_require__(424));
50142 var cs_marked = load(__webpack_require__(131));
50143 var cs_mark = load(__webpack_require__(132));
50144
50145 /**
50146 * The cs_reach function computes X = Reach(B), where B is the nonzero pattern of the n-by-1
50147 * sparse column of vector b. The function returns the set of nodes reachable from any node in B. The
50148 * nonzero pattern xi of the solution x to the sparse linear system Lx=b is given by X=Reach(B).
50149 *
50150 * @param {Matrix} g The G matrix
50151 * @param {Matrix} b The B matrix
50152 * @param {Number} k The kth column in B
50153 * @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n
50154 * The first n entries is the nonzero pattern, the last n entries is the stack
50155 * @param {Array} pinv The inverse row permutation vector
50156 *
50157 * @return {Number} The index for the nonzero pattern
50158 *
50159 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
50160 */
50161 var cs_reach = function (g, b, k, xi, pinv) {
50162 // g arrays
50163 var gptr = g._ptr;
50164 var gsize = g._size;
50165 // b arrays
50166 var bindex = b._index;
50167 var bptr = b._ptr;
50168 // columns
50169 var n = gsize[1];
50170 // vars
50171 var p, p0, p1;
50172 // initialize top
50173 var top = n;
50174 // loop column indeces in B
50175 for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) {
50176 // node i
50177 var i = bindex[p];
50178 // check node i is marked
50179 if (!cs_marked(gptr, i)) {
50180 // start a dfs at unmarked node i
50181 top = cs_dfs(i, g, top, xi, pinv);
50182 }
50183 }
50184 // loop columns from top -> n - 1
50185 for (p = top; p < n; p++) {
50186 // restore G
50187 cs_mark(gptr, xi[p]);
50188 }
50189 return top;
50190 };
50191
50192 return cs_reach;
50193}
50194
50195exports.name = 'cs_reach';
50196exports.path = 'sparse';
50197exports.factory = factory;
50198
50199
50200/***/ }),
50201/* 424 */
50202/***/ (function(module, exports, __webpack_require__) {
50203
50204"use strict";
50205
50206
50207function factory (type, config, load) {
50208
50209 var cs_marked = load(__webpack_require__(131));
50210 var cs_mark = load(__webpack_require__(132));
50211 var cs_unflip = load(__webpack_require__(425));
50212
50213 /**
50214 * Depth-first search computes the nonzero pattern xi of the directed graph G (Matrix) starting
50215 * at nodes in B (see cs_reach()).
50216 *
50217 * @param {Number} j The starting node for the DFS algorithm
50218 * @param {Matrix} g The G matrix to search, ptr array modified, then restored
50219 * @param {Number} top Start index in stack xi[top..n-1]
50220 * @param {Number} k The kth column in B
50221 * @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n
50222 * The first n entries is the nonzero pattern, the last n entries is the stack
50223 * @param {Array} pinv The inverse row permutation vector, must be null for L * x = b
50224 *
50225 * @return {Number} New value of top
50226 *
50227 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
50228 */
50229 var cs_dfs = function (j, g, top, xi, pinv) {
50230 // g arrays
50231 var index = g._index;
50232 var ptr = g._ptr;
50233 var size = g._size;
50234 // columns
50235 var n = size[1];
50236 // vars
50237 var i, p, p2;
50238 // initialize head
50239 var head = 0;
50240 // initialize the recursion stack
50241 xi[0] = j;
50242 // loop
50243 while (head >= 0) {
50244 // get j from the top of the recursion stack
50245 j = xi[head];
50246 // apply permutation vector
50247 var jnew = pinv ? pinv[j] : j;
50248 // check node j is marked
50249 if (!cs_marked(ptr, j)) {
50250 // mark node j as visited
50251 cs_mark(ptr, j);
50252 // update stack (last n entries in xi)
50253 xi[n + head] = jnew < 0 ? 0 : cs_unflip(ptr[jnew]);
50254 }
50255 // node j done if no unvisited neighbors
50256 var done = 1;
50257 // examine all neighbors of j, stack (last n entries in xi)
50258 for (p = xi[n + head], p2 = jnew < 0 ? 0 : cs_unflip(ptr[jnew+1]); p < p2; p++) {
50259 // consider neighbor node i
50260 i = index[p];
50261 // check we have visited node i, skip it
50262 if (cs_marked(ptr, i))
50263 continue;
50264 // pause depth-first search of node j, update stack (last n entries in xi)
50265 xi[n + head] = p;
50266 // start dfs at node i
50267 xi[++head] = i;
50268 // node j is not done
50269 done = 0;
50270 // break, to start dfs(i)
50271 break;
50272 }
50273 // check depth-first search at node j is done
50274 if (done) {
50275 // remove j from the recursion stack
50276 head--;
50277 // and place in the output stack
50278 xi[--top] = j;
50279 }
50280 }
50281 return top;
50282 };
50283
50284 return cs_dfs;
50285}
50286
50287exports.name = 'cs_dfs';
50288exports.path = 'sparse';
50289exports.factory = factory;
50290
50291
50292/***/ }),
50293/* 425 */
50294/***/ (function(module, exports, __webpack_require__) {
50295
50296"use strict";
50297
50298
50299function factory (type, config, load) {
50300
50301 var cs_flip = load(__webpack_require__(84));
50302
50303 /**
50304 * Flips the value if it is negative of returns the same value otherwise.
50305 *
50306 * @param {Number} i The value to flip
50307 *
50308 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
50309 */
50310 var cs_unflip = function (i) {
50311 // flip the value if it is negative
50312 return i < 0 ? cs_flip(i) : i;
50313 };
50314
50315 return cs_unflip;
50316}
50317
50318exports.name = 'cs_unflip';
50319exports.path = 'sparse';
50320exports.factory = factory;
50321
50322
50323/***/ }),
50324/* 426 */
50325/***/ (function(module, exports, __webpack_require__) {
50326
50327"use strict";
50328
50329
50330var isArray = Array.isArray;
50331
50332function factory (type, config, load, typed) {
50333
50334 var matrix = load(__webpack_require__(0));
50335 var lup = load(__webpack_require__(127));
50336 var slu = load(__webpack_require__(128));
50337 var cs_ipvec = load(__webpack_require__(427));
50338
50339 var solveValidation = load(__webpack_require__(85));
50340
50341 var usolve = load(__webpack_require__(134));
50342 var lsolve = load(__webpack_require__(133));
50343
50344 /**
50345 * Solves the linear system `A * x = b` where `A` is an [n x n] matrix and `b` is a [n] column vector.
50346 *
50347 * Syntax:
50348 *
50349 * math.lusolve(A, b) // returns column vector with the solution to the linear system A * x = b
50350 * math.lusolve(lup, b) // returns column vector with the solution to the linear system A * x = b, lup = math.lup(A)
50351 *
50352 * Examples:
50353 *
50354 * var m = [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]];
50355 *
50356 * var x = math.lusolve(m, [-1, -1, -1, -1]); // x = [[-1], [-0.5], [-1/3], [-0.25]]
50357 *
50358 * var f = math.lup(m);
50359 * var x1 = math.lusolve(f, [-1, -1, -1, -1]); // x1 = [[-1], [-0.5], [-1/3], [-0.25]]
50360 * var x2 = math.lusolve(f, [1, 2, 1, -1]); // x2 = [[1], [1], [1/3], [-0.25]]
50361 *
50362 * var a = [[-2, 3], [2, 1]];
50363 * var b = [11, 9];
50364 * var x = math.lusolve(a, b); // [[2], [5]]
50365 *
50366 * See also:
50367 *
50368 * lup, slu, lsolve, usolve
50369 *
50370 * @param {Matrix | Array | Object} A Invertible Matrix or the Matrix LU decomposition
50371 * @param {Matrix | Array} b Column Vector
50372 * @param {number} [order] The Symbolic Ordering and Analysis order, see slu for details. Matrix must be a SparseMatrix
50373 * @param {Number} [threshold] Partial pivoting threshold (1 for partial pivoting), see slu for details. Matrix must be a SparseMatrix.
50374 *
50375 * @return {DenseMatrix | Array} Column vector with the solution to the linear system A * x = b
50376 */
50377 var lusolve = typed('lusolve', {
50378
50379 'Array, Array | Matrix': function (a, b) {
50380 // convert a to matrix
50381 a = matrix(a);
50382 // matrix lup decomposition
50383 var d = lup(a);
50384 // solve
50385 var x = _lusolve(d.L, d.U, d.p, null, b);
50386 // convert result to array
50387 return x.valueOf();
50388 },
50389
50390 'DenseMatrix, Array | Matrix': function (a, b) {
50391 // matrix lup decomposition
50392 var d = lup(a);
50393 // solve
50394 return _lusolve(d.L, d.U, d.p, null, b);
50395 },
50396
50397 'SparseMatrix, Array | Matrix': function (a, b) {
50398 // matrix lup decomposition
50399 var d = lup(a);
50400 // solve
50401 return _lusolve(d.L, d.U, d.p, null, b);
50402 },
50403
50404 'SparseMatrix, Array | Matrix, number, number': function (a, b, order, threshold) {
50405 // matrix lu decomposition
50406 var d = slu(a, order, threshold);
50407 // solve
50408 return _lusolve(d.L, d.U, d.p, d.q, b);
50409 },
50410
50411 'Object, Array | Matrix': function (d, b) {
50412 // solve
50413 return _lusolve(d.L, d.U, d.p, d.q, b);
50414 }
50415 });
50416
50417 var _toMatrix = function (a) {
50418 // check it is a matrix
50419 if (type.isMatrix(a))
50420 return a;
50421 // check array
50422 if (isArray(a))
50423 return matrix(a);
50424 // throw
50425 throw new TypeError('Invalid Matrix LU decomposition');
50426 };
50427
50428 var _lusolve = function (l, u, p, q, b) {
50429 // verify L, U, P
50430 l = _toMatrix(l);
50431 u = _toMatrix(u);
50432 // validate matrix and vector
50433 b = solveValidation(l, b, false);
50434 // apply row permutations if needed (b is a DenseMatrix)
50435 if (p)
50436 b._data = cs_ipvec(p, b._data);
50437 // use forward substitution to resolve L * y = b
50438 var y = lsolve(l, b);
50439 // use backward substitution to resolve U * x = y
50440 var x = usolve(u, y);
50441 // apply column permutations if needed (x is a DenseMatrix)
50442 if (q)
50443 x._data = cs_ipvec(q, x._data);
50444 // return solution
50445 return x;
50446 };
50447
50448 return lusolve;
50449}
50450
50451exports.name = 'lusolve';
50452exports.factory = factory;
50453
50454
50455/***/ }),
50456/* 427 */
50457/***/ (function(module, exports, __webpack_require__) {
50458
50459"use strict";
50460
50461
50462function factory () {
50463
50464 /**
50465 * Permutes a vector; x = P'b. In MATLAB notation, x(p)=b.
50466 *
50467 * @param {Array} p The permutation vector of length n. null value denotes identity
50468 * @param {Array} b The input vector
50469 *
50470 * @return {Array} The output vector x = P'b
50471 */
50472 var cs_ipvec = function (p, b, n) {
50473 // vars
50474 var k;
50475 var n = b.length;
50476 var x = [];
50477 // check permutation vector was provided, p = null denotes identity
50478 if (p) {
50479 // loop vector
50480 for (k = 0; k < n; k++) {
50481 // apply permutation
50482 x[p[k]] = b[k];
50483 }
50484 }
50485 else {
50486 // loop vector
50487 for (k = 0; k < n; k++) {
50488 // x[i] = b[i]
50489 x[k] = b[k];
50490 }
50491 }
50492 return x;
50493 };
50494
50495 return cs_ipvec;
50496}
50497
50498exports.name = 'cs_ipvec';
50499exports.path = 'sparse';
50500exports.factory = factory;
50501
50502
50503/***/ }),
50504/* 428 */
50505/***/ (function(module, exports, __webpack_require__) {
50506
50507module.exports = [
50508 __webpack_require__(28),
50509 __webpack_require__(20),
50510 __webpack_require__(16),
50511 __webpack_require__(429),
50512 __webpack_require__(430),
50513 __webpack_require__(431),
50514 __webpack_require__(49),
50515 __webpack_require__(135),
50516 __webpack_require__(432),
50517 __webpack_require__(433),
50518 __webpack_require__(434),
50519 __webpack_require__(97),
50520 __webpack_require__(435),
50521 __webpack_require__(436),
50522 __webpack_require__(437),
50523 __webpack_require__(438),
50524 __webpack_require__(137),
50525 __webpack_require__(440),
50526 __webpack_require__(441),
50527 __webpack_require__(12),
50528 __webpack_require__(442),
50529 __webpack_require__(443),
50530 __webpack_require__(46),
50531 __webpack_require__(98),
50532 __webpack_require__(125),
50533 __webpack_require__(50),
50534 __webpack_require__(444),
50535 __webpack_require__(21),
50536 __webpack_require__(35),
50537 __webpack_require__(445),
50538 __webpack_require__(446)
50539];
50540
50541
50542/***/ }),
50543/* 429 */
50544/***/ (function(module, exports, __webpack_require__) {
50545
50546"use strict";
50547
50548
50549var deepMap = __webpack_require__(1);
50550
50551function factory (type, config, load, typed) {
50552 var unaryMinus = load(__webpack_require__(35));
50553 var isNegative = load(__webpack_require__(58));
50554 var matrix = load(__webpack_require__(0));
50555
50556 /**
50557 * Calculate the cubic root of a value.
50558 *
50559 * For matrices, the function is evaluated element wise.
50560 *
50561 * Syntax:
50562 *
50563 * math.cbrt(x)
50564 * math.cbrt(x, allRoots)
50565 *
50566 * Examples:
50567 *
50568 * math.cbrt(27); // returns 3
50569 * math.cube(3); // returns 27
50570 * math.cbrt(-64); // returns -4
50571 * math.cbrt(math.unit('27 m^3')); // returns Unit 3 m
50572 * math.cbrt([27, 64, 125]); // returns [3, 4, 5]
50573 *
50574 * var x = math.complex('8i');
50575 * math.cbrt(x); // returns Complex 1.7320508075689 + i
50576 * math.cbrt(x, true); // returns Matrix [
50577 * // 1.7320508075689 + i
50578 * // -1.7320508075689 + i
50579 * // -2i
50580 * // ]
50581 *
50582 * See also:
50583 *
50584 * square, sqrt, cube
50585 *
50586 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x
50587 * Value for which to calculate the cubic root.
50588 * @param {boolean} [allRoots] Optional, false by default. Only applicable
50589 * when `x` is a number or complex number. If true, all complex
50590 * roots are returned, if false (default) the principal root is
50591 * returned.
50592 * @return {number | BigNumber | Complex | Unit | Array | Matrix}
50593 * Returns the cubic root of `x`
50594 */
50595 var cbrt = typed('cbrt', {
50596 'number': _cbrtNumber,
50597 // note: signature 'number, boolean' is also supported,
50598 // created by typed as it knows how to convert number to Complex
50599
50600 'Complex': _cbrtComplex,
50601
50602 'Complex, boolean': _cbrtComplex,
50603
50604 'BigNumber': function (x) {
50605 return x.cbrt();
50606 },
50607
50608 'Unit': _cbrtUnit,
50609
50610 'Array | Matrix': function (x) {
50611 // deep map collection, skip zeros since cbrt(0) = 0
50612 return deepMap(x, cbrt, true);
50613 }
50614 });
50615
50616 /**
50617 * Calculate the cubic root for a complex number
50618 * @param {Complex} x
50619 * @param {boolean} [allRoots] If true, the function will return an array
50620 * with all three roots. If false or undefined,
50621 * the principal root is returned.
50622 * @returns {Complex | Array.<Complex> | Matrix.<Complex>} Returns the cubic root(s) of x
50623 * @private
50624 */
50625 function _cbrtComplex(x, allRoots) {
50626 // https://www.wikiwand.com/en/Cube_root#/Complex_numbers
50627
50628 var arg_3 = x.arg() / 3;
50629 var abs = x.abs();
50630
50631 // principal root:
50632 var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
50633 new type.Complex(0, arg_3).exp());
50634
50635 if (allRoots) {
50636 var all = [
50637 principal,
50638 new type.Complex(_cbrtNumber(abs), 0).mul(
50639 new type.Complex(0, arg_3 + Math.PI * 2 / 3).exp()),
50640 new type.Complex(_cbrtNumber(abs), 0).mul(
50641 new type.Complex(0, arg_3 - Math.PI * 2 / 3).exp())
50642 ];
50643
50644 return (config.matrix === 'Array') ? all : matrix(all);
50645 }
50646 else {
50647 return principal;
50648 }
50649 }
50650
50651 /**
50652 * Calculate the cubic root for a Unit
50653 * @param {Unit} x
50654 * @return {Unit} Returns the cubic root of x
50655 * @private
50656 */
50657 function _cbrtUnit(x) {
50658 if(x.value && type.isComplex(x.value)) {
50659 var result = x.clone();
50660 result.value = 1.0;
50661 result = result.pow(1.0/3); // Compute the units
50662 result.value = _cbrtComplex(x.value); // Compute the value
50663 return result;
50664 }
50665 else {
50666 var negate = isNegative(x.value);
50667 if (negate) {
50668 x.value = unaryMinus(x.value);
50669 }
50670
50671 // TODO: create a helper function for this
50672 var third;
50673 if (type.isBigNumber(x.value)) {
50674 third = new type.BigNumber(1).div(3);
50675 }
50676 else if (type.isFraction(x.value)) {
50677 third = new type.Fraction(1, 3);
50678 }
50679 else {
50680 third = 1/3;
50681 }
50682
50683 var result = x.pow(third);
50684
50685 if (negate) {
50686 result.value = unaryMinus(result.value);
50687 }
50688
50689 return result;
50690 }
50691 }
50692
50693 cbrt.toTex = {1: '\\sqrt[3]{${args[0]}}'};
50694
50695 return cbrt;
50696}
50697
50698/**
50699 * Calculate cbrt for a number
50700 *
50701 * Code from es6-shim.js:
50702 * https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1564-L1577
50703 *
50704 * @param {number} x
50705 * @returns {number | Complex} Returns the cubic root of x
50706 * @private
50707 */
50708var _cbrtNumber = Math.cbrt || function (x) {
50709 if (x === 0) {
50710 return x;
50711 }
50712
50713 var negate = x < 0;
50714 var result;
50715 if (negate) {
50716 x = -x;
50717 }
50718
50719 if (isFinite(x)) {
50720 result = Math.exp(Math.log(x) / 3);
50721 // from http://en.wikipedia.org/wiki/Cube_root#Numerical_methods
50722 result = (x / (result * result) + (2 * result)) / 3;
50723 } else {
50724 result = x;
50725 }
50726
50727 return negate ? -result : result;
50728};
50729
50730exports.name = 'cbrt';
50731exports.factory = factory;
50732
50733
50734/***/ }),
50735/* 430 */
50736/***/ (function(module, exports, __webpack_require__) {
50737
50738"use strict";
50739
50740
50741var deepMap = __webpack_require__(1);
50742
50743function factory (type, config, load, typed) {
50744 /**
50745 * Round a value towards plus infinity
50746 * If `x` is complex, both real and imaginary part are rounded towards plus infinity.
50747 * For matrices, the function is evaluated element wise.
50748 *
50749 * Syntax:
50750 *
50751 * math.ceil(x)
50752 *
50753 * Examples:
50754 *
50755 * math.ceil(3.2); // returns number 4
50756 * math.ceil(3.8); // returns number 4
50757 * math.ceil(-4.2); // returns number -4
50758 * math.ceil(-4.7); // returns number -4
50759 *
50760 * var c = math.complex(3.2, -2.7);
50761 * math.ceil(c); // returns Complex 4 - 2i
50762 *
50763 * math.ceil([3.2, 3.8, -4.7]); // returns Array [4, 4, -4]
50764 *
50765 * See also:
50766 *
50767 * floor, fix, round
50768 *
50769 * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
50770 * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
50771 */
50772 var ceil = typed('ceil', {
50773 'number': Math.ceil,
50774
50775 'Complex': function (x) {
50776 return x.ceil();
50777 },
50778
50779 'BigNumber': function (x) {
50780 return x.ceil();
50781 },
50782
50783 'Fraction': function (x) {
50784 return x.ceil();
50785 },
50786
50787 'Array | Matrix': function (x) {
50788 // deep map collection, skip zeros since ceil(0) = 0
50789 return deepMap(x, ceil, true);
50790 }
50791 });
50792
50793 ceil.toTex = {1: '\\left\\lceil${args[0]}\\right\\rceil'};
50794
50795 return ceil;
50796}
50797
50798exports.name = 'ceil';
50799exports.factory = factory;
50800
50801
50802/***/ }),
50803/* 431 */
50804/***/ (function(module, exports, __webpack_require__) {
50805
50806"use strict";
50807
50808
50809var deepMap = __webpack_require__(1);
50810
50811function factory (type, config, load, typed) {
50812
50813 /**
50814 * Compute the cube of a value, `x * x * x`.
50815 * For matrices, the function is evaluated element wise.
50816 *
50817 * Syntax:
50818 *
50819 * math.cube(x)
50820 *
50821 * Examples:
50822 *
50823 * math.cube(2); // returns number 8
50824 * math.pow(2, 3); // returns number 8
50825 * math.cube(4); // returns number 64
50826 * 4 * 4 * 4; // returns number 64
50827 *
50828 * math.cube([1, 2, 3, 4]); // returns Array [1, 8, 27, 64]
50829 *
50830 * See also:
50831 *
50832 * multiply, square, pow, cbrt
50833 *
50834 * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x Number for which to calculate the cube
50835 * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} Cube of x
50836 */
50837 var cube = typed('cube', {
50838 'number': function (x) {
50839 return x * x * x;
50840 },
50841
50842 'Complex': function (x) {
50843 return x.mul(x).mul(x); // Is faster than pow(x, 3)
50844 },
50845
50846 'BigNumber': function (x) {
50847 return x.times(x).times(x);
50848 },
50849
50850 'Fraction': function (x) {
50851 return x.pow(3); // Is faster than mul()mul()mul()
50852 },
50853
50854 'Array | Matrix': function (x) {
50855 // deep map collection, skip zeros since cube(0) = 0
50856 return deepMap(x, cube, true);
50857 },
50858
50859 'Unit': function(x) {
50860 return x.pow(3);
50861 }
50862 });
50863
50864 cube.toTex = {1: '\\left(${args[0]}\\right)^3'};
50865
50866 return cube;
50867}
50868
50869exports.name = 'cube';
50870exports.factory = factory;
50871
50872
50873/***/ }),
50874/* 432 */
50875/***/ (function(module, exports, __webpack_require__) {
50876
50877"use strict";
50878
50879
50880function factory (type, config, load, typed) {
50881
50882 var matrix = load(__webpack_require__(0));
50883 var multiplyScalar = load(__webpack_require__(22));
50884 var latex = __webpack_require__(4);
50885
50886 var algorithm02 = load(__webpack_require__(24));
50887 var algorithm09 = load(__webpack_require__(136));
50888 var algorithm11 = load(__webpack_require__(19));
50889 var algorithm13 = load(__webpack_require__(8));
50890 var algorithm14 = load(__webpack_require__(6));
50891
50892 /**
50893 * Multiply two matrices element wise. The function accepts both matrices and
50894 * scalar values.
50895 *
50896 * Syntax:
50897 *
50898 * math.dotMultiply(x, y)
50899 *
50900 * Examples:
50901 *
50902 * math.dotMultiply(2, 4); // returns 8
50903 *
50904 * a = [[9, 5], [6, 1]];
50905 * b = [[3, 2], [5, 2]];
50906 *
50907 * math.dotMultiply(a, b); // returns [[27, 10], [30, 2]]
50908 * math.multiply(a, b); // returns [[52, 28], [23, 14]]
50909 *
50910 * See also:
50911 *
50912 * multiply, divide, dotDivide
50913 *
50914 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Left hand value
50915 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Right hand value
50916 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y`
50917 */
50918 var dotMultiply = typed('dotMultiply', {
50919
50920 'any, any': multiplyScalar,
50921
50922 'Matrix, Matrix': function (x, y) {
50923 // result
50924 var c;
50925
50926 // process matrix storage
50927 switch (x.storage()) {
50928 case 'sparse':
50929 switch (y.storage()) {
50930 case 'sparse':
50931 // sparse .* sparse
50932 c = algorithm09(x, y, multiplyScalar, false);
50933 break;
50934 default:
50935 // sparse .* dense
50936 c = algorithm02(y, x, multiplyScalar, true);
50937 break;
50938 }
50939 break;
50940 default:
50941 switch (y.storage()) {
50942 case 'sparse':
50943 // dense .* sparse
50944 c = algorithm02(x, y, multiplyScalar, false);
50945 break;
50946 default:
50947 // dense .* dense
50948 c = algorithm13(x, y, multiplyScalar);
50949 break;
50950 }
50951 break;
50952 }
50953 return c;
50954 },
50955
50956 'Array, Array': function (x, y) {
50957 // use matrix implementation
50958 return dotMultiply(matrix(x), matrix(y)).valueOf();
50959 },
50960
50961 'Array, Matrix': function (x, y) {
50962 // use matrix implementation
50963 return dotMultiply(matrix(x), y);
50964 },
50965
50966 'Matrix, Array': function (x, y) {
50967 // use matrix implementation
50968 return dotMultiply(x, matrix(y));
50969 },
50970
50971 'Matrix, any': function (x, y) {
50972 // result
50973 var c;
50974 // check storage format
50975 switch (x.storage()) {
50976 case 'sparse':
50977 c = algorithm11(x, y, multiplyScalar, false);
50978 break;
50979 default:
50980 c = algorithm14(x, y, multiplyScalar, false);
50981 break;
50982 }
50983 return c;
50984 },
50985
50986 'any, Matrix': function (x, y) {
50987 // result
50988 var c;
50989 // check storage format
50990 switch (y.storage()) {
50991 case 'sparse':
50992 c = algorithm11(y, x, multiplyScalar, true);
50993 break;
50994 default:
50995 c = algorithm14(y, x, multiplyScalar, true);
50996 break;
50997 }
50998 return c;
50999 },
51000
51001 'Array, any': function (x, y) {
51002 // use matrix implementation
51003 return algorithm14(matrix(x), y, multiplyScalar, false).valueOf();
51004 },
51005
51006 'any, Array': function (x, y) {
51007 // use matrix implementation
51008 return algorithm14(matrix(y), x, multiplyScalar, true).valueOf();
51009 }
51010 });
51011
51012 dotMultiply.toTex = {
51013 2: '\\left(${args[0]}' + latex.operators['dotMultiply'] + '${args[1]}\\right)'
51014 };
51015
51016 return dotMultiply;
51017}
51018
51019exports.name = 'dotMultiply';
51020exports.factory = factory;
51021
51022
51023/***/ }),
51024/* 433 */
51025/***/ (function(module, exports, __webpack_require__) {
51026
51027"use strict";
51028
51029
51030function factory (type, config, load, typed) {
51031
51032 var matrix = load(__webpack_require__(0));
51033 var pow = load(__webpack_require__(46));
51034 var latex = __webpack_require__(4);
51035
51036 var algorithm03 = load(__webpack_require__(17));
51037 var algorithm07 = load(__webpack_require__(26));
51038 var algorithm11 = load(__webpack_require__(19));
51039 var algorithm12 = load(__webpack_require__(18));
51040 var algorithm13 = load(__webpack_require__(8));
51041 var algorithm14 = load(__webpack_require__(6));
51042
51043 /**
51044 * Calculates the power of x to y element wise.
51045 *
51046 * Syntax:
51047 *
51048 * math.dotPow(x, y)
51049 *
51050 * Examples:
51051 *
51052 * math.dotPow(2, 3); // returns number 8
51053 *
51054 * var a = [[1, 2], [4, 3]];
51055 * math.dotPow(a, 2); // returns Array [[1, 4], [16, 9]]
51056 * math.pow(a, 2); // returns Array [[9, 8], [16, 17]]
51057 *
51058 * See also:
51059 *
51060 * pow, sqrt, multiply
51061 *
51062 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x The base
51063 * @param {number | BigNumber | Complex | Unit | Array | Matrix} y The exponent
51064 * @return {number | BigNumber | Complex | Unit | Array | Matrix} The value of `x` to the power `y`
51065 */
51066 var dotPow = typed('dotPow', {
51067
51068 'any, any': pow,
51069
51070 'Matrix, Matrix': function (x, y) {
51071 // result
51072 var c;
51073
51074 // process matrix storage
51075 switch (x.storage()) {
51076 case 'sparse':
51077 switch (y.storage()) {
51078 case 'sparse':
51079 // sparse .^ sparse
51080 c = algorithm07(x, y, pow, false);
51081 break;
51082 default:
51083 // sparse .^ dense
51084 c = algorithm03(y, x, pow, true);
51085 break;
51086 }
51087 break;
51088 default:
51089 switch (y.storage()) {
51090 case 'sparse':
51091 // dense .^ sparse
51092 c = algorithm03(x, y, pow, false);
51093 break;
51094 default:
51095 // dense .^ dense
51096 c = algorithm13(x, y, pow);
51097 break;
51098 }
51099 break;
51100 }
51101 return c;
51102 },
51103
51104 'Array, Array': function (x, y) {
51105 // use matrix implementation
51106 return dotPow(matrix(x), matrix(y)).valueOf();
51107 },
51108
51109 'Array, Matrix': function (x, y) {
51110 // use matrix implementation
51111 return dotPow(matrix(x), y);
51112 },
51113
51114 'Matrix, Array': function (x, y) {
51115 // use matrix implementation
51116 return dotPow(x, matrix(y));
51117 },
51118
51119 'Matrix, any': function (x, y) {
51120 // result
51121 var c;
51122 // check storage format
51123 switch (x.storage()) {
51124 case 'sparse':
51125 c = algorithm11(x, y, dotPow, false);
51126 break;
51127 default:
51128 c = algorithm14(x, y, dotPow, false);
51129 break;
51130 }
51131 return c;
51132 },
51133
51134 'any, Matrix': function (x, y) {
51135 // result
51136 var c;
51137 // check storage format
51138 switch (y.storage()) {
51139 case 'sparse':
51140 c = algorithm12(y, x, dotPow, true);
51141 break;
51142 default:
51143 c = algorithm14(y, x, dotPow, true);
51144 break;
51145 }
51146 return c;
51147 },
51148
51149 'Array, any': function (x, y) {
51150 // use matrix implementation
51151 return algorithm14(matrix(x), y, dotPow, false).valueOf();
51152 },
51153
51154 'any, Array': function (x, y) {
51155 // use matrix implementation
51156 return algorithm14(matrix(y), x, dotPow, true).valueOf();
51157 }
51158 });
51159
51160 dotPow.toTex = {
51161 2: '\\left(${args[0]}' + latex.operators['dotPow'] + '${args[1]}\\right)'
51162 };
51163
51164 return dotPow;
51165}
51166
51167exports.name = 'dotPow';
51168exports.factory = factory;
51169
51170
51171/***/ }),
51172/* 434 */
51173/***/ (function(module, exports, __webpack_require__) {
51174
51175"use strict";
51176
51177
51178var deepMap = __webpack_require__(1);
51179
51180function factory (type, config, load, typed) {
51181 /**
51182 * Calculate the exponent of a value.
51183 * For matrices, the function is evaluated element wise.
51184 *
51185 * Syntax:
51186 *
51187 * math.exp(x)
51188 *
51189 * Examples:
51190 *
51191 * math.exp(2); // returns number 7.3890560989306495
51192 * math.pow(math.e, 2); // returns number 7.3890560989306495
51193 * math.log(math.exp(2)); // returns number 2
51194 *
51195 * math.exp([1, 2, 3]);
51196 * // returns Array [
51197 * // 2.718281828459045,
51198 * // 7.3890560989306495,
51199 * // 20.085536923187668
51200 * // ]
51201 *
51202 * See also:
51203 *
51204 * log, pow
51205 *
51206 * @param {number | BigNumber | Complex | Array | Matrix} x A number or matrix to exponentiate
51207 * @return {number | BigNumber | Complex | Array | Matrix} Exponent of `x`
51208 */
51209 var exp = typed('exp', {
51210 'number': Math.exp,
51211
51212 'Complex': function (x) {
51213 return x.exp();
51214 },
51215
51216 'BigNumber': function (x) {
51217 return x.exp();
51218 },
51219
51220 'Array | Matrix': function (x) {
51221 // TODO: exp(sparse) should return a dense matrix since exp(0)==1
51222 return deepMap(x, exp);
51223 }
51224 });
51225
51226 exp.toTex = {1: '\\exp\\left(${args[0]}\\right)'};
51227
51228 return exp;
51229}
51230
51231exports.name = 'exp';
51232exports.factory = factory;
51233
51234
51235/***/ }),
51236/* 435 */
51237/***/ (function(module, exports, __webpack_require__) {
51238
51239"use strict";
51240
51241
51242var deepMap = __webpack_require__(1);
51243
51244function factory (type, config, load, typed) {
51245 /**
51246 * Round a value towards minus infinity.
51247 * For matrices, the function is evaluated element wise.
51248 *
51249 * Syntax:
51250 *
51251 * math.floor(x)
51252 *
51253 * Examples:
51254 *
51255 * math.floor(3.2); // returns number 3
51256 * math.floor(3.8); // returns number 3
51257 * math.floor(-4.2); // returns number -5
51258 * math.floor(-4.7); // returns number -5
51259 *
51260 * var c = math.complex(3.2, -2.7);
51261 * math.floor(c); // returns Complex 3 - 3i
51262 *
51263 * math.floor([3.2, 3.8, -4.7]); // returns Array [3, 3, -5]
51264 *
51265 * See also:
51266 *
51267 * ceil, fix, round
51268 *
51269 * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
51270 * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
51271 */
51272 var floor = typed('floor', {
51273 'number': Math.floor,
51274
51275 'Complex': function (x) {
51276 return x.floor();
51277 },
51278
51279 'BigNumber': function (x) {
51280 return x.floor();
51281 },
51282
51283 'Fraction': function (x) {
51284 return x.floor();
51285 },
51286
51287 'Array | Matrix': function (x) {
51288 // deep map collection, skip zeros since floor(0) = 0
51289 return deepMap(x, floor, true);
51290 }
51291 });
51292
51293 floor.toTex = {1: '\\left\\lfloor${args[0]}\\right\\rfloor'};
51294
51295 return floor;
51296}
51297
51298exports.name = 'floor';
51299exports.factory = factory;
51300
51301
51302/***/ }),
51303/* 436 */
51304/***/ (function(module, exports, __webpack_require__) {
51305
51306"use strict";
51307
51308
51309var isInteger = __webpack_require__(3).isInteger;
51310
51311function factory (type, config, load, typed) {
51312
51313 var matrix = load(__webpack_require__(0));
51314
51315 var algorithm01 = load(__webpack_require__(33));
51316 var algorithm04 = load(__webpack_require__(73));
51317 var algorithm10 = load(__webpack_require__(38));
51318 var algorithm13 = load(__webpack_require__(8));
51319 var algorithm14 = load(__webpack_require__(6));
51320
51321 /**
51322 * Calculate the greatest common divisor for two or more values or arrays.
51323 *
51324 * For matrices, the function is evaluated element wise.
51325 *
51326 * Syntax:
51327 *
51328 * math.gcd(a, b)
51329 * math.gcd(a, b, c, ...)
51330 *
51331 * Examples:
51332 *
51333 * math.gcd(8, 12); // returns 4
51334 * math.gcd(-4, 6); // returns 2
51335 * math.gcd(25, 15, -10); // returns 5
51336 *
51337 * math.gcd([8, -4], [12, 6]); // returns [4, 2]
51338 *
51339 * See also:
51340 *
51341 * lcm, xgcd
51342 *
51343 * @param {... number | BigNumber | Fraction | Array | Matrix} args Two or more integer numbers
51344 * @return {number | BigNumber | Fraction | Array | Matrix} The greatest common divisor
51345 */
51346 var gcd = typed('gcd', {
51347
51348 'number, number': _gcd,
51349
51350 'BigNumber, BigNumber': _gcdBigNumber,
51351
51352 'Fraction, Fraction': function (x, y) {
51353 return x.gcd(y);
51354 },
51355
51356 'Matrix, Matrix': function (x, y) {
51357 // result
51358 var c;
51359
51360 // process matrix storage
51361 switch (x.storage()) {
51362 case 'sparse':
51363 switch (y.storage()) {
51364 case 'sparse':
51365 // sparse + sparse
51366 c = algorithm04(x, y, gcd);
51367 break;
51368 default:
51369 // sparse + dense
51370 c = algorithm01(y, x, gcd, true);
51371 break;
51372 }
51373 break;
51374 default:
51375 switch (y.storage()) {
51376 case 'sparse':
51377 // dense + sparse
51378 c = algorithm01(x, y, gcd, false);
51379 break;
51380 default:
51381 // dense + dense
51382 c = algorithm13(x, y, gcd);
51383 break;
51384 }
51385 break;
51386 }
51387 return c;
51388 },
51389
51390 'Array, Array': function (x, y) {
51391 // use matrix implementation
51392 return gcd(matrix(x), matrix(y)).valueOf();
51393 },
51394
51395 'Array, Matrix': function (x, y) {
51396 // use matrix implementation
51397 return gcd(matrix(x), y);
51398 },
51399
51400 'Matrix, Array': function (x, y) {
51401 // use matrix implementation
51402 return gcd(x, matrix(y));
51403 },
51404
51405 'Matrix, number | BigNumber': function (x, y) {
51406 // result
51407 var c;
51408 // check storage format
51409 switch (x.storage()) {
51410 case 'sparse':
51411 c = algorithm10(x, y, gcd, false);
51412 break;
51413 default:
51414 c = algorithm14(x, y, gcd, false);
51415 break;
51416 }
51417 return c;
51418 },
51419
51420 'number | BigNumber, Matrix': function (x, y) {
51421 // result
51422 var c;
51423 // check storage format
51424 switch (y.storage()) {
51425 case 'sparse':
51426 c = algorithm10(y, x, gcd, true);
51427 break;
51428 default:
51429 c = algorithm14(y, x, gcd, true);
51430 break;
51431 }
51432 return c;
51433 },
51434
51435 'Array, number | BigNumber': function (x, y) {
51436 // use matrix implementation
51437 return algorithm14(matrix(x), y, gcd, false).valueOf();
51438 },
51439
51440 'number | BigNumber, Array': function (x, y) {
51441 // use matrix implementation
51442 return algorithm14(matrix(y), x, gcd, true).valueOf();
51443 },
51444
51445 // TODO: need a smarter notation here
51446 'Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber': function (a, b, args) {
51447 var res = gcd(a, b);
51448 for (var i = 0; i < args.length; i++) {
51449 res = gcd(res, args[i]);
51450 }
51451 return res;
51452 }
51453 });
51454
51455 gcd.toTex = '\\gcd\\left(${args}\\right)';
51456
51457 return gcd;
51458
51459 /**
51460 * Calculate gcd for BigNumbers
51461 * @param {BigNumber} a
51462 * @param {BigNumber} b
51463 * @returns {BigNumber} Returns greatest common denominator of a and b
51464 * @private
51465 */
51466 function _gcdBigNumber(a, b) {
51467 if (!a.isInt() || !b.isInt()) {
51468 throw new Error('Parameters in function gcd must be integer numbers');
51469 }
51470
51471 // http://en.wikipedia.org/wiki/Euclidean_algorithm
51472 var zero = new type.BigNumber(0);
51473 while (!b.isZero()) {
51474 var r = a.mod(b);
51475 a = b;
51476 b = r;
51477 }
51478 return a.lt(zero) ? a.neg() : a;
51479 }
51480}
51481
51482/**
51483 * Calculate gcd for numbers
51484 * @param {number} a
51485 * @param {number} b
51486 * @returns {number} Returns the greatest common denominator of a and b
51487 * @private
51488 */
51489function _gcd(a, b) {
51490 if (!isInteger(a) || !isInteger(b)) {
51491 throw new Error('Parameters in function gcd must be integer numbers');
51492 }
51493
51494 // http://en.wikipedia.org/wiki/Euclidean_algorithm
51495 var r;
51496 while (b != 0) {
51497 r = a % b;
51498 a = b;
51499 b = r;
51500 }
51501 return (a < 0) ? -a : a;
51502}
51503
51504exports.name = 'gcd';
51505exports.factory = factory;
51506
51507
51508/***/ }),
51509/* 437 */
51510/***/ (function(module, exports, __webpack_require__) {
51511
51512"use strict";
51513
51514
51515var flatten = __webpack_require__(2).flatten;
51516
51517function factory (type, config, load, typed) {
51518 var abs = load(__webpack_require__(28));
51519 var add = load(__webpack_require__(16));
51520 var divide = load(__webpack_require__(14));
51521 var multiply = load(__webpack_require__(22));
51522 var sqrt = load(__webpack_require__(50));
51523 var smaller = load(__webpack_require__(39));
51524 var isPositive = load(__webpack_require__(57));
51525
51526 /**
51527 * Calculate the hypotenusa of a list with values. The hypotenusa is defined as:
51528 *
51529 * hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...)
51530 *
51531 * For matrix input, the hypotenusa is calculated for all values in the matrix.
51532 *
51533 * Syntax:
51534 *
51535 * math.hypot(a, b, ...)
51536 * math.hypot([a, b, c, ...])
51537 *
51538 * Examples:
51539 *
51540 * math.hypot(3, 4); // 5
51541 * math.hypot(3, 4, 5); // 7.0710678118654755
51542 * math.hypot([3, 4, 5]); // 7.0710678118654755
51543 * math.hypot(-2); // 2
51544 *
51545 * See also:
51546 *
51547 * abs, norm
51548 *
51549 * @param {... number | BigNumber} args
51550 * @return {number | BigNumber} Returns the hypothenusa of the input values.
51551 */
51552 var hypot = typed('hypot', {
51553 '... number | BigNumber': _hypot,
51554
51555 'Array': function (x) {
51556 return hypot.apply(hypot, flatten(x));
51557 },
51558
51559 'Matrix': function (x) {
51560 return hypot.apply(hypot, flatten(x.toArray()));
51561 }
51562 });
51563
51564 /**
51565 * Calculate the hypotenusa for an Array with values
51566 * @param {Array.<number | BigNumber>} args
51567 * @return {number | BigNumber} Returns the result
51568 * @private
51569 */
51570 function _hypot (args) {
51571 // code based on `hypot` from es6-shim:
51572 // https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1619-L1633
51573 var result = 0;
51574 var largest = 0;
51575
51576 for (var i = 0; i < args.length; i++) {
51577 var value = abs(args[i]);
51578 if (smaller(largest, value)) {
51579 result = multiply(result, multiply(divide(largest, value), divide(largest, value)));
51580 result = add(result, 1);
51581 largest = value;
51582 } else {
51583 result = add(result, isPositive(value) ? multiply(divide(value, largest), divide(value, largest)) : value);
51584 }
51585 }
51586
51587 return multiply(largest, sqrt(result));
51588 }
51589
51590 hypot.toTex = '\\hypot\\left(${args}\\right)';
51591
51592 return hypot;
51593}
51594
51595exports.name = 'hypot';
51596exports.factory = factory;
51597
51598
51599/***/ }),
51600/* 438 */
51601/***/ (function(module, exports, __webpack_require__) {
51602
51603"use strict";
51604
51605
51606var isInteger = __webpack_require__(3).isInteger;
51607
51608function factory (type, config, load, typed) {
51609
51610 var matrix = load(__webpack_require__(0));
51611
51612 var algorithm02 = load(__webpack_require__(24));
51613 var algorithm06 = load(__webpack_require__(68));
51614 var algorithm11 = load(__webpack_require__(19));
51615 var algorithm13 = load(__webpack_require__(8));
51616 var algorithm14 = load(__webpack_require__(6));
51617
51618 /**
51619 * Calculate the least common multiple for two or more values or arrays.
51620 *
51621 * lcm is defined as:
51622 *
51623 * lcm(a, b) = abs(a * b) / gcd(a, b)
51624 *
51625 * For matrices, the function is evaluated element wise.
51626 *
51627 * Syntax:
51628 *
51629 * math.lcm(a, b)
51630 * math.lcm(a, b, c, ...)
51631 *
51632 * Examples:
51633 *
51634 * math.lcm(4, 6); // returns 12
51635 * math.lcm(6, 21); // returns 42
51636 * math.lcm(6, 21, 5); // returns 210
51637 *
51638 * math.lcm([4, 6], [6, 21]); // returns [12, 42]
51639 *
51640 * See also:
51641 *
51642 * gcd, xgcd
51643 *
51644 * @param {... number | BigNumber | Array | Matrix} args Two or more integer numbers
51645 * @return {number | BigNumber | Array | Matrix} The least common multiple
51646 */
51647 var lcm = typed('lcm', {
51648 'number, number': _lcm,
51649
51650 'BigNumber, BigNumber': _lcmBigNumber,
51651
51652 'Fraction, Fraction': function (x, y) {
51653
51654 return x.lcm(y);
51655 },
51656
51657 'Matrix, Matrix': function (x, y) {
51658 // result
51659 var c;
51660
51661 // process matrix storage
51662 switch (x.storage()) {
51663 case 'sparse':
51664 switch (y.storage()) {
51665 case 'sparse':
51666 // sparse + sparse
51667 c = algorithm06(x, y, lcm);
51668 break;
51669 default:
51670 // sparse + dense
51671 c = algorithm02(y, x, lcm, true);
51672 break;
51673 }
51674 break;
51675 default:
51676 switch (y.storage()) {
51677 case 'sparse':
51678 // dense + sparse
51679 c = algorithm02(x, y, lcm, false);
51680 break;
51681 default:
51682 // dense + dense
51683 c = algorithm13(x, y, lcm);
51684 break;
51685 }
51686 break;
51687 }
51688 return c;
51689 },
51690
51691 'Array, Array': function (x, y) {
51692 // use matrix implementation
51693 return lcm(matrix(x), matrix(y)).valueOf();
51694 },
51695
51696 'Array, Matrix': function (x, y) {
51697 // use matrix implementation
51698 return lcm(matrix(x), y);
51699 },
51700
51701 'Matrix, Array': function (x, y) {
51702 // use matrix implementation
51703 return lcm(x, matrix(y));
51704 },
51705
51706 'Matrix, number | BigNumber': function (x, y) {
51707 // result
51708 var c;
51709 // check storage format
51710 switch (x.storage()) {
51711 case 'sparse':
51712 c = algorithm11(x, y, lcm, false);
51713 break;
51714 default:
51715 c = algorithm14(x, y, lcm, false);
51716 break;
51717 }
51718 return c;
51719 },
51720
51721 'number | BigNumber, Matrix': function (x, y) {
51722 // result
51723 var c;
51724 // check storage format
51725 switch (y.storage()) {
51726 case 'sparse':
51727 c = algorithm11(y, x, lcm, true);
51728 break;
51729 default:
51730 c = algorithm14(y, x, lcm, true);
51731 break;
51732 }
51733 return c;
51734 },
51735
51736 'Array, number | BigNumber': function (x, y) {
51737 // use matrix implementation
51738 return algorithm14(matrix(x), y, lcm, false).valueOf();
51739 },
51740
51741 'number | BigNumber, Array': function (x, y) {
51742 // use matrix implementation
51743 return algorithm14(matrix(y), x, lcm, true).valueOf();
51744 },
51745
51746 // TODO: need a smarter notation here
51747 'Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber': function (a, b, args) {
51748 var res = lcm(a, b);
51749 for (var i = 0; i < args.length; i++) {
51750 res = lcm(res, args[i]);
51751 }
51752 return res;
51753 }
51754 });
51755
51756 lcm.toTex = undefined; // use default template
51757
51758 return lcm;
51759
51760 /**
51761 * Calculate lcm for two BigNumbers
51762 * @param {BigNumber} a
51763 * @param {BigNumber} b
51764 * @returns {BigNumber} Returns the least common multiple of a and b
51765 * @private
51766 */
51767 function _lcmBigNumber(a, b) {
51768 if (!a.isInt() || !b.isInt()) {
51769 throw new Error('Parameters in function lcm must be integer numbers');
51770 }
51771
51772 if (a.isZero() || b.isZero()) {
51773 return new type.BigNumber(0);
51774 }
51775
51776 // http://en.wikipedia.org/wiki/Euclidean_algorithm
51777 // evaluate lcm here inline to reduce overhead
51778 var prod = a.times(b);
51779 while (!b.isZero()) {
51780 var t = b;
51781 b = a.mod(t);
51782 a = t;
51783 }
51784 return prod.div(a).abs();
51785 }
51786}
51787
51788/**
51789 * Calculate lcm for two numbers
51790 * @param {number} a
51791 * @param {number} b
51792 * @returns {number} Returns the least common multiple of a and b
51793 * @private
51794 */
51795function _lcm (a, b) {
51796 if (!isInteger(a) || !isInteger(b)) {
51797 throw new Error('Parameters in function lcm must be integer numbers');
51798 }
51799
51800 if (a == 0 || b == 0) {
51801 return 0;
51802 }
51803
51804 // http://en.wikipedia.org/wiki/Euclidean_algorithm
51805 // evaluate lcm here inline to reduce overhead
51806 var t;
51807 var prod = a * b;
51808 while (b != 0) {
51809 t = b;
51810 b = a % t;
51811 a = t;
51812 }
51813 return Math.abs(prod / a);
51814}
51815
51816exports.name = 'lcm';
51817exports.factory = factory;
51818
51819
51820/***/ }),
51821/* 439 */
51822/***/ (function(module, exports, __webpack_require__) {
51823
51824"use strict";
51825
51826
51827module.exports = function scatter(a, j, w, x, u, mark, c, f, inverse, update, value) {
51828 // a arrays
51829 var avalues = a._values;
51830 var aindex = a._index;
51831 var aptr = a._ptr;
51832 // c arrays
51833 var cindex = c._index;
51834
51835 // vars
51836 var k, k0, k1, i;
51837
51838 // check we need to process values (pattern matrix)
51839 if (x) {
51840 // values in j
51841 for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
51842 // row
51843 i = aindex[k];
51844 // check value exists in current j
51845 if (w[i] !== mark) {
51846 // i is new entry in j
51847 w[i] = mark;
51848 // add i to pattern of C
51849 cindex.push(i);
51850 // x(i) = A, check we need to call function this time
51851 if (update) {
51852 // copy value to workspace calling callback function
51853 x[i] = inverse ? f(avalues[k], value) : f(value, avalues[k]);
51854 // function was called on current row
51855 u[i] = mark;
51856 }
51857 else {
51858 // copy value to workspace
51859 x[i] = avalues[k];
51860 }
51861 }
51862 else {
51863 // i exists in C already
51864 x[i] = inverse ? f(avalues[k], x[i]) : f(x[i], avalues[k]);
51865 // function was called on current row
51866 u[i] = mark;
51867 }
51868 }
51869 }
51870 else {
51871 // values in j
51872 for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
51873 // row
51874 i = aindex[k];
51875 // check value exists in current j
51876 if (w[i] !== mark) {
51877 // i is new entry in j
51878 w[i] = mark;
51879 // add i to pattern of C
51880 cindex.push(i);
51881 }
51882 else {
51883 // indicate function was called on current row
51884 u[i] = mark;
51885 }
51886 }
51887 }
51888};
51889
51890
51891/***/ }),
51892/* 440 */
51893/***/ (function(module, exports, __webpack_require__) {
51894
51895"use strict";
51896
51897
51898var deepMap = __webpack_require__(1);
51899
51900function factory (type, config, load, typed) {
51901 /**
51902 * Calculate the 10-base logarithm of a value. This is the same as calculating `log(x, 10)`.
51903 *
51904 * For matrices, the function is evaluated element wise.
51905 *
51906 * Syntax:
51907 *
51908 * math.log10(x)
51909 *
51910 * Examples:
51911 *
51912 * math.log10(0.00001); // returns -5
51913 * math.log10(10000); // returns 4
51914 * math.log(10000) / math.log(10); // returns 4
51915 * math.pow(10, 4); // returns 10000
51916 *
51917 * See also:
51918 *
51919 * exp, log
51920 *
51921 * @param {number | BigNumber | Complex | Array | Matrix} x
51922 * Value for which to calculate the logarithm.
51923 * @return {number | BigNumber | Complex | Array | Matrix}
51924 * Returns the 10-base logarithm of `x`
51925 */
51926 var log10 = typed('log10', {
51927 'number': function (x) {
51928 if (x >= 0 || config.predictable) {
51929 return _log10(x);
51930 }
51931 else {
51932 // negative value -> complex value computation
51933 return new type.Complex(x, 0).log().div(Math.LN10);
51934 }
51935 },
51936
51937 'Complex': function (x) {
51938 return new type.Complex(x).log().div(Math.LN10);
51939 },
51940
51941 'BigNumber': function (x) {
51942 if (!x.isNegative() || config.predictable) {
51943 return x.log();
51944 }
51945 else {
51946 // downgrade to number, return Complex valued result
51947 return new type.Complex(x.toNumber(), 0).log().div(Math.LN10);
51948 }
51949 },
51950
51951 'Array | Matrix': function (x) {
51952 return deepMap(x, log10);
51953 }
51954 });
51955
51956 log10.toTex = {1: '\\log_{10}\\left(${args[0]}\\right)'};
51957
51958 return log10;
51959}
51960
51961/**
51962 * Calculate the 10-base logarithm of a number
51963 * @param {number} x
51964 * @return {number}
51965 * @private
51966 */
51967var _log10 = Math.log10 || function (x) {
51968 return Math.log(x) / Math.LN10;
51969};
51970
51971exports.name = 'log10';
51972exports.factory = factory;
51973
51974
51975
51976/***/ }),
51977/* 441 */
51978/***/ (function(module, exports, __webpack_require__) {
51979
51980"use strict";
51981
51982
51983function factory (type, config, load, typed) {
51984
51985 var matrix = load(__webpack_require__(0));
51986 var latex = __webpack_require__(4);
51987
51988 var algorithm02 = load(__webpack_require__(24));
51989 var algorithm03 = load(__webpack_require__(17));
51990 var algorithm05 = load(__webpack_require__(61));
51991 var algorithm11 = load(__webpack_require__(19));
51992 var algorithm12 = load(__webpack_require__(18));
51993 var algorithm13 = load(__webpack_require__(8));
51994 var algorithm14 = load(__webpack_require__(6));
51995
51996 /**
51997 * Calculates the modulus, the remainder of an integer division.
51998 *
51999 * For matrices, the function is evaluated element wise.
52000 *
52001 * The modulus is defined as:
52002 *
52003 * x - y * floor(x / y)
52004 *
52005 * See http://en.wikipedia.org/wiki/Modulo_operation.
52006 *
52007 * Syntax:
52008 *
52009 * math.mod(x, y)
52010 *
52011 * Examples:
52012 *
52013 * math.mod(8, 3); // returns 2
52014 * math.mod(11, 2); // returns 1
52015 *
52016 * function isOdd(x) {
52017 * return math.mod(x, 2) != 0;
52018 * }
52019 *
52020 * isOdd(2); // returns false
52021 * isOdd(3); // returns true
52022 *
52023 * See also:
52024 *
52025 * divide
52026 *
52027 * @param {number | BigNumber | Fraction | Array | Matrix} x Dividend
52028 * @param {number | BigNumber | Fraction | Array | Matrix} y Divisor
52029 * @return {number | BigNumber | Fraction | Array | Matrix} Returns the remainder of `x` divided by `y`.
52030 */
52031 var mod = typed('mod', {
52032
52033 'number, number': _mod,
52034
52035 'BigNumber, BigNumber': function (x, y) {
52036 return y.isZero() ? x : x.mod(y);
52037 },
52038
52039 'Fraction, Fraction': function (x, y) {
52040 return x.mod(y);
52041 },
52042
52043 'Matrix, Matrix': function (x, y) {
52044 // result
52045 var c;
52046
52047 // process matrix storage
52048 switch (x.storage()) {
52049 case 'sparse':
52050 switch (y.storage()) {
52051 case 'sparse':
52052 // mod(sparse, sparse)
52053 c = algorithm05(x, y, mod, false);
52054 break;
52055 default:
52056 // mod(sparse, dense)
52057 c = algorithm02(y, x, mod, true);
52058 break;
52059 }
52060 break;
52061 default:
52062 switch (y.storage()) {
52063 case 'sparse':
52064 // mod(dense, sparse)
52065 c = algorithm03(x, y, mod, false);
52066 break;
52067 default:
52068 // mod(dense, dense)
52069 c = algorithm13(x, y, mod);
52070 break;
52071 }
52072 break;
52073 }
52074 return c;
52075 },
52076
52077 'Array, Array': function (x, y) {
52078 // use matrix implementation
52079 return mod(matrix(x), matrix(y)).valueOf();
52080 },
52081
52082 'Array, Matrix': function (x, y) {
52083 // use matrix implementation
52084 return mod(matrix(x), y);
52085 },
52086
52087 'Matrix, Array': function (x, y) {
52088 // use matrix implementation
52089 return mod(x, matrix(y));
52090 },
52091
52092 'Matrix, any': function (x, y) {
52093 // result
52094 var c;
52095 // check storage format
52096 switch (x.storage()) {
52097 case 'sparse':
52098 c = algorithm11(x, y, mod, false);
52099 break;
52100 default:
52101 c = algorithm14(x, y, mod, false);
52102 break;
52103 }
52104 return c;
52105 },
52106
52107 'any, Matrix': function (x, y) {
52108 // result
52109 var c;
52110 // check storage format
52111 switch (y.storage()) {
52112 case 'sparse':
52113 c = algorithm12(y, x, mod, true);
52114 break;
52115 default:
52116 c = algorithm14(y, x, mod, true);
52117 break;
52118 }
52119 return c;
52120 },
52121
52122 'Array, any': function (x, y) {
52123 // use matrix implementation
52124 return algorithm14(matrix(x), y, mod, false).valueOf();
52125 },
52126
52127 'any, Array': function (x, y) {
52128 // use matrix implementation
52129 return algorithm14(matrix(y), x, mod, true).valueOf();
52130 }
52131 });
52132
52133 mod.toTex = {
52134 2: '\\left(${args[0]}' + latex.operators['mod'] + '${args[1]}\\right)'
52135 };
52136
52137 return mod;
52138
52139 /**
52140 * Calculate the modulus of two numbers
52141 * @param {number} x
52142 * @param {number} y
52143 * @returns {number} res
52144 * @private
52145 */
52146 function _mod(x, y) {
52147 if (y > 0) {
52148 // We don't use JavaScript's % operator here as this doesn't work
52149 // correctly for x < 0 and x == 0
52150 // see http://en.wikipedia.org/wiki/Modulo_operation
52151 return x - y * Math.floor(x / y);
52152 }
52153 else if (y === 0) {
52154 return x;
52155 }
52156 else { // y < 0
52157 // TODO: implement mod for a negative divisor
52158 throw new Error('Cannot calculate mod for a negative divisor');
52159 }
52160 }
52161}
52162
52163exports.name = 'mod';
52164exports.factory = factory;
52165
52166
52167/***/ }),
52168/* 442 */
52169/***/ (function(module, exports, __webpack_require__) {
52170
52171"use strict";
52172
52173
52174function factory (type, config, load, typed) {
52175
52176 var abs = load(__webpack_require__(28));
52177 var add = load(__webpack_require__(20));
52178 var pow = load(__webpack_require__(46));
52179 var sqrt = load(__webpack_require__(50));
52180 var multiply = load(__webpack_require__(12));
52181 var equalScalar = load(__webpack_require__(10));
52182 var larger = load(__webpack_require__(34));
52183 var smaller = load(__webpack_require__(39));
52184 var matrix = load(__webpack_require__(0));
52185 var trace = load(__webpack_require__(138));
52186 var transpose = load(__webpack_require__(67));
52187
52188
52189 /**
52190 * Calculate the norm of a number, vector or matrix.
52191 *
52192 * The second parameter p is optional. If not provided, it defaults to 2.
52193 *
52194 * Syntax:
52195 *
52196 * math.norm(x)
52197 * math.norm(x, p)
52198 *
52199 * Examples:
52200 *
52201 * math.abs(-3.5); // returns 3.5
52202 * math.norm(-3.5); // returns 3.5
52203 *
52204 * math.norm(math.complex(3, -4)); // returns 5
52205 *
52206 * math.norm([1, 2, -3], Infinity); // returns 3
52207 * math.norm([1, 2, -3], -Infinity); // returns 1
52208 *
52209 * math.norm([3, 4], 2); // returns 5
52210 *
52211 * math.norm([[1, 2], [3, 4]], 1) // returns 6
52212 * math.norm([[1, 2], [3, 4]], 'inf'); // returns 7
52213 * math.norm([[1, 2], [3, 4]], 'fro'); // returns 5.477225575051661
52214 *
52215 * See also:
52216 *
52217 * abs, hypot
52218 *
52219 * @param {number | BigNumber | Complex | Array | Matrix} x
52220 * Value for which to calculate the norm
52221 * @param {number | BigNumber | string} [p=2]
52222 * Vector space.
52223 * Supported numbers include Infinity and -Infinity.
52224 * Supported strings are: 'inf', '-inf', and 'fro' (The Frobenius norm)
52225 * @return {number | BigNumber} the p-norm
52226 */
52227 var norm = typed('norm', {
52228 'number': Math.abs,
52229
52230 'Complex': function (x) {
52231 return x.abs();
52232 },
52233
52234 'BigNumber': function (x) {
52235 // norm(x) = abs(x)
52236 return x.abs();
52237 },
52238
52239 'boolean | null' : function (x) {
52240 // norm(x) = abs(x)
52241 return Math.abs(x);
52242 },
52243
52244 'Array': function (x) {
52245 return _norm(matrix(x), 2);
52246 },
52247
52248 'Matrix': function (x) {
52249 return _norm(x, 2);
52250 },
52251
52252 'number | Complex | BigNumber | boolean | null, number | BigNumber | string': function (x) {
52253 // ignore second parameter, TODO: remove the option of second parameter for these types
52254 return norm(x);
52255 },
52256
52257 'Array, number | BigNumber | string': function (x, p) {
52258 return _norm(matrix(x), p);
52259 },
52260
52261 'Matrix, number | BigNumber | string': function (x, p) {
52262 return _norm(x, p);
52263 }
52264 });
52265
52266 /**
52267 * Calculate the norm for an array
52268 * @param {Array} x
52269 * @param {number | string} p
52270 * @returns {number} Returns the norm
52271 * @private
52272 */
52273 function _norm (x, p) {
52274 // size
52275 var sizeX = x.size();
52276
52277 // check if it is a vector
52278 if (sizeX.length == 1) {
52279 // check p
52280 if (p === Number.POSITIVE_INFINITY || p === 'inf') {
52281 // norm(x, Infinity) = max(abs(x))
52282 var pinf = 0;
52283 // skip zeros since abs(0) == 0
52284 x.forEach(
52285 function (value) {
52286 var v = abs(value);
52287 if (larger(v, pinf))
52288 pinf = v;
52289 },
52290 true);
52291 return pinf;
52292 }
52293 if (p === Number.NEGATIVE_INFINITY || p === '-inf') {
52294 // norm(x, -Infinity) = min(abs(x))
52295 var ninf;
52296 // skip zeros since abs(0) == 0
52297 x.forEach(
52298 function (value) {
52299 var v = abs(value);
52300 if (!ninf || smaller(v, ninf))
52301 ninf = v;
52302 },
52303 true);
52304 return ninf || 0;
52305 }
52306 if (p === 'fro') {
52307 return _norm(x, 2);
52308 }
52309 if (typeof p === 'number' && !isNaN(p)) {
52310 // check p != 0
52311 if (!equalScalar(p, 0)) {
52312 // norm(x, p) = sum(abs(xi) ^ p) ^ 1/p
52313 var n = 0;
52314 // skip zeros since abs(0) == 0
52315 x.forEach(
52316 function (value) {
52317 n = add(pow(abs(value), p), n);
52318 },
52319 true);
52320 return pow(n, 1 / p);
52321 }
52322 return Number.POSITIVE_INFINITY;
52323 }
52324 // invalid parameter value
52325 throw new Error('Unsupported parameter value');
52326 }
52327 // MxN matrix
52328 if (sizeX.length == 2) {
52329 // check p
52330 if (p === 1) {
52331 // norm(x) = the largest column sum
52332 var c = [];
52333 // result
52334 var maxc = 0;
52335 // skip zeros since abs(0) == 0
52336 x.forEach(
52337 function (value, index) {
52338 var j = index[1];
52339 var cj = add(c[j] || 0, abs(value));
52340 if (larger(cj, maxc))
52341 maxc = cj;
52342 c[j] = cj;
52343 },
52344 true);
52345 return maxc;
52346 }
52347 if (p === Number.POSITIVE_INFINITY || p === 'inf') {
52348 // norm(x) = the largest row sum
52349 var r = [];
52350 // result
52351 var maxr = 0;
52352 // skip zeros since abs(0) == 0
52353 x.forEach(
52354 function (value, index) {
52355 var i = index[0];
52356 var ri = add(r[i] || 0, abs(value));
52357 if (larger(ri, maxr))
52358 maxr = ri;
52359 r[i] = ri;
52360 },
52361 true);
52362 return maxr;
52363 }
52364 if (p === 'fro') {
52365 // norm(x) = sqrt(sum(diag(x'x)))
52366 return sqrt(trace(multiply(transpose(x), x)));
52367 }
52368 if (p === 2) {
52369 // not implemented
52370 throw new Error('Unsupported parameter value, missing implementation of matrix singular value decomposition');
52371 }
52372 // invalid parameter value
52373 throw new Error('Unsupported parameter value');
52374 }
52375 }
52376
52377 norm.toTex = {
52378 1: '\\left\\|${args[0]}\\right\\|',
52379 2: undefined // use default template
52380 };
52381
52382 return norm;
52383}
52384
52385exports.name = 'norm';
52386exports.factory = factory;
52387
52388
52389/***/ }),
52390/* 443 */
52391/***/ (function(module, exports, __webpack_require__) {
52392
52393"use strict";
52394
52395
52396function factory (type, config, load, typed) {
52397
52398 var matrix = load(__webpack_require__(0));
52399
52400 var algorithm01 = load(__webpack_require__(33));
52401 var algorithm02 = load(__webpack_require__(24));
52402 var algorithm06 = load(__webpack_require__(68));
52403 var algorithm11 = load(__webpack_require__(19));
52404 var algorithm13 = load(__webpack_require__(8));
52405 var algorithm14 = load(__webpack_require__(6));
52406
52407 /**
52408 * Calculate the nth root of a value.
52409 * The principal nth root of a positive real number A, is the positive real
52410 * solution of the equation
52411 *
52412 * x^root = A
52413 *
52414 * For matrices, the function is evaluated element wise.
52415 *
52416 * Syntax:
52417 *
52418 * math.nthRoot(a)
52419 * math.nthRoot(a, root)
52420 *
52421 * Examples:
52422 *
52423 * math.nthRoot(9, 2); // returns 3, as 3^2 == 9
52424 * math.sqrt(9); // returns 3, as 3^2 == 9
52425 * math.nthRoot(64, 3); // returns 4, as 4^3 == 64
52426 *
52427 * See also:
52428 *
52429 * sqrt, pow
52430 *
52431 * @param {number | BigNumber | Array | Matrix | Complex} a
52432 * Value for which to calculate the nth root
52433 * @param {number | BigNumber} [root=2] The root.
52434 * @return {number | Complex | Array | Matrix} Returns the nth root of `a`
52435 */
52436 var nthRoot = typed('nthRoot', {
52437
52438 'number': function (x) {
52439 return _nthRoot(x, 2);
52440 },
52441 'number, number': _nthRoot,
52442
52443 'BigNumber': function (x) {
52444 return _bigNthRoot(x, new type.BigNumber(2));
52445 },
52446 'Complex' : function(x) {
52447 return _nthComplexRoot(x, 2);
52448 },
52449 'Complex, number' : _nthComplexRoot,
52450 'BigNumber, BigNumber': _bigNthRoot,
52451
52452 'Array | Matrix': function (x) {
52453 return nthRoot(x, 2);
52454 },
52455
52456 'Matrix, Matrix': function (x, y) {
52457 // result
52458 var c;
52459
52460 // process matrix storage
52461 switch (x.storage()) {
52462 case 'sparse':
52463 switch (y.storage()) {
52464 case 'sparse':
52465 // density must be one (no zeros in matrix)
52466 if (y.density() === 1) {
52467 // sparse + sparse
52468 c = algorithm06(x, y, nthRoot);
52469 }
52470 else {
52471 // throw exception
52472 throw new Error('Root must be non-zero');
52473 }
52474 break;
52475 default:
52476 // sparse + dense
52477 c = algorithm02(y, x, nthRoot, true);
52478 break;
52479 }
52480 break;
52481 default:
52482 switch (y.storage()) {
52483 case 'sparse':
52484 // density must be one (no zeros in matrix)
52485 if (y.density() === 1) {
52486 // dense + sparse
52487 c = algorithm01(x, y, nthRoot, false);
52488 }
52489 else {
52490 // throw exception
52491 throw new Error('Root must be non-zero');
52492 }
52493 break;
52494 default:
52495 // dense + dense
52496 c = algorithm13(x, y, nthRoot);
52497 break;
52498 }
52499 break;
52500 }
52501 return c;
52502 },
52503
52504 'Array, Array': function (x, y) {
52505 // use matrix implementation
52506 return nthRoot(matrix(x), matrix(y)).valueOf();
52507 },
52508
52509 'Array, Matrix': function (x, y) {
52510 // use matrix implementation
52511 return nthRoot(matrix(x), y);
52512 },
52513
52514 'Matrix, Array': function (x, y) {
52515 // use matrix implementation
52516 return nthRoot(x, matrix(y));
52517 },
52518
52519 'Matrix, number | BigNumber': function (x, y) {
52520 // result
52521 var c;
52522 // check storage format
52523 switch (x.storage()) {
52524 case 'sparse':
52525 c = algorithm11(x, y, nthRoot, false);
52526 break;
52527 default:
52528 c = algorithm14(x, y, nthRoot, false);
52529 break;
52530 }
52531 return c;
52532 },
52533
52534 'number | BigNumber, Matrix': function (x, y) {
52535 // result
52536 var c;
52537 // check storage format
52538 switch (y.storage()) {
52539 case 'sparse':
52540 // density must be one (no zeros in matrix)
52541 if (y.density() === 1) {
52542 // sparse - scalar
52543 c = algorithm11(y, x, nthRoot, true);
52544 }
52545 else {
52546 // throw exception
52547 throw new Error('Root must be non-zero');
52548 }
52549 break;
52550 default:
52551 c = algorithm14(y, x, nthRoot, true);
52552 break;
52553 }
52554 return c;
52555 },
52556
52557 'Array, number | BigNumber': function (x, y) {
52558 // use matrix implementation
52559 return nthRoot(matrix(x), y).valueOf();
52560 },
52561
52562 'number | BigNumber, Array': function (x, y) {
52563 // use matrix implementation
52564 return nthRoot(x, matrix(y)).valueOf();
52565 }
52566 });
52567
52568 nthRoot.toTex = {2: '\\sqrt[${args[1]}]{${args[0]}}'};
52569
52570 return nthRoot;
52571
52572 /**
52573 * Calculate the nth root of a for BigNumbers, solve x^root == a
52574 * http://rosettacode.org/wiki/Nth_root#JavaScript
52575 * @param {BigNumber} a
52576 * @param {BigNumber} root
52577 * @private
52578 */
52579 function _bigNthRoot(a, root) {
52580 var precision = type.BigNumber.precision;
52581 var Big = type.BigNumber.clone({precision: precision + 2});
52582 var zero = new type.BigNumber(0);
52583
52584 var one = new Big(1);
52585 var inv = root.isNegative();
52586 if (inv) {
52587 root = root.neg();
52588 }
52589
52590 if (root.isZero()) {
52591 throw new Error('Root must be non-zero');
52592 }
52593 if (a.isNegative() && !root.abs().mod(2).equals(1)) {
52594 throw new Error('Root must be odd when a is negative.');
52595 }
52596
52597 // edge cases zero and infinity
52598 if (a.isZero()) {
52599 return inv ? new Big(Infinity) : 0;
52600 }
52601 if (!a.isFinite()) {
52602 return inv ? zero : a;
52603 }
52604
52605 var x = a.abs().pow(one.div(root));
52606 // If a < 0, we require that root is an odd integer,
52607 // so (-1) ^ (1/root) = -1
52608 x = a.isNeg() ? x.neg() : x;
52609 return new type.BigNumber((inv ? one.div(x) : x).toPrecision(precision));
52610 }
52611}
52612
52613/**
52614 * Calculate the nth root of a, solve x^root == a
52615 * http://rosettacode.org/wiki/Nth_root#JavaScript
52616 * @param {number} a
52617 * @param {number} root
52618 * @private
52619 */
52620function _nthRoot(a, root) {
52621 var inv = root < 0;
52622 if (inv) {
52623 root = -root;
52624 }
52625
52626 if (root === 0) {
52627 throw new Error('Root must be non-zero');
52628 }
52629 if (a < 0 && (Math.abs(root) % 2 != 1)) {
52630 throw new Error('Root must be odd when a is negative.');
52631 }
52632
52633 // edge cases zero and infinity
52634 if (a == 0) {
52635 return inv ? Infinity : 0;
52636 }
52637 if (!isFinite(a)) {
52638 return inv ? 0 : a;
52639 }
52640
52641 var x = Math.pow(Math.abs(a), 1/root);
52642 // If a < 0, we require that root is an odd integer,
52643 // so (-1) ^ (1/root) = -1
52644 x = a < 0 ? -x : x;
52645 return inv ? 1 / x : x;
52646
52647 // Very nice algorithm, but fails with nthRoot(-2, 3).
52648 // Newton's method has some well-known problems at times:
52649 // https://en.wikipedia.org/wiki/Newton%27s_method#Failure_analysis
52650 /*
52651 var x = 1; // Initial guess
52652 var xPrev = 1;
52653 var i = 0;
52654 var iMax = 10000;
52655 do {
52656 var delta = (a / Math.pow(x, root - 1) - x) / root;
52657 xPrev = x;
52658 x = x + delta;
52659 i++;
52660 }
52661 while (xPrev !== x && i < iMax);
52662
52663 if (xPrev !== x) {
52664 throw new Error('Function nthRoot failed to converge');
52665 }
52666
52667 return inv ? 1 / x : x;
52668 */
52669}
52670
52671/**
52672 * Calculate the nth root of a Complex Number a using De Moviers Theorem.
52673 * @param {Complex} a
52674 * @param {number} root
52675 * @return {Array} array or n Complex Roots in Polar Form.
52676 */
52677function _nthComplexRoot(a, root) {
52678 if (root < 0) throw new Error('Root must be greater than zero');
52679 if (root === 0) throw new Error('Root must be non-zero');
52680 if (root % 1 !== 0) throw new Error('Root must be an integer');
52681 var arg = a.arg();
52682 var abs = a.abs();
52683 var roots = [];
52684 var r = Math.pow(abs, 1/root);
52685 for(var k = 0; k < root; k++) {
52686 roots.push({r: r, phi: (arg + 2 * Math.PI * k)/root});
52687 }
52688 return roots;
52689}
52690
52691exports.name = 'nthRoot';
52692exports.factory = factory;
52693
52694
52695/***/ }),
52696/* 444 */
52697/***/ (function(module, exports, __webpack_require__) {
52698
52699"use strict";
52700
52701
52702var deepMap = __webpack_require__(1);
52703
52704function factory (type, config, load, typed) {
52705 /**
52706 * Compute the square of a value, `x * x`.
52707 * For matrices, the function is evaluated element wise.
52708 *
52709 * Syntax:
52710 *
52711 * math.square(x)
52712 *
52713 * Examples:
52714 *
52715 * math.square(2); // returns number 4
52716 * math.square(3); // returns number 9
52717 * math.pow(3, 2); // returns number 9
52718 * math.multiply(3, 3); // returns number 9
52719 *
52720 * math.square([1, 2, 3, 4]); // returns Array [1, 4, 9, 16]
52721 *
52722 * See also:
52723 *
52724 * multiply, cube, sqrt, pow
52725 *
52726 * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x
52727 * Number for which to calculate the square
52728 * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit}
52729 * Squared value
52730 */
52731 var square = typed('square', {
52732 'number': function (x) {
52733 return x * x;
52734 },
52735
52736 'Complex': function (x) {
52737 return x.mul(x);
52738 },
52739
52740 'BigNumber': function (x) {
52741 return x.times(x);
52742 },
52743
52744 'Fraction': function (x) {
52745 return x.mul(x);
52746 },
52747
52748 'Array | Matrix': function (x) {
52749 // deep map collection, skip zeros since square(0) = 0
52750 return deepMap(x, square, true);
52751 },
52752
52753 'Unit': function(x) {
52754 return x.pow(2);
52755 }
52756 });
52757
52758 square.toTex = {1: '\\left(${args[0]}\\right)^2'};
52759
52760 return square;
52761}
52762
52763exports.name = 'square';
52764exports.factory = factory;
52765
52766
52767/***/ }),
52768/* 445 */
52769/***/ (function(module, exports, __webpack_require__) {
52770
52771"use strict";
52772
52773
52774var deepMap = __webpack_require__(1);
52775
52776function factory (type, config, load, typed) {
52777 var latex = __webpack_require__(4);
52778
52779 /**
52780 * Unary plus operation.
52781 * Boolean values and strings will be converted to a number, numeric values will be returned as is.
52782 *
52783 * For matrices, the function is evaluated element wise.
52784 *
52785 * Syntax:
52786 *
52787 * math.unaryPlus(x)
52788 *
52789 * Examples:
52790 *
52791 * math.unaryPlus(3.5); // returns 3.5
52792 * math.unaryPlus(1); // returns 1
52793 *
52794 * See also:
52795 *
52796 * unaryMinus, add, subtract
52797 *
52798 * @param {number | BigNumber | Fraction | string | Complex | Unit | Array | Matrix} x
52799 * Input value
52800 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix}
52801 * Returns the input value when numeric, converts to a number when input is non-numeric.
52802 */
52803 var unaryPlus = typed('unaryPlus', {
52804 'number': function (x) {
52805 return x;
52806 },
52807
52808 'Complex': function (x) {
52809 return x; // complex numbers are immutable
52810 },
52811
52812 'BigNumber': function (x) {
52813 return x; // bignumbers are immutable
52814 },
52815
52816 'Fraction': function (x) {
52817 return x; // fractions are immutable
52818 },
52819
52820 'Unit': function (x) {
52821 return x.clone();
52822 },
52823
52824 'Array | Matrix': function (x) {
52825 // deep map collection, skip zeros since unaryPlus(0) = 0
52826 return deepMap(x, unaryPlus, true);
52827 },
52828
52829 'boolean | string | null': function (x) {
52830 // convert to a number or bignumber
52831 return (config.number == 'BigNumber') ? new type.BigNumber(+x): +x;
52832 }
52833 });
52834
52835 unaryPlus.toTex = {
52836 1: latex.operators['unaryPlus'] + '\\left(${args[0]}\\right)'
52837 };
52838
52839 return unaryPlus;
52840}
52841
52842exports.name = 'unaryPlus';
52843exports.factory = factory;
52844
52845
52846/***/ }),
52847/* 446 */
52848/***/ (function(module, exports, __webpack_require__) {
52849
52850"use strict";
52851
52852
52853var isInteger = __webpack_require__(3).isInteger;
52854
52855function factory (type, config, load, typed) {
52856 var matrix = load(__webpack_require__(0));
52857
52858 /**
52859 * Calculate the extended greatest common divisor for two values.
52860 * See http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm.
52861 *
52862 * Syntax:
52863 *
52864 * math.xgcd(a, b)
52865 *
52866 * Examples:
52867 *
52868 * math.xgcd(8, 12); // returns [4, -1, 1]
52869 * math.gcd(8, 12); // returns 4
52870 * math.xgcd(36163, 21199); // returns [1247, -7, 12]
52871 *
52872 * See also:
52873 *
52874 * gcd, lcm
52875 *
52876 * @param {number | BigNumber} a An integer number
52877 * @param {number | BigNumber} b An integer number
52878 * @return {Array} Returns an array containing 3 integers `[div, m, n]`
52879 * where `div = gcd(a, b)` and `a*m + b*n = div`
52880 */
52881 var xgcd = typed('xgcd', {
52882 'number, number': _xgcd,
52883 'BigNumber, BigNumber': _xgcdBigNumber
52884 // TODO: implement support for Fraction
52885 });
52886
52887 xgcd.toTex = undefined; // use default template
52888
52889 return xgcd;
52890
52891 /**
52892 * Calculate xgcd for two numbers
52893 * @param {number} a
52894 * @param {number} b
52895 * @return {number} result
52896 * @private
52897 */
52898 function _xgcd (a, b) {
52899 // source: http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
52900 var t, // used to swap two variables
52901 q, // quotient
52902 r, // remainder
52903 x = 0, lastx = 1,
52904 y = 1, lasty = 0;
52905
52906 if (!isInteger(a) || !isInteger(b)) {
52907 throw new Error('Parameters in function xgcd must be integer numbers');
52908 }
52909
52910 while (b) {
52911 q = Math.floor(a / b);
52912 r = a - q*b;
52913
52914 t = x;
52915 x = lastx - q * x;
52916 lastx = t;
52917
52918 t = y;
52919 y = lasty - q * y;
52920 lasty = t;
52921
52922 a = b;
52923 b = r;
52924 }
52925
52926 var res;
52927 if (a < 0) {
52928 res = [-a, -lastx, -lasty];
52929 }
52930 else {
52931 res = [a, a ? lastx : 0, lasty];
52932 }
52933 return (config.matrix === 'Array') ? res : matrix(res);
52934 }
52935
52936 /**
52937 * Calculate xgcd for two BigNumbers
52938 * @param {BigNumber} a
52939 * @param {BigNumber} b
52940 * @return {BigNumber[]} result
52941 * @private
52942 */
52943 function _xgcdBigNumber(a, b) {
52944 // source: http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
52945 var t, // used to swap two variables
52946 q, // quotient
52947 r, // remainder
52948 zero = new type.BigNumber(0),
52949 one = new type.BigNumber(1),
52950 x = zero,
52951 lastx = one,
52952 y = one,
52953 lasty = zero;
52954
52955 if (!a.isInt() || !b.isInt()) {
52956 throw new Error('Parameters in function xgcd must be integer numbers');
52957 }
52958
52959 while (!b.isZero()) {
52960 q = a.div(b).floor();
52961 r = a.mod(b);
52962
52963 t = x;
52964 x = lastx.minus(q.times(x));
52965 lastx = t;
52966
52967 t = y;
52968 y = lasty.minus(q.times(y));
52969 lasty = t;
52970
52971 a = b;
52972 b = r;
52973 }
52974
52975 var res;
52976 if (a.lt(zero)) {
52977 res = [a.neg(), lastx.neg(), lasty.neg()];
52978 }
52979 else {
52980 res = [a, !a.isZero() ? lastx : 0, lasty];
52981 }
52982 return (config.matrix === 'Array') ? res : matrix(res);
52983 }
52984}
52985
52986exports.name = 'xgcd';
52987exports.factory = factory;
52988
52989
52990/***/ }),
52991/* 447 */
52992/***/ (function(module, exports, __webpack_require__) {
52993
52994module.exports = [
52995 __webpack_require__(448),
52996 __webpack_require__(450),
52997 __webpack_require__(451),
52998 __webpack_require__(453),
52999 __webpack_require__(455),
53000 __webpack_require__(457),
53001 __webpack_require__(459)
53002];
53003
53004
53005/***/ }),
53006/* 448 */
53007/***/ (function(module, exports, __webpack_require__) {
53008
53009"use strict";
53010
53011
53012var isInteger = __webpack_require__(3).isInteger;
53013var bigBitAnd = __webpack_require__(449);
53014
53015function factory (type, config, load, typed) {
53016 var latex = __webpack_require__(4);
53017
53018 var matrix = load(__webpack_require__(0));
53019
53020 var algorithm02 = load(__webpack_require__(24));
53021 var algorithm06 = load(__webpack_require__(68));
53022 var algorithm11 = load(__webpack_require__(19));
53023 var algorithm13 = load(__webpack_require__(8));
53024 var algorithm14 = load(__webpack_require__(6));
53025
53026 /**
53027 * Bitwise AND two values, `x & y`.
53028 * For matrices, the function is evaluated element wise.
53029 *
53030 * Syntax:
53031 *
53032 * math.bitAnd(x, y)
53033 *
53034 * Examples:
53035 *
53036 * math.bitAnd(53, 131); // returns number 1
53037 *
53038 * math.bitAnd([1, 12, 31], 42); // returns Array [0, 8, 10]
53039 *
53040 * See also:
53041 *
53042 * bitNot, bitOr, bitXor, leftShift, rightArithShift, rightLogShift
53043 *
53044 * @param {number | BigNumber | Array | Matrix} x First value to and
53045 * @param {number | BigNumber | Array | Matrix} y Second value to and
53046 * @return {number | BigNumber | Array | Matrix} AND of `x` and `y`
53047 */
53048 var bitAnd = typed('bitAnd', {
53049
53050 'number, number': function (x, y) {
53051 if (!isInteger(x) || !isInteger(y)) {
53052 throw new Error('Integers expected in function bitAnd');
53053 }
53054
53055 return x & y;
53056 },
53057
53058 'BigNumber, BigNumber': bigBitAnd,
53059
53060 'Matrix, Matrix': function (x, y) {
53061 // result
53062 var c;
53063
53064 // process matrix storage
53065 switch (x.storage()) {
53066 case 'sparse':
53067 switch (y.storage()) {
53068 case 'sparse':
53069 // sparse & sparse
53070 c = algorithm06(x, y, bitAnd, false);
53071 break;
53072 default:
53073 // sparse & dense
53074 c = algorithm02(y, x, bitAnd, true);
53075 break;
53076 }
53077 break;
53078 default:
53079 switch (y.storage()) {
53080 case 'sparse':
53081 // dense & sparse
53082 c = algorithm02(x, y, bitAnd, false);
53083 break;
53084 default:
53085 // dense & dense
53086 c = algorithm13(x, y, bitAnd);
53087 break;
53088 }
53089 break;
53090 }
53091 return c;
53092 },
53093
53094 'Array, Array': function (x, y) {
53095 // use matrix implementation
53096 return bitAnd(matrix(x), matrix(y)).valueOf();
53097 },
53098
53099 'Array, Matrix': function (x, y) {
53100 // use matrix implementation
53101 return bitAnd(matrix(x), y);
53102 },
53103
53104 'Matrix, Array': function (x, y) {
53105 // use matrix implementation
53106 return bitAnd(x, matrix(y));
53107 },
53108
53109 'Matrix, any': function (x, y) {
53110 // result
53111 var c;
53112 // check storage format
53113 switch (x.storage()) {
53114 case 'sparse':
53115 c = algorithm11(x, y, bitAnd, false);
53116 break;
53117 default:
53118 c = algorithm14(x, y, bitAnd, false);
53119 break;
53120 }
53121 return c;
53122 },
53123
53124 'any, Matrix': function (x, y) {
53125 // result
53126 var c;
53127 // check storage format
53128 switch (y.storage()) {
53129 case 'sparse':
53130 c = algorithm11(y, x, bitAnd, true);
53131 break;
53132 default:
53133 c = algorithm14(y, x, bitAnd, true);
53134 break;
53135 }
53136 return c;
53137 },
53138
53139 'Array, any': function (x, y) {
53140 // use matrix implementation
53141 return algorithm14(matrix(x), y, bitAnd, false).valueOf();
53142 },
53143
53144 'any, Array': function (x, y) {
53145 // use matrix implementation
53146 return algorithm14(matrix(y), x, bitAnd, true).valueOf();
53147 }
53148 });
53149
53150 bitAnd.toTex = {
53151 2: '\\left(${args[0]}' + latex.operators['bitAnd'] + '${args[1]}\\right)'
53152 };
53153
53154 return bitAnd;
53155}
53156
53157exports.name = 'bitAnd';
53158exports.factory = factory;
53159
53160
53161/***/ }),
53162/* 449 */
53163/***/ (function(module, exports, __webpack_require__) {
53164
53165var bitwise = __webpack_require__(86);
53166
53167/**
53168 * Bitwise and for Bignumbers
53169 *
53170 * Special Cases:
53171 * N & n = N
53172 * n & 0 = 0
53173 * n & -1 = n
53174 * n & n = n
53175 * I & I = I
53176 * -I & -I = -I
53177 * I & -I = 0
53178 * I & n = n
53179 * I & -n = I
53180 * -I & n = 0
53181 * -I & -n = -I
53182 *
53183 * @param {BigNumber} x
53184 * @param {BigNumber} y
53185 * @return {BigNumber} Result of `x` & `y`, is fully precise
53186 * @private
53187 */
53188module.exports = function bitAnd(x, y) {
53189 if ((x.isFinite() && !x.isInteger()) || (y.isFinite() && !y.isInteger())) {
53190 throw new Error('Integers expected in function bitAnd');
53191 }
53192
53193 var BigNumber = x.constructor;
53194 if (x.isNaN() || y.isNaN()) {
53195 return new BigNumber(NaN);
53196 }
53197
53198 if (x.isZero() || y.eq(-1) || x.eq(y)) {
53199 return x;
53200 }
53201 if (y.isZero() || x.eq(-1)) {
53202 return y;
53203 }
53204
53205 if (!x.isFinite() || !y.isFinite()) {
53206 if (!x.isFinite() && !y.isFinite()) {
53207 if (x.isNegative() == y.isNegative()) {
53208 return x;
53209 }
53210 return new BigNumber(0);
53211 }
53212 if (!x.isFinite()) {
53213 if (y.isNegative()) {
53214 return x;
53215 }
53216 if (x.isNegative()) {
53217 return new BigNumber(0);
53218 }
53219 return y;
53220 }
53221 if (!y.isFinite()) {
53222 if (x.isNegative()) {
53223 return y;
53224 }
53225 if (y.isNegative()) {
53226 return new BigNumber(0);
53227 }
53228 return x;
53229 }
53230 }
53231 return bitwise(x, y, function (a, b) { return a & b });
53232};
53233
53234
53235/***/ }),
53236/* 450 */
53237/***/ (function(module, exports, __webpack_require__) {
53238
53239"use strict";
53240
53241
53242var deepMap = __webpack_require__(1);
53243var bigBitNot = __webpack_require__(87);
53244var isInteger = __webpack_require__(3).isInteger;
53245
53246function factory (type, config, load, typed) {
53247 var latex = __webpack_require__(4);
53248
53249 /**
53250 * Bitwise NOT value, `~x`.
53251 * For matrices, the function is evaluated element wise.
53252 * For units, the function is evaluated on the best prefix base.
53253 *
53254 * Syntax:
53255 *
53256 * math.bitNot(x)
53257 *
53258 * Examples:
53259 *
53260 * math.bitNot(1); // returns number -2
53261 *
53262 * math.bitNot([2, -3, 4]); // returns Array [-3, 2, 5]
53263 *
53264 * See also:
53265 *
53266 * bitAnd, bitOr, bitXor, leftShift, rightArithShift, rightLogShift
53267 *
53268 * @param {number | BigNumber | Array | Matrix} x Value to not
53269 * @return {number | BigNumber | Array | Matrix} NOT of `x`
53270 */
53271 var bitNot = typed('bitNot', {
53272 'number': function (x) {
53273 if (!isInteger(x)) {
53274 throw new Error('Integer expected in function bitNot');
53275 }
53276
53277 return ~x;
53278 },
53279
53280 'BigNumber': bigBitNot,
53281
53282 'Array | Matrix': function (x) {
53283 return deepMap(x, bitNot);
53284 }
53285 });
53286
53287 bitNot.toTex = {
53288 1: latex.operators['bitNot'] + '\\left(${args[0]}\\right)'
53289 };
53290
53291 return bitNot;
53292}
53293
53294exports.name = 'bitNot';
53295exports.factory = factory;
53296
53297
53298/***/ }),
53299/* 451 */
53300/***/ (function(module, exports, __webpack_require__) {
53301
53302"use strict";
53303
53304
53305var isInteger = __webpack_require__(3).isInteger;
53306var bigBitOr = __webpack_require__(452);
53307
53308function factory (type, config, load, typed) {
53309 var latex = __webpack_require__(4);
53310
53311 var matrix = load(__webpack_require__(0));
53312
53313 var algorithm01 = load(__webpack_require__(33));
53314 var algorithm04 = load(__webpack_require__(73));
53315 var algorithm10 = load(__webpack_require__(38));
53316 var algorithm13 = load(__webpack_require__(8));
53317 var algorithm14 = load(__webpack_require__(6));
53318
53319 /**
53320 * Bitwise OR two values, `x | y`.
53321 * For matrices, the function is evaluated element wise.
53322 * For units, the function is evaluated on the lowest print base.
53323 *
53324 * Syntax:
53325 *
53326 * math.bitOr(x, y)
53327 *
53328 * Examples:
53329 *
53330 * math.bitOr(1, 2); // returns number 3
53331 *
53332 * math.bitOr([1, 2, 3], 4); // returns Array [5, 6, 7]
53333 *
53334 * See also:
53335 *
53336 * bitAnd, bitNot, bitXor, leftShift, rightArithShift, rightLogShift
53337 *
53338 * @param {number | BigNumber | Array | Matrix} x First value to or
53339 * @param {number | BigNumber | Array | Matrix} y Second value to or
53340 * @return {number | BigNumber | Array | Matrix} OR of `x` and `y`
53341 */
53342 var bitOr = typed('bitOr', {
53343
53344 'number, number': function (x, y) {
53345 if (!isInteger(x) || !isInteger(y)) {
53346 throw new Error('Integers expected in function bitOr');
53347 }
53348
53349 return x | y;
53350 },
53351
53352 'BigNumber, BigNumber': bigBitOr,
53353
53354 'Matrix, Matrix': function (x, y) {
53355 // result
53356 var c;
53357
53358 // process matrix storage
53359 switch (x.storage()) {
53360 case 'sparse':
53361 switch (y.storage()) {
53362 case 'sparse':
53363 // sparse + sparse
53364 c = algorithm04(x, y, bitOr);
53365 break;
53366 default:
53367 // sparse + dense
53368 c = algorithm01(y, x, bitOr, true);
53369 break;
53370 }
53371 break;
53372 default:
53373 switch (y.storage()) {
53374 case 'sparse':
53375 // dense + sparse
53376 c = algorithm01(x, y, bitOr, false);
53377 break;
53378 default:
53379 c = algorithm13(x, y, bitOr);
53380 break;
53381 }
53382 break;
53383 }
53384 return c;
53385 },
53386
53387 'Array, Array': function (x, y) {
53388 // use matrix implementation
53389 return bitOr(matrix(x), matrix(y)).valueOf();
53390 },
53391
53392 'Array, Matrix': function (x, y) {
53393 // use matrix implementation
53394 return bitOr(matrix(x), y);
53395 },
53396
53397 'Matrix, Array': function (x, y) {
53398 // use matrix implementation
53399 return bitOr(x, matrix(y));
53400 },
53401
53402 'Matrix, any': function (x, y) {
53403 // result
53404 var c;
53405 // check storage format
53406 switch (x.storage()) {
53407 case 'sparse':
53408 c = algorithm10(x, y, bitOr, false);
53409 break;
53410 default:
53411 c = algorithm14(x, y, bitOr, false);
53412 break;
53413 }
53414 return c;
53415 },
53416
53417 'any, Matrix': function (x, y) {
53418 // result
53419 var c;
53420 // check storage format
53421 switch (y.storage()) {
53422 case 'sparse':
53423 c = algorithm10(y, x, bitOr, true);
53424 break;
53425 default:
53426 c = algorithm14(y, x, bitOr, true);
53427 break;
53428 }
53429 return c;
53430 },
53431
53432 'Array, any': function (x, y) {
53433 // use matrix implementation
53434 return algorithm14(matrix(x), y, bitOr, false).valueOf();
53435 },
53436
53437 'any, Array': function (x, y) {
53438 // use matrix implementation
53439 return algorithm14(matrix(y), x, bitOr, true).valueOf();
53440 }
53441 });
53442
53443 bitOr.toTex = {
53444 2: '\\left(${args[0]}' + latex.operators['bitOr'] + '${args[1]}\\right)'
53445 };
53446
53447 return bitOr;
53448}
53449
53450exports.name = 'bitOr';
53451exports.factory = factory;
53452
53453
53454/***/ }),
53455/* 452 */
53456/***/ (function(module, exports, __webpack_require__) {
53457
53458var bitwise = __webpack_require__(86);
53459
53460/**
53461 * Bitwise OR for BigNumbers
53462 *
53463 * Special Cases:
53464 * N | n = N
53465 * n | 0 = n
53466 * n | -1 = -1
53467 * n | n = n
53468 * I | I = I
53469 * -I | -I = -I
53470 * I | -n = -1
53471 * I | -I = -1
53472 * I | n = I
53473 * -I | n = -I
53474 * -I | -n = -n
53475 *
53476 * @param {BigNumber} x
53477 * @param {BigNumber} y
53478 * @return {BigNumber} Result of `x` | `y`, fully precise
53479 */
53480module.exports = function bitOr (x, y) {
53481 if ((x.isFinite() && !x.isInteger()) || (y.isFinite() && !y.isInteger())) {
53482 throw new Error('Integers expected in function bitOr');
53483 }
53484
53485 var BigNumber = x.constructor;
53486 if (x.isNaN() || y.isNaN()) {
53487 return new BigNumber(NaN);
53488 }
53489
53490 var negOne = new BigNumber(-1);
53491 if (x.isZero() || y.eq(negOne) || x.eq(y)) {
53492 return y;
53493 }
53494 if (y.isZero() || x.eq(negOne)) {
53495 return x;
53496 }
53497
53498 if (!x.isFinite() || !y.isFinite()) {
53499 if ((!x.isFinite() && !x.isNegative() && y.isNegative()) ||
53500 (x.isNegative() && !y.isNegative() && !y.isFinite())) {
53501 return negOne;
53502 }
53503 if (x.isNegative() && y.isNegative()) {
53504 return x.isFinite() ? x : y;
53505 }
53506 return x.isFinite() ? y : x;
53507 }
53508
53509 return bitwise(x, y, function (a, b) { return a | b });
53510};
53511
53512
53513/***/ }),
53514/* 453 */
53515/***/ (function(module, exports, __webpack_require__) {
53516
53517"use strict";
53518
53519
53520var isInteger = __webpack_require__(3).isInteger;
53521var bigBitXor = __webpack_require__(454);
53522
53523function factory (type, config, load, typed) {
53524 var latex = __webpack_require__(4);
53525
53526 var matrix = load(__webpack_require__(0));
53527
53528 var algorithm03 = load(__webpack_require__(17));
53529 var algorithm07 = load(__webpack_require__(26));
53530 var algorithm12 = load(__webpack_require__(18));
53531 var algorithm13 = load(__webpack_require__(8));
53532 var algorithm14 = load(__webpack_require__(6));
53533
53534 /**
53535 * Bitwise XOR two values, `x ^ y`.
53536 * For matrices, the function is evaluated element wise.
53537 *
53538 * Syntax:
53539 *
53540 * math.bitXor(x, y)
53541 *
53542 * Examples:
53543 *
53544 * math.bitXor(1, 2); // returns number 3
53545 *
53546 * math.bitXor([2, 3, 4], 4); // returns Array [6, 7, 0]
53547 *
53548 * See also:
53549 *
53550 * bitAnd, bitNot, bitOr, leftShift, rightArithShift, rightLogShift
53551 *
53552 * @param {number | BigNumber | Array | Matrix} x First value to xor
53553 * @param {number | BigNumber | Array | Matrix} y Second value to xor
53554 * @return {number | BigNumber | Array | Matrix} XOR of `x` and `y`
53555 */
53556 var bitXor = typed('bitXor', {
53557
53558 'number, number': function (x, y) {
53559 if (!isInteger(x) || !isInteger(y)) {
53560 throw new Error('Integers expected in function bitXor');
53561 }
53562
53563 return x ^ y;
53564 },
53565
53566 'BigNumber, BigNumber': bigBitXor,
53567
53568 'Matrix, Matrix': function (x, y) {
53569 // result
53570 var c;
53571
53572 // process matrix storage
53573 switch (x.storage()) {
53574 case 'sparse':
53575 switch (y.storage()) {
53576 case 'sparse':
53577 // sparse + sparse
53578 c = algorithm07(x, y, bitXor);
53579 break;
53580 default:
53581 // sparse + dense
53582 c = algorithm03(y, x, bitXor, true);
53583 break;
53584 }
53585 break;
53586 default:
53587 switch (y.storage()) {
53588 case 'sparse':
53589 // dense + sparse
53590 c = algorithm03(x, y, bitXor, false);
53591 break;
53592 default:
53593 // dense + dense
53594 c = algorithm13(x, y, bitXor);
53595 break;
53596 }
53597 break;
53598 }
53599 return c;
53600 },
53601
53602 'Array, Array': function (x, y) {
53603 // use matrix implementation
53604 return bitXor(matrix(x), matrix(y)).valueOf();
53605 },
53606
53607 'Array, Matrix': function (x, y) {
53608 // use matrix implementation
53609 return bitXor(matrix(x), y);
53610 },
53611
53612 'Matrix, Array': function (x, y) {
53613 // use matrix implementation
53614 return bitXor(x, matrix(y));
53615 },
53616
53617 'Matrix, any': function (x, y) {
53618 // result
53619 var c;
53620 // check storage format
53621 switch (x.storage()) {
53622 case 'sparse':
53623 c = algorithm12(x, y, bitXor, false);
53624 break;
53625 default:
53626 c = algorithm14(x, y, bitXor, false);
53627 break;
53628 }
53629 return c;
53630 },
53631
53632 'any, Matrix': function (x, y) {
53633 // result
53634 var c;
53635 // check storage format
53636 switch (y.storage()) {
53637 case 'sparse':
53638 c = algorithm12(y, x, bitXor, true);
53639 break;
53640 default:
53641 c = algorithm14(y, x, bitXor, true);
53642 break;
53643 }
53644 return c;
53645 },
53646
53647 'Array, any': function (x, y) {
53648 // use matrix implementation
53649 return algorithm14(matrix(x), y, bitXor, false).valueOf();
53650 },
53651
53652 'any, Array': function (x, y) {
53653 // use matrix implementation
53654 return algorithm14(matrix(y), x, bitXor, true).valueOf();
53655 }
53656 });
53657
53658 bitXor.toTex = {
53659 2: '\\left(${args[0]}' + latex.operators['bitXor'] + '${args[1]}\\right)'
53660 };
53661
53662 return bitXor;
53663}
53664
53665exports.name = 'bitXor';
53666exports.factory = factory;
53667
53668
53669/***/ }),
53670/* 454 */
53671/***/ (function(module, exports, __webpack_require__) {
53672
53673var bitwise = __webpack_require__(86);
53674var bitNot = __webpack_require__(87);
53675
53676/**
53677 * Bitwise XOR for BigNumbers
53678 *
53679 * Special Cases:
53680 * N ^ n = N
53681 * n ^ 0 = n
53682 * n ^ n = 0
53683 * n ^ -1 = ~n
53684 * I ^ n = I
53685 * I ^ -n = -I
53686 * I ^ -I = -1
53687 * -I ^ n = -I
53688 * -I ^ -n = I
53689 *
53690 * @param {BigNumber} x
53691 * @param {BigNumber} y
53692 * @return {BigNumber} Result of `x` ^ `y`, fully precise
53693 *
53694 */
53695module.exports = function bitXor(x, y) {
53696 if ((x.isFinite() && !x.isInteger()) || (y.isFinite() && !y.isInteger())) {
53697 throw new Error('Integers expected in function bitXor');
53698 }
53699
53700 var BigNumber = x.constructor;
53701 if (x.isNaN() || y.isNaN()) {
53702 return new BigNumber(NaN);
53703 }
53704 if (x.isZero()) {
53705 return y;
53706 }
53707 if (y.isZero()) {
53708 return x;
53709 }
53710
53711 if (x.eq(y)) {
53712 return new BigNumber(0);
53713 }
53714
53715 var negOne = new BigNumber(-1);
53716 if (x.eq(negOne)) {
53717 return bitNot(y);
53718 }
53719 if (y.eq(negOne)) {
53720 return bitNot(x);
53721 }
53722
53723 if (!x.isFinite() || !y.isFinite()) {
53724 if (!x.isFinite() && !y.isFinite()) {
53725 return negOne;
53726 }
53727 return new BigNumber(x.isNegative() == y.isNegative()
53728 ? Infinity
53729 : -Infinity);
53730 }
53731 return bitwise(x, y, function (a, b) { return a ^ b });
53732};
53733
53734
53735/***/ }),
53736/* 455 */
53737/***/ (function(module, exports, __webpack_require__) {
53738
53739"use strict";
53740
53741
53742var isInteger = __webpack_require__(3).isInteger;
53743var bigLeftShift = __webpack_require__(456);
53744
53745function factory (type, config, load, typed) {
53746 var latex = __webpack_require__(4);
53747
53748 var matrix = load(__webpack_require__(0));
53749 var equalScalar = load(__webpack_require__(10));
53750 var zeros = load(__webpack_require__(40));
53751
53752 var algorithm01 = load(__webpack_require__(33));
53753 var algorithm02 = load(__webpack_require__(24));
53754 var algorithm08 = load(__webpack_require__(88));
53755 var algorithm10 = load(__webpack_require__(38));
53756 var algorithm11 = load(__webpack_require__(19));
53757 var algorithm13 = load(__webpack_require__(8));
53758 var algorithm14 = load(__webpack_require__(6));
53759
53760 /**
53761 * Bitwise left logical shift of a value x by y number of bits, `x << y`.
53762 * For matrices, the function is evaluated element wise.
53763 * For units, the function is evaluated on the best prefix base.
53764 *
53765 * Syntax:
53766 *
53767 * math.leftShift(x, y)
53768 *
53769 * Examples:
53770 *
53771 * math.leftShift(1, 2); // returns number 4
53772 *
53773 * math.leftShift([1, 2, 3], 4); // returns Array [16, 32, 64]
53774 *
53775 * See also:
53776 *
53777 * leftShift, bitNot, bitOr, bitXor, rightArithShift, rightLogShift
53778 *
53779 * @param {number | BigNumber | Array | Matrix} x Value to be shifted
53780 * @param {number | BigNumber} y Amount of shifts
53781 * @return {number | BigNumber | Array | Matrix} `x` shifted left `y` times
53782 */
53783 var leftShift = typed('leftShift', {
53784
53785 'number, number': function (x, y) {
53786 if (!isInteger(x) || !isInteger(y)) {
53787 throw new Error('Integers expected in function leftShift');
53788 }
53789
53790 return x << y;
53791 },
53792
53793 'BigNumber, BigNumber': bigLeftShift,
53794
53795 'Matrix, Matrix': function (x, y) {
53796 // result
53797 var c;
53798
53799 // process matrix storage
53800 switch (x.storage()) {
53801 case 'sparse':
53802 switch (y.storage()) {
53803 case 'sparse':
53804 // sparse & sparse
53805 c = algorithm08(x, y, leftShift, false);
53806 break;
53807 default:
53808 // sparse & dense
53809 c = algorithm02(y, x, leftShift, true);
53810 break;
53811 }
53812 break;
53813 default:
53814 switch (y.storage()) {
53815 case 'sparse':
53816 // dense & sparse
53817 c = algorithm01(x, y, leftShift, false);
53818 break;
53819 default:
53820 // dense & dense
53821 c = algorithm13(x, y, leftShift);
53822 break;
53823 }
53824 break;
53825 }
53826 return c;
53827 },
53828
53829 'Array, Array': function (x, y) {
53830 // use matrix implementation
53831 return leftShift(matrix(x), matrix(y)).valueOf();
53832 },
53833
53834 'Array, Matrix': function (x, y) {
53835 // use matrix implementation
53836 return leftShift(matrix(x), y);
53837 },
53838
53839 'Matrix, Array': function (x, y) {
53840 // use matrix implementation
53841 return leftShift(x, matrix(y));
53842 },
53843
53844 'Matrix, number | BigNumber': function (x, y) {
53845 // check scalar
53846 if (!equalScalar(y, 0)) {
53847 // result
53848 var c;
53849 // check storage format
53850 switch (x.storage()) {
53851 case 'sparse':
53852 c = algorithm11(x, y, leftShift, false);
53853 break;
53854 default:
53855 c = algorithm14(x, y, leftShift, false);
53856 break;
53857 }
53858 return c;
53859 }
53860 return x.clone();
53861 },
53862
53863 'number | BigNumber, Matrix': function (x, y) {
53864 // check scalar
53865 if (!equalScalar(x, 0)) {
53866 // result
53867 var c;
53868 // check storage format
53869 switch (y.storage()) {
53870 case 'sparse':
53871 c = algorithm10(y, x, leftShift, true);
53872 break;
53873 default:
53874 c = algorithm14(y, x, leftShift, true);
53875 break;
53876 }
53877 return c;
53878 }
53879 return zeros(y.size(), y.storage());
53880 },
53881
53882 'Array, number | BigNumber': function (x, y) {
53883 // use matrix implementation
53884 return leftShift(matrix(x), y).valueOf();
53885 },
53886
53887 'number | BigNumber, Array': function (x, y) {
53888 // use matrix implementation
53889 return leftShift(x, matrix(y)).valueOf();
53890 }
53891 });
53892
53893 leftShift.toTex = {
53894 2: '\\left(${args[0]}' + latex.operators['leftShift'] + '${args[1]}\\right)'
53895 };
53896
53897 return leftShift;
53898}
53899
53900exports.name = 'leftShift';
53901exports.factory = factory;
53902
53903
53904/***/ }),
53905/* 456 */
53906/***/ (function(module, exports) {
53907
53908
53909/**
53910 * Bitwise left shift
53911 *
53912 * Special Cases:
53913 * n << -n = N
53914 * n << N = N
53915 * N << n = N
53916 * n << 0 = n
53917 * 0 << n = 0
53918 * I << I = N
53919 * I << n = I
53920 * n << I = I
53921 *
53922 * @param {BigNumber} x
53923 * @param {BigNumber} y
53924 * @return {BigNumber} Result of `x` << `y`
53925 *
53926 */
53927module.exports = function leftShift (x, y) {
53928 if ((x.isFinite() && !x.isInteger()) || (y.isFinite() && !y.isInteger())) {
53929 throw new Error('Integers expected in function leftShift');
53930 }
53931
53932 var BigNumber = x.constructor;
53933 if (x.isNaN() || y.isNaN() || (y.isNegative() && !y.isZero())) {
53934 return new BigNumber(NaN);
53935 }
53936 if (x.isZero() || y.isZero()) {
53937 return x;
53938 }
53939 if (!x.isFinite() && !y.isFinite()) {
53940 return new BigNumber(NaN);
53941 }
53942
53943 // Math.pow(2, y) is fully precise for y < 55, and fast
53944 if (y.lt(55)) {
53945 return x.times(Math.pow(2, y.toNumber()) + '');
53946 }
53947 return x.times(new BigNumber(2).pow(y));
53948};
53949
53950
53951/***/ }),
53952/* 457 */
53953/***/ (function(module, exports, __webpack_require__) {
53954
53955"use strict";
53956
53957
53958var isInteger = __webpack_require__(3).isInteger;
53959var bigRightArithShift = __webpack_require__(458);
53960
53961function factory (type, config, load, typed) {
53962 var latex = __webpack_require__(4);
53963
53964 var matrix = load(__webpack_require__(0));
53965 var equalScalar = load(__webpack_require__(10));
53966 var zeros = load(__webpack_require__(40));
53967
53968 var algorithm01 = load(__webpack_require__(33));
53969 var algorithm02 = load(__webpack_require__(24));
53970 var algorithm08 = load(__webpack_require__(88));
53971 var algorithm10 = load(__webpack_require__(38));
53972 var algorithm11 = load(__webpack_require__(19));
53973 var algorithm13 = load(__webpack_require__(8));
53974 var algorithm14 = load(__webpack_require__(6));
53975
53976 /**
53977 * Bitwise right arithmetic shift of a value x by y number of bits, `x >> y`.
53978 * For matrices, the function is evaluated element wise.
53979 * For units, the function is evaluated on the best prefix base.
53980 *
53981 * Syntax:
53982 *
53983 * math.rightArithShift(x, y)
53984 *
53985 * Examples:
53986 *
53987 * math.rightArithShift(4, 2); // returns number 1
53988 *
53989 * math.rightArithShift([16, -32, 64], 4); // returns Array [1, -2, 3]
53990 *
53991 * See also:
53992 *
53993 * bitAnd, bitNot, bitOr, bitXor, rightArithShift, rightLogShift
53994 *
53995 * @param {number | BigNumber | Array | Matrix} x Value to be shifted
53996 * @param {number | BigNumber} y Amount of shifts
53997 * @return {number | BigNumber | Array | Matrix} `x` sign-filled shifted right `y` times
53998 */
53999 var rightArithShift = typed('rightArithShift', {
54000
54001 'number, number': function (x, y) {
54002 if (!isInteger(x) || !isInteger(y)) {
54003 throw new Error('Integers expected in function rightArithShift');
54004 }
54005
54006 return x >> y;
54007 },
54008
54009 'BigNumber, BigNumber': bigRightArithShift,
54010
54011 'Matrix, Matrix': function (x, y) {
54012 // result
54013 var c;
54014
54015 // process matrix storage
54016 switch (x.storage()) {
54017 case 'sparse':
54018 switch (y.storage()) {
54019 case 'sparse':
54020 // sparse & sparse
54021 c = algorithm08(x, y, rightArithShift, false);
54022 break;
54023 default:
54024 // sparse & dense
54025 c = algorithm02(y, x, rightArithShift, true);
54026 break;
54027 }
54028 break;
54029 default:
54030 switch (y.storage()) {
54031 case 'sparse':
54032 // dense & sparse
54033 c = algorithm01(x, y, rightArithShift, false);
54034 break;
54035 default:
54036 // dense & dense
54037 c = algorithm13(x, y, rightArithShift);
54038 break;
54039 }
54040 break;
54041 }
54042 return c;
54043 },
54044
54045 'Array, Array': function (x, y) {
54046 // use matrix implementation
54047 return rightArithShift(matrix(x), matrix(y)).valueOf();
54048 },
54049
54050 'Array, Matrix': function (x, y) {
54051 // use matrix implementation
54052 return rightArithShift(matrix(x), y);
54053 },
54054
54055 'Matrix, Array': function (x, y) {
54056 // use matrix implementation
54057 return rightArithShift(x, matrix(y));
54058 },
54059
54060 'Matrix, number | BigNumber': function (x, y) {
54061 // check scalar
54062 if (!equalScalar(y, 0)) {
54063 // result
54064 var c;
54065 // check storage format
54066 switch (x.storage()) {
54067 case 'sparse':
54068 c = algorithm11(x, y, rightArithShift, false);
54069 break;
54070 default:
54071 c = algorithm14(x, y, rightArithShift, false);
54072 break;
54073 }
54074 return c;
54075 }
54076 return x.clone();
54077 },
54078
54079 'number | BigNumber, Matrix': function (x, y) {
54080 // check scalar
54081 if (!equalScalar(x, 0)) {
54082 // result
54083 var c;
54084 // check storage format
54085 switch (y.storage()) {
54086 case 'sparse':
54087 c = algorithm10(y, x, rightArithShift, true);
54088 break;
54089 default:
54090 c = algorithm14(y, x, rightArithShift, true);
54091 break;
54092 }
54093 return c;
54094 }
54095 return zeros(y.size(), y.storage());
54096 },
54097
54098 'Array, number | BigNumber': function (x, y) {
54099 // use matrix implementation
54100 return rightArithShift(matrix(x), y).valueOf();
54101 },
54102
54103 'number | BigNumber, Array': function (x, y) {
54104 // use matrix implementation
54105 return rightArithShift(x, matrix(y)).valueOf();
54106 }
54107 });
54108
54109 rightArithShift.toTex = {
54110 2: '\\left(${args[0]}' + latex.operators['rightArithShift'] + '${args[1]}\\right)'
54111 };
54112
54113 return rightArithShift;
54114}
54115
54116exports.name = 'rightArithShift';
54117exports.factory = factory;
54118
54119
54120/***/ }),
54121/* 458 */
54122/***/ (function(module, exports) {
54123
54124/*
54125 * Special Cases:
54126 * n >> -n = N
54127 * n >> N = N
54128 * N >> n = N
54129 * I >> I = N
54130 * n >> 0 = n
54131 * I >> n = I
54132 * -I >> n = -I
54133 * -I >> I = -I
54134 * n >> I = I
54135 * -n >> I = -1
54136 * 0 >> n = 0
54137 *
54138 * @param {BigNumber} value
54139 * @param {BigNumber} value
54140 * @return {BigNumber} Result of `x` >> `y`
54141 *
54142 */
54143module.exports = function rightArithShift (x, y) {
54144 if ((x.isFinite() && !x.isInteger()) || (y.isFinite() && !y.isInteger())) {
54145 throw new Error('Integers expected in function rightArithShift');
54146 }
54147
54148 var BigNumber = x.constructor;
54149 if (x.isNaN() || y.isNaN() || (y.isNegative() && !y.isZero())) {
54150 return new BigNumber(NaN);
54151 }
54152 if (x.isZero() || y.isZero()) {
54153 return x;
54154 }
54155 if (!y.isFinite()) {
54156 if (x.isNegative()) {
54157 return new BigNumber(-1);
54158 }
54159 if (!x.isFinite()) {
54160 return new BigNumber(NaN);
54161 }
54162 return new BigNumber(0);
54163 }
54164
54165 // Math.pow(2, y) is fully precise for y < 55, and fast
54166 if (y.lt(55)) {
54167 return x.div(Math.pow(2, y.toNumber()) + '').floor();
54168 }
54169 return x.div(new BigNumber(2).pow(y)).floor();
54170};
54171
54172
54173/***/ }),
54174/* 459 */
54175/***/ (function(module, exports, __webpack_require__) {
54176
54177"use strict";
54178
54179
54180var isInteger = __webpack_require__(3).isInteger;
54181
54182function factory (type, config, load, typed) {
54183 var latex = __webpack_require__(4);
54184
54185 var matrix = load(__webpack_require__(0));
54186 var equalScalar = load(__webpack_require__(10));
54187 var zeros = load(__webpack_require__(40));
54188
54189 var algorithm01 = load(__webpack_require__(33));
54190 var algorithm02 = load(__webpack_require__(24));
54191 var algorithm08 = load(__webpack_require__(88));
54192 var algorithm10 = load(__webpack_require__(38));
54193 var algorithm11 = load(__webpack_require__(19));
54194 var algorithm13 = load(__webpack_require__(8));
54195 var algorithm14 = load(__webpack_require__(6));
54196
54197 /**
54198 * Bitwise right logical shift of value x by y number of bits, `x >>> y`.
54199 * For matrices, the function is evaluated element wise.
54200 * For units, the function is evaluated on the best prefix base.
54201 *
54202 * Syntax:
54203 *
54204 * math.rightLogShift(x, y)
54205 *
54206 * Examples:
54207 *
54208 * math.rightLogShift(4, 2); // returns number 1
54209 *
54210 * math.rightLogShift([16, -32, 64], 4); // returns Array [1, 2, 3]
54211 *
54212 * See also:
54213 *
54214 * bitAnd, bitNot, bitOr, bitXor, leftShift, rightLogShift
54215 *
54216 * @param {number | Array | Matrix} x Value to be shifted
54217 * @param {number} y Amount of shifts
54218 * @return {number | Array | Matrix} `x` zero-filled shifted right `y` times
54219 */
54220
54221 var rightLogShift = typed('rightLogShift', {
54222
54223 'number, number': function (x, y) {
54224 if (!isInteger(x) || !isInteger(y)) {
54225 throw new Error('Integers expected in function rightLogShift');
54226 }
54227
54228 return x >>> y;
54229 },
54230
54231 // 'BigNumber, BigNumber': ..., // TODO: implement BigNumber support for rightLogShift
54232
54233 'Matrix, Matrix': function (x, y) {
54234 // result
54235 var c;
54236
54237 // process matrix storage
54238 switch (x.storage()) {
54239 case 'sparse':
54240 switch (y.storage()) {
54241 case 'sparse':
54242 // sparse & sparse
54243 c = algorithm08(x, y, rightLogShift, false);
54244 break;
54245 default:
54246 // sparse & dense
54247 c = algorithm02(y, x, rightLogShift, true);
54248 break;
54249 }
54250 break;
54251 default:
54252 switch (y.storage()) {
54253 case 'sparse':
54254 // dense & sparse
54255 c = algorithm01(x, y, rightLogShift, false);
54256 break;
54257 default:
54258 // dense & dense
54259 c = algorithm13(x, y, rightLogShift);
54260 break;
54261 }
54262 break;
54263 }
54264 return c;
54265 },
54266
54267 'Array, Array': function (x, y) {
54268 // use matrix implementation
54269 return rightLogShift(matrix(x), matrix(y)).valueOf();
54270 },
54271
54272 'Array, Matrix': function (x, y) {
54273 // use matrix implementation
54274 return rightLogShift(matrix(x), y);
54275 },
54276
54277 'Matrix, Array': function (x, y) {
54278 // use matrix implementation
54279 return rightLogShift(x, matrix(y));
54280 },
54281
54282 'Matrix, number | BigNumber': function (x, y) {
54283 // check scalar
54284 if (!equalScalar(y, 0)) {
54285 // result
54286 var c;
54287 // check storage format
54288 switch (x.storage()) {
54289 case 'sparse':
54290 c = algorithm11(x, y, rightLogShift, false);
54291 break;
54292 default:
54293 c = algorithm14(x, y, rightLogShift, false);
54294 break;
54295 }
54296 return c;
54297 }
54298 return x.clone();
54299 },
54300
54301 'number | BigNumber, Matrix': function (x, y) {
54302 // check scalar
54303 if (!equalScalar(x, 0)) {
54304 // result
54305 var c;
54306 // check storage format
54307 switch (y.storage()) {
54308 case 'sparse':
54309 c = algorithm10(y, x, rightLogShift, true);
54310 break;
54311 default:
54312 c = algorithm14(y, x, rightLogShift, true);
54313 break;
54314 }
54315 return c;
54316 }
54317 return zeros(y.size(), y.storage());
54318 },
54319
54320 'Array, number | BigNumber': function (x, y) {
54321 // use matrix implementation
54322 return rightLogShift(matrix(x), y).valueOf();
54323 },
54324
54325 'number | BigNumber, Array': function (x, y) {
54326 // use matrix implementation
54327 return rightLogShift(x, matrix(y)).valueOf();
54328 }
54329 });
54330
54331 rightLogShift.toTex = {
54332 2: '\\left(${args[0]}' + latex.operators['rightLogShift'] + '${args[1]}\\right)'
54333 };
54334
54335 return rightLogShift;
54336}
54337
54338exports.name = 'rightLogShift';
54339exports.factory = factory;
54340
54341
54342/***/ }),
54343/* 460 */
54344/***/ (function(module, exports, __webpack_require__) {
54345
54346module.exports = [
54347 __webpack_require__(461),
54348 __webpack_require__(462),
54349 __webpack_require__(139),
54350 __webpack_require__(463)
54351];
54352
54353
54354/***/ }),
54355/* 461 */
54356/***/ (function(module, exports, __webpack_require__) {
54357
54358"use strict";
54359
54360
54361function factory (type, config, load, typed) {
54362 var add = load(__webpack_require__(20));
54363 var stirlingS2 = load(__webpack_require__(139));
54364 var isNegative = load(__webpack_require__(58));
54365 var isInteger = load(__webpack_require__(51));
54366
54367 /**
54368 * The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S.
54369 * bellNumbers only takes integer arguments.
54370 * The following condition must be enforced: n >= 0
54371 *
54372 * Syntax:
54373 *
54374 * math.bellNumbers(n)
54375 *
54376 * Examples:
54377 *
54378 * math.bellNumbers(3); // returns 5;
54379 * math.bellNumbers(8); // returns 4140;
54380 *
54381 * See also:
54382 *
54383 * stirlingS2
54384 *
54385 * @param {Number | BigNumber} n Total number of objects in the set
54386 * @return {Number | BigNumber} B(n)
54387 */
54388 var bellNumbers = typed('bellNumbers', {
54389 'number | BigNumber': function (n) {
54390
54391 if (!isInteger(n) || isNegative(n)) {
54392 throw new TypeError('Non-negative integer value expected in function bellNumbers');
54393 }
54394
54395 // Sum (k=0, n) S(n,k).
54396 var result = 0;
54397 for(var i = 0; i <= n; i++) {
54398 result = add(result, stirlingS2(n, i));
54399 }
54400
54401 return result;
54402 }
54403 });
54404
54405 bellNumbers.toTex = {1: '\\mathrm{B}_{${args[0]}}'};
54406
54407 return bellNumbers;
54408}
54409
54410exports.name = 'bellNumbers';
54411exports.factory = factory;
54412
54413
54414/***/ }),
54415/* 462 */
54416/***/ (function(module, exports, __webpack_require__) {
54417
54418"use strict";
54419
54420
54421function factory (type, config, load, typed) {
54422 var combinations = load(__webpack_require__(70));
54423 var add = load(__webpack_require__(16));
54424 var isPositive = load(__webpack_require__(57));
54425 var isInteger = load(__webpack_require__(51));
54426 var larger = load(__webpack_require__(34));
54427
54428 /**
54429 * The composition counts of n into k parts.
54430 *
54431 * composition only takes integer arguments.
54432 * The following condition must be enforced: k <= n.
54433 *
54434 * Syntax:
54435 *
54436 * math.composition(n, k)
54437 *
54438 * Examples:
54439 *
54440 * math.composition(5, 3); // returns 6
54441 *
54442 * See also:
54443 *
54444 * combinations
54445 *
54446 * @param {Number | BigNumber} n Total number of objects in the set
54447 * @param {Number | BigNumber} k Number of objects in the subset
54448 * @return {Number | BigNumber} Returns the composition counts of n into k parts.
54449 */
54450 var composition = typed('composition', {
54451 'number | BigNumber, number | BigNumber': function (n, k) {
54452 if (!isInteger(n) || !isPositive(n) || !isInteger(k) || !isPositive(k)) {
54453 throw new TypeError('Positive integer value expected in function composition');
54454 }
54455 else if (larger(k, n)) {
54456 throw new TypeError('k must be less than or equal to n in function composition');
54457 }
54458
54459 return combinations(add(n, -1), add(k, -1));
54460 }
54461 });
54462
54463 composition.toTex = undefined; // use default template
54464
54465 return composition;
54466}
54467
54468exports.name = 'composition';
54469exports.factory = factory;
54470
54471
54472/***/ }),
54473/* 463 */
54474/***/ (function(module, exports, __webpack_require__) {
54475
54476"use strict";
54477
54478
54479function factory (type, config, load, typed) {
54480 var add = load(__webpack_require__(20));
54481 var divide = load(__webpack_require__(49));
54482 var multiply = load(__webpack_require__(12));
54483 var combinations = load(__webpack_require__(70));
54484 var isNegative = load(__webpack_require__(58));
54485 var isInteger = load(__webpack_require__(51));
54486
54487
54488 /**
54489 * The Catalan Numbers enumerate combinatorial structures of many different types.
54490 * catalan only takes integer arguments.
54491 * The following condition must be enforced: n >= 0
54492 *
54493 * Syntax:
54494 *
54495 * math.catalan(n)
54496 *
54497 * Examples:
54498 *
54499 * math.catalan(3); // returns 5;
54500 * math.catalan(8); // returns 1430;
54501 *
54502 * See also:
54503 *
54504 * bellNumbers
54505 *
54506 * @param {Number | BigNumber} n nth Catalan number
54507 * @return {Number | BigNumber} Cn(n)
54508 */
54509 var catalan = typed('catalan', {
54510 'number | BigNumber': function (n) {
54511
54512 if (!isInteger(n) || isNegative(n)) {
54513 throw new TypeError('Non-negative integer value expected in function catalan');
54514 }
54515
54516 return divide(combinations(multiply(n,2), n), add(n,1));
54517
54518 }
54519 });
54520
54521 catalan.toTex = {1: '\\mathrm{C}_{${args[0]}}'};
54522
54523 return catalan;
54524}
54525
54526exports.name = 'catalan';
54527exports.factory = factory;
54528
54529
54530/***/ }),
54531/* 464 */
54532/***/ (function(module, exports, __webpack_require__) {
54533
54534module.exports = [
54535 __webpack_require__(465),
54536 __webpack_require__(126),
54537 __webpack_require__(466),
54538 __webpack_require__(467)
54539];
54540
54541
54542/***/ }),
54543/* 465 */
54544/***/ (function(module, exports, __webpack_require__) {
54545
54546"use strict";
54547
54548
54549var deepMap = __webpack_require__(1);
54550
54551function factory (type, config, load, typed) {
54552 /**
54553 * Compute the argument of a complex value.
54554 * For a complex number `a + bi`, the argument is computed as `atan2(b, a)`.
54555 *
54556 * For matrices, the function is evaluated element wise.
54557 *
54558 * Syntax:
54559 *
54560 * math.arg(x)
54561 *
54562 * Examples:
54563 *
54564 * var a = math.complex(2, 2);
54565 * math.arg(a) / math.pi; // returns number 0.25
54566 *
54567 * var b = math.complex('2 + 3i');
54568 * math.arg(b); // returns number 0.982793723247329
54569 * math.atan2(3, 2); // returns number 0.982793723247329
54570 *
54571 * See also:
54572 *
54573 * re, im, conj, abs
54574 *
54575 * @param {number | BigNumber | Complex | Array | Matrix} x
54576 * A complex number or array with complex numbers
54577 * @return {number | BigNumber | Array | Matrix} The argument of x
54578 */
54579 var arg = typed('arg', {
54580 'number': function (x) {
54581 return Math.atan2(0, x);
54582 },
54583
54584 'BigNumber': function (x) {
54585 return type.BigNumber.atan2(0, x);
54586 },
54587
54588 'Complex': function (x) {
54589 return x.arg();
54590 },
54591
54592 // TODO: implement BigNumber support for function arg
54593
54594 'Array | Matrix': function (x) {
54595 return deepMap(x, arg);
54596 }
54597 });
54598
54599 arg.toTex = {1: '\\arg\\left(${args[0]}\\right)'};
54600
54601 return arg;
54602}
54603
54604exports.name = 'arg';
54605exports.factory = factory;
54606
54607
54608/***/ }),
54609/* 466 */
54610/***/ (function(module, exports, __webpack_require__) {
54611
54612"use strict";
54613
54614
54615var deepMap = __webpack_require__(1);
54616
54617function factory (type, config, load, typed) {
54618 /**
54619 * Get the imaginary part of a complex number.
54620 * For a complex number `a + bi`, the function returns `b`.
54621 *
54622 * For matrices, the function is evaluated element wise.
54623 *
54624 * Syntax:
54625 *
54626 * math.im(x)
54627 *
54628 * Examples:
54629 *
54630 * var a = math.complex(2, 3);
54631 * math.re(a); // returns number 2
54632 * math.im(a); // returns number 3
54633 *
54634 * math.re(math.complex('-5.2i')); // returns number -5.2
54635 * math.re(math.complex(2.4)); // returns number 0
54636 *
54637 * See also:
54638 *
54639 * re, conj, abs, arg
54640 *
54641 * @param {number | BigNumber | Complex | Array | Matrix} x
54642 * A complex number or array with complex numbers
54643 * @return {number | BigNumber | Array | Matrix} The imaginary part of x
54644 */
54645 var im = typed('im', {
54646 'number': function (x) {
54647 return 0;
54648 },
54649
54650 'BigNumber': function (x) {
54651 return new type.BigNumber(0);
54652 },
54653
54654 'Complex': function (x) {
54655 return x.im;
54656 },
54657
54658 'Array | Matrix': function (x) {
54659 return deepMap(x, im);
54660 }
54661 });
54662
54663 im.toTex = {1: '\\Im\\left\\lbrace${args[0]}\\right\\rbrace'};
54664
54665 return im;
54666}
54667
54668exports.name = 'im';
54669exports.factory = factory;
54670
54671
54672/***/ }),
54673/* 467 */
54674/***/ (function(module, exports, __webpack_require__) {
54675
54676"use strict";
54677
54678
54679var deepMap = __webpack_require__(1);
54680
54681function factory (type, config, load, typed) {
54682 /**
54683 * Get the real part of a complex number.
54684 * For a complex number `a + bi`, the function returns `a`.
54685 *
54686 * For matrices, the function is evaluated element wise.
54687 *
54688 * Syntax:
54689 *
54690 * math.re(x)
54691 *
54692 * Examples:
54693 *
54694 * var a = math.complex(2, 3);
54695 * math.re(a); // returns number 2
54696 * math.im(a); // returns number 3
54697 *
54698 * math.re(math.complex('-5.2i')); // returns number 0
54699 * math.re(math.complex(2.4)); // returns number 2.4
54700 *
54701 * See also:
54702 *
54703 * im, conj, abs, arg
54704 *
54705 * @param {number | BigNumber | Complex | Array | Matrix} x
54706 * A complex number or array with complex numbers
54707 * @return {number | BigNumber | Array | Matrix} The real part of x
54708 */
54709 var re = typed('re', {
54710 'number': function (x) {
54711 return x;
54712 },
54713
54714 'BigNumber': function (x) {
54715 return x;
54716 },
54717
54718 'Complex': function (x) {
54719 return x.re;
54720 },
54721
54722 'Array | Matrix': function (x) {
54723 return deepMap(x, re);
54724 }
54725 });
54726
54727 re.toTex = {1: '\\Re\\left\\lbrace${args[0]}\\right\\rbrace'};
54728
54729 return re;
54730}
54731
54732exports.name = 're';
54733exports.factory = factory;
54734
54735
54736/***/ }),
54737/* 468 */
54738/***/ (function(module, exports, __webpack_require__) {
54739
54740module.exports = [
54741 __webpack_require__(469),
54742 __webpack_require__(470)
54743];
54744
54745
54746/***/ }),
54747/* 469 */
54748/***/ (function(module, exports, __webpack_require__) {
54749
54750"use strict";
54751
54752
54753function factory (type, config, load, typed) {
54754
54755 var abs = load(__webpack_require__(28));
54756 var add = load(__webpack_require__(20));
54757 var addScalar = load(__webpack_require__(16));
54758 var matrix = load(__webpack_require__(0));
54759 var multiply = load(__webpack_require__(12));
54760 var multiplyScalar = load(__webpack_require__(22));
54761 var divideScalar = load(__webpack_require__(14));
54762 var subtract = load(__webpack_require__(21));
54763 var smaller = load(__webpack_require__(39));
54764 var equalScalar = load(__webpack_require__(10));
54765
54766 /**
54767 * Calculates the point of intersection of two lines in two or three dimensions
54768 * and of a line and a plane in three dimensions. The inputs are in the form of
54769 * arrays or 1 dimensional matrices. The line intersection functions return null
54770 * if the lines do not meet.
54771 *
54772 * Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`.
54773 *
54774 * Syntax:
54775 *
54776 * math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2)
54777 * math.intersect(endPoint1, endPoint2, planeCoefficients)
54778 *
54779 * Examples:
54780 *
54781 * math.intersect([0, 0], [10, 10], [10, 0], [0, 10]); // Returns [5, 5]
54782 * math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]); // Returns [5, 5, 0]
54783 * math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]); // Returns [7, -4, 3]
54784 *
54785 * @param {Array | Matrix} w Co-ordinates of first end-point of first line
54786 * @param {Array | Matrix} x Co-ordinates of second end-point of first line
54787 * @param {Array | Matrix} y Co-ordinates of first end-point of second line
54788 * OR Co-efficients of the plane's equation
54789 * @param {Array | Matrix} z Co-ordinates of second end-point of second line
54790 * OR null if the calculation is for line and plane
54791 * @return {Array} Returns the point of intersection of lines/lines-planes
54792 */
54793 var intersect = typed('intersect', {
54794 'Array, Array, Array': function (x, y, plane) {
54795 if (!_3d(x)) { throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument'); }
54796 if (!_3d(y)) { throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument'); }
54797 if (!_4d(plane)) { throw new TypeError('Array with 4 numbers expected as third argument'); }
54798
54799 return _intersectLinePlane(x[0], x[1], x[2], y[0], y[1], y[2], plane[0], plane[1], plane[2], plane[3]);
54800 },
54801
54802 'Array, Array, Array, Array': function (w, x, y, z) {
54803 if (w.length === 2) {
54804 if (!_2d(w)) { throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument'); }
54805 if (!_2d(x)) { throw new TypeError('Array with 2 numbers or BigNumbers expected for second argument'); }
54806 if (!_2d(y)) { throw new TypeError('Array with 2 numbers or BigNumbers expected for third argument'); }
54807 if (!_2d(z)) { throw new TypeError('Array with 2 numbers or BigNumbers expected for fourth argument'); }
54808
54809 return _intersect2d(w, x, y, z);
54810 }
54811 else if (w.length === 3) {
54812 if (!_3d(w)) { throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument'); }
54813 if (!_3d(x)) { throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument'); }
54814 if (!_3d(y)) { throw new TypeError('Array with 3 numbers or BigNumbers expected for third argument'); }
54815 if (!_3d(z)) { throw new TypeError('Array with 3 numbers or BigNumbers expected for fourth argument'); }
54816
54817 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]);
54818 }
54819 else {
54820 throw new TypeError('Arrays with two or thee dimensional points expected');
54821 }
54822 },
54823
54824 'Matrix, Matrix, Matrix': function (x, y, plane) {
54825 return matrix(intersect(x.valueOf(), y.valueOf(), plane.valueOf()));
54826 },
54827
54828 'Matrix, Matrix, Matrix, Matrix': function (w, x, y, z) {
54829 // TODO: output matrix type should match input matrix type
54830 return matrix(intersect(w.valueOf(), x.valueOf(), y.valueOf(), z.valueOf()));
54831 }
54832 });
54833
54834 function _isNumber(a) {
54835 // intersect supports numbers and bignumbers
54836 return (typeof a === 'number' || type.isBigNumber(a));
54837 }
54838
54839 function _2d(x) {
54840 return x.length === 2 && _isNumber(x[0]) && _isNumber(x[1]);
54841 }
54842
54843 function _3d(x) {
54844 return x.length === 3 && _isNumber(x[0]) && _isNumber(x[1]) && _isNumber(x[2]);
54845 }
54846
54847 function _4d(x) {
54848 return x.length === 4 && _isNumber(x[0]) && _isNumber(x[1]) && _isNumber(x[2]) && _isNumber(x[3]);
54849 }
54850
54851 function _intersect2d(p1a, p1b, p2a, p2b){
54852 var o1 = p1a;
54853 var o2 = p2a;
54854 var d1 = subtract(o1, p1b);
54855 var d2 = subtract(o2, p2b);
54856 var det = subtract(multiplyScalar(d1[0], d2[1]), multiplyScalar(d2[0], d1[1]));
54857 if (smaller(abs(det), config.epsilon)) {
54858 return null;
54859 }
54860 var d20o11 = multiplyScalar(d2[0], o1[1]);
54861 var d21o10 = multiplyScalar(d2[1], o1[0]);
54862 var d20o21 = multiplyScalar(d2[0], o2[1]);
54863 var d21o20 = multiplyScalar(d2[1], o2[0]);
54864 var t = divideScalar(addScalar(subtract(subtract(d20o11, d21o10), d20o21), d21o20), det);
54865 return add(multiply(d1, t), o1);
54866 }
54867
54868 function _intersect3dHelper(a, b, c, d, e, f, g, h, i, j, k, l){
54869 // (a - b)*(c - d) + (e - f)*(g - h) + (i - j)*(k - l)
54870 var add1 = multiplyScalar(subtract(a, b), subtract(c, d));
54871 var add2 = multiplyScalar(subtract(e, f), subtract(g, h));
54872 var add3 = multiplyScalar(subtract(i, j), subtract(k, l));
54873 return addScalar(addScalar(add1, add2), add3);
54874 }
54875
54876 function _intersect3d(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4){
54877 var d1343 = _intersect3dHelper(x1, x3, x4, x3, y1, y3, y4, y3, z1, z3, z4, z3);
54878 var d4321 = _intersect3dHelper(x4, x3, x2, x1, y4, y3, y2, y1, z4, z3, z2, z1);
54879 var d1321 = _intersect3dHelper(x1, x3, x2, x1, y1, y3, y2, y1, z1, z3, z2, z1);
54880 var d4343 = _intersect3dHelper(x4, x3, x4, x3, y4, y3, y4, y3, z4, z3, z4, z3);
54881 var d2121 = _intersect3dHelper(x2, x1, x2, x1, y2, y1, y2, y1, z2, z1, z2, z1);
54882 var ta = divideScalar(
54883 subtract(multiplyScalar(d1343, d4321), multiplyScalar(d1321, d4343)),
54884 subtract(multiplyScalar(d2121, d4343), multiplyScalar(d4321, d4321)));
54885 var tb = divideScalar(addScalar(d1343, multiplyScalar(ta, d4321)), d4343);
54886
54887 var pax = addScalar(x1, multiplyScalar(ta, subtract(x2, x1)));
54888 var pay = addScalar(y1, multiplyScalar(ta, subtract(y2, y1)));
54889 var paz = addScalar(z1, multiplyScalar(ta, subtract(z2, z1)));
54890 var pbx = addScalar(x3, multiplyScalar(tb, subtract(x4, x3)));
54891 var pby = addScalar(y3, multiplyScalar(tb, subtract(y4, y3)));
54892 var pbz = addScalar(z3, multiplyScalar(tb, subtract(z4, z3)));
54893 if (equalScalar(pax, pbx) && equalScalar(pay, pby) && equalScalar(paz, pbz)){
54894 return [pax, pay, paz];
54895 }
54896 else{
54897 return null;
54898 }
54899 }
54900
54901 function _intersectLinePlane(x1, y1, z1, x2, y2, z2, x, y, z, c){
54902 var x1x = multiplyScalar(x1, x);
54903 var x2x = multiplyScalar(x2, x);
54904 var y1y = multiplyScalar(y1, y);
54905 var y2y = multiplyScalar(y2, y);
54906 var z1z = multiplyScalar(z1, z);
54907 var z2z = multiplyScalar(z2, z);
54908 var t = divideScalar(
54909 subtract(subtract(subtract(c, x1x), y1y), z1z),
54910 subtract(subtract(subtract(addScalar(addScalar(x2x, y2y), z2z), x1x), y1y), z1z));
54911 var px = addScalar(x1, multiplyScalar(t, subtract(x2, x1)));
54912 var py = addScalar(y1, multiplyScalar(t, subtract(y2, y1)));
54913 var pz = addScalar(z1, multiplyScalar(t, subtract(z2, z1)));
54914 return [px, py, pz];
54915 // TODO: Add cases when line is parallel to the plane:
54916 // (a) no intersection,
54917 // (b) line contained in plane
54918 }
54919
54920 return intersect;
54921}
54922
54923exports.name = 'intersect';
54924exports.factory = factory;
54925
54926
54927/***/ }),
54928/* 470 */
54929/***/ (function(module, exports, __webpack_require__) {
54930
54931"use strict";
54932
54933
54934function factory (type, config, load, typed) {
54935 var matrix = load(__webpack_require__(0));
54936 var add = load(__webpack_require__(16));
54937 var subtract = load(__webpack_require__(21));
54938 var multiply = load(__webpack_require__(22));
54939 var divide = load(__webpack_require__(14));
54940 var negate = load(__webpack_require__(35));
54941 var sqrt = load(__webpack_require__(50));
54942 var abs = load(__webpack_require__(28));
54943
54944 /**
54945 * Calculates:
54946 * The eucledian distance between two points in 2 and 3 dimensional spaces.
54947 * Distance between point and a line in 2 and 3 dimensional spaces.
54948 * Pairwise distance between a set of 2D or 3D points
54949 * NOTE:
54950 * When substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c
54951 * 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)
54952 *
54953 * Syntax:
54954 * math.distance([x1, y1], [x2, y2])
54955 *- math.distance({pointOneX: 4, pointOneY: 5}, {pointTwoX: 2, pointTwoY: 7})
54956 * math.distance([x1, y1, z1], [x2, y2, z2])
54957 * math.distance({pointOneX: 4, pointOneY: 5, pointOneZ: 8}, {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9})
54958 * math.distance([[A], [B], [C]...])
54959 * math.distance([x1, y1], [LinePtX1, LinePtY1], [LinePtX2, LinePtY2])
54960 * math.distance({pointX: 1, pointY: 4}, {lineOnePtX: 6, lineOnePtY: 3}, {lineTwoPtX: 2, lineTwoPtY: 8})
54961 * math.distance([x1, y1, z1], [LinePtX1, LinePtY1, LinePtZ1], [LinePtX2, LinePtY2, LinePtZ2])
54962 * math.distance({pointX: 1, pointY: 4, pointZ: 7}, {lineOnePtX: 6, lineOnePtY: 3, lineOnePtZ: 4}, {lineTwoPtX: 2, lineTwoPtY: 8, lineTwoPtZ: 5})
54963 * math.distance([x1, y1], [xCoeffLine, yCoeffLine, constant])
54964 * math.distance({pointX: 10, pointY: 10}, {xCoeffLine: 8, yCoeffLine: 1, constant: 3})
54965 * math.distance([x1, y1, z1], [x0, y0, z0, a-tCoeff, b-tCoeff, c-tCoeff]) point and parametric equation of 3D line
54966 * math.distance([x, y, z], [x0, y0, z0, a, b, c])
54967 * math.distance({pointX: 2, pointY: 5, pointZ: 9}, {x0: 4, y0: 6, z0: 3, a: 4, b: 2, c: 0})
54968 *
54969 * Examples:
54970 * math.distance([0,0], [4,4]) // Returns 5.6569
54971 * math.distance(
54972 * {pointOneX: 0, pointOneY: 0},
54973 * {pointTwoX: 10, pointTwoY: 10}) // Returns 14.142135623730951
54974 * math.distance([1, 0, 1], [4, -2, 2]) // Returns 3.74166
54975 * math.distance(
54976 * {pointOneX: 4, pointOneY: 5, pointOneZ: 8},
54977 * {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9}) // Returns 3
54978 * math.distance([[1, 2], [1, 2], [1, 3]]) // Returns [0, 1, 1]
54979 * math.distance([[1,2,4], [1,2,6], [8,1,3]]) // Returns [2, 7.14142842854285, 7.681145747868608]
54980 * math.distance([10, 10], [8, 1, 3]) // Returns 11.535230316796387
54981 * math.distance([10, 10], [2, 3], [-8, 0]) // Returns 8.759953130362847
54982 * math.distance(
54983 * {pointX: 1, pointY: 4},
54984 * {lineOnePtX: 6, lineOnePtY: 3},
54985 * {lineTwoPtX: 2, lineTwoPtY: 8}) // Returns 2.720549372624744
54986 * math.distance([2, 3, 1], [1, 1, 2, 5, 0, 1]) // Returns 2.3204774044612857
54987 * math.distance(
54988 * {pointX: 2, pointY: 3, pointZ: 1},
54989 * {x0: 1, y0: 1, z0: 2, a: 5, b: 0, c: 1} // Returns 2.3204774044612857
54990 *
54991 * @param {Array | Matrix | Object} x Co-ordinates of first point
54992 * @param {Array | Matrix | Object} y Co-ordinates of second point
54993 * @return {Number | BigNumber} Returns the distance from two/three points
54994 */
54995
54996 var distance = typed('distance', {
54997 'Array, Array, Array': function(x, y, z){
54998 // Point to Line 2D; (x=Point, y=LinePoint1, z=LinePoint2)
54999 if (x.length == 2 && y.length == 2 && z.length == 2){
55000 if (!_2d(x)) { throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument'); }
55001 if (!_2d(y)) { throw new TypeError('Array with 2 numbers or BigNumbers expected for second argument'); }
55002 if (!_2d(z)) { throw new TypeError('Array with 2 numbers or BigNumbers expected for third argument'); }
55003 var m = divide(subtract(z[1], z[0]), subtract(y[1], y[0]));
55004 var xCoeff = multiply(multiply(m, m), y[0]);
55005 var yCoeff = negate(multiply(m, y[0]));
55006 var constant = x[1];
55007
55008 return _distancePointLine2D(x[0], x[1], xCoeff, yCoeff, constant);
55009 }
55010 else{
55011 throw new TypeError('Invalid Arguments: Try again');
55012 }
55013 },
55014 'Object, Object, Object': function(x, y, z){
55015 if (Object.keys(x).length == 2 && Object.keys(y).length == 2 && Object.keys(z).length == 2){
55016 if (!_2d(x)) { throw new TypeError('Values of pointX and pointY should be numbers or BigNumbers'); }
55017 if (!_2d(y)) { throw new TypeError('Values of lineOnePtX and lineOnePtY should be numbers or BigNumbers'); }
55018 if (!_2d(z)) { throw new TypeError('Values of lineTwoPtX and lineTwoPtY should be numbers or BigNumbers'); }
55019 if (x.hasOwnProperty('pointX') && x.hasOwnProperty('pointY') && y.hasOwnProperty('lineOnePtX') &&
55020 y.hasOwnProperty('lineOnePtY') && z.hasOwnProperty('lineTwoPtX') && z.hasOwnProperty('lineTwoPtY')){
55021 var m = divide(subtract(z.lineTwoPtY, z.lineTwoPtX), subtract(y.lineOnePtY, y.lineOnePtX));
55022 var xCoeff = multiply(multiply(m, m), y.lineOnePtX);
55023 var yCoeff = negate(multiply(m, y.lineOnePtX));
55024 var constant = x.pointX;
55025
55026 return _distancePointLine2D(x.pointX, x.pointY, xCoeff, yCoeff, constant);
55027 }
55028 else{
55029 throw new TypeError('Key names do not match');
55030 }
55031 }
55032 else{
55033 throw new TypeError('Invalid Arguments: Try again');
55034 }
55035 },
55036 'Array, Array': function(x, y){
55037 // Point to Line 2D; (x=[pointX, pointY], y=[x-coeff, y-coeff, const])
55038 if (x.length == 2 && y.length == 3){
55039 if (!_2d(x)) { throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument'); }
55040 if (!_3d(y)) { throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument'); }
55041
55042 return _distancePointLine2D(x[0], x[1], y[0], y[1], y[2]);
55043 }
55044 // Point to Line 3D
55045 else if (x.length == 3 && y.length == 6){
55046 if (!_3d(x)) { throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument'); }
55047 if (!_parametricLine(y)) { throw new TypeError('Array with 6 numbers or BigNumbers expected for second argument'); }
55048
55049 return _distancePointLine3D(x[0], x[1], x[2], y[0], y[1], y[2], y[3], y[4], y[5]);
55050 }
55051 // Point to Point 2D
55052 else if (x.length == 2 && y.length == 2){
55053 if (!_2d(x)) { throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument'); }
55054 if (!_2d(y)) { throw new TypeError('Array with 2 numbers or BigNumbers expected for second argument'); }
55055
55056 return _distance2d(x[0], x[1], y[0], y[1]);
55057 }
55058 // Point to Point 3D
55059 else if(x.length == 3 && y.length == 3){
55060 if (!_3d(x)) { throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument'); }
55061 if (!_3d(y)) { throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument'); }
55062
55063 return _distance3d(x[0], x[1], x[2], y[0], y[1], y[2]);
55064 }
55065 else{
55066 throw new TypeError('Invalid Arguments: Try again');
55067 }
55068 },
55069 'Object, Object': function(x, y){
55070 if (Object.keys(x).length == 2 && Object.keys(y).length == 3){
55071 if (!_2d(x)) { throw new TypeError('Values of pointX and pointY should be numbers or BigNumbers'); }
55072 if (!_3d(y)) { throw new TypeError('Values of xCoeffLine, yCoeffLine and constant should be numbers or BigNumbers'); }
55073 if (x.hasOwnProperty('pointX') && x.hasOwnProperty('pointY') && y.hasOwnProperty('xCoeffLine') &&
55074 y.hasOwnProperty('yCoeffLine') && y.hasOwnProperty('constant')){
55075
55076 return _distancePointLine2D(x.pointX, x.pointY, y.xCoeffLine, y.yCoeffLine, y.constant);
55077 }
55078 else{
55079 throw new TypeError('Key names do not match');
55080 }
55081 }
55082 // Point to Line 3D
55083 else if (Object.keys(x).length == 3 && Object.keys(y).length == 6){
55084 if (!_3d(x)) { throw new TypeError('Values of pointX, pointY and pointZ should be numbers or BigNumbers'); }
55085 if (!_parametricLine(y)) { throw new TypeError('Values of x0, y0, z0, a, b and c should be numbers or BigNumbers'); }
55086 if (x.hasOwnProperty('pointX') && x.hasOwnProperty('pointY') && y.hasOwnProperty('x0') &&
55087 y.hasOwnProperty('y0') && y.hasOwnProperty('z0') && y.hasOwnProperty('a') &&
55088 y.hasOwnProperty('b') && y.hasOwnProperty('c')){
55089
55090 return _distancePointLine3D(x.pointX, x.pointY, x.pointZ, y.x0, y.y0, y.z0, y.a, y.b, y.c);
55091 }
55092 else{
55093 throw new TypeError('Key names do not match');
55094 }
55095 }
55096 // Point to Point 2D
55097 else if (Object.keys(x).length == 2 && Object.keys(y).length == 2){
55098 if (!_2d(x)) { throw new TypeError('Values of pointOneX and pointOneY should be numbers or BigNumbers'); }
55099 if (!_2d(y)) { throw new TypeError('Values of pointTwoX and pointTwoY should be numbers or BigNumbers'); }
55100 if (x.hasOwnProperty('pointOneX') && x.hasOwnProperty('pointOneY') &&
55101 y.hasOwnProperty('pointTwoX') && y.hasOwnProperty('pointTwoY')){
55102
55103 return _distance2d(x.pointOneX, x.pointOneY, y.pointTwoX, y.pointTwoY);
55104 }
55105 else{
55106 throw new TypeError('Key names do not match');
55107 }
55108 }
55109 // Point to Point 3D
55110 else if(Object.keys(x).length == 3 && Object.keys(y).length == 3){
55111 if (!_3d(x)) { throw new TypeError('Values of pointOneX, pointOneY and pointOneZ should be numbers or BigNumbers'); }
55112 if (!_3d(y)) { throw new TypeError('Values of pointTwoX, pointTwoY and pointTwoZ should be numbers or BigNumbers'); }
55113 if (x.hasOwnProperty('pointOneX') && x.hasOwnProperty('pointOneY') && x.hasOwnProperty('pointOneZ') &&
55114 y.hasOwnProperty('pointTwoX') && y.hasOwnProperty('pointTwoY') && y.hasOwnProperty('pointTwoZ')){
55115
55116 return _distance3d(x.pointOneX, x.pointOneY, x.pointOneZ, y.pointTwoX, y.pointTwoY, y.pointTwoZ);
55117 }
55118 else {
55119 throw new TypeError('Key names do not match');
55120 }
55121 }
55122 else{
55123 throw new TypeError('Invalid Arguments: Try again');
55124 }
55125 },
55126 'Array': function(arr){
55127 if (!_pairwise(arr)) { throw new TypeError('Incorrect array format entered for pairwise distance calculation'); }
55128
55129 return _distancePairwise(arr);
55130 }
55131 });
55132
55133 function _isNumber(a) {
55134 // distance supports numbers and bignumbers
55135 return (typeof a === 'number' || type.isBigNumber(a));
55136 }
55137
55138 function _2d(a){
55139 // checks if the number of arguments are correct in count and are valid (should be numbers)
55140 if (a.constructor !== Array){
55141 a = _objectToArray(a);
55142 }
55143 return _isNumber(a[0]) && _isNumber(a[1]);
55144 }
55145
55146 function _3d(a){
55147 // checks if the number of arguments are correct in count and are valid (should be numbers)
55148 if (a.constructor !== Array){
55149 a = _objectToArray(a);
55150 }
55151 return _isNumber(a[0]) && _isNumber(a[1]) && _isNumber(a[2]);
55152 }
55153
55154 function _parametricLine(a){
55155 if (a.constructor !== Array){
55156 a = _objectToArray(a);
55157 }
55158 return _isNumber(a[0]) && _isNumber(a[1]) && _isNumber(a[2]) &&
55159 _isNumber(a[3]) && _isNumber(a[4]) && _isNumber(a[5]);
55160 }
55161
55162 function _objectToArray(o){
55163 var keys = Object.keys(o);
55164 var a = [];
55165 for (var i = 0; i < keys.length; i++) {
55166 a.push(o[keys[i]]);
55167 }
55168 return a;
55169 }
55170
55171 function _pairwise(a){
55172 //checks for valid arguments passed to _distancePairwise(Array)
55173 if (a[0].length == 2 && _isNumber(a[0][0]) && _isNumber(a[0][1])){
55174 for(var i in a){
55175 if (a[i].length != 2 || !_isNumber(a[i][0]) || !_isNumber(a[i][1])){
55176 return false;
55177 }
55178 }
55179 }
55180 else if (a[0].length == 3 && _isNumber(a[0][0]) && _isNumber(a[0][1]) && _isNumber(a[0][2])){
55181 for(var i in a){
55182 if (a[i].length != 3 || !_isNumber(a[i][0]) || !_isNumber(a[i][1]) || !_isNumber(a[i][2])){
55183 return false;
55184 }
55185 }
55186 }
55187 else{
55188 return false;
55189 }
55190 return true;
55191 }
55192
55193 function _distancePointLine2D(x, y, a, b, c){
55194 var num = abs(add(add(multiply(a, x), multiply(b, y)), c));
55195 var den = sqrt(add(multiply(a, a), multiply(b, b)));
55196 var result = divide(num, den);
55197 return result;
55198 }
55199
55200 function _distancePointLine3D(x, y, z, x0, y0, z0, a, b, c){
55201 var num = [ subtract(multiply(subtract(y0, y), c), multiply(subtract(z0, z), b)),
55202 subtract(multiply(subtract(z0, z), a), multiply(subtract(x0, x), c)),
55203 subtract(multiply(subtract(x0, x), b), multiply(subtract(y0, y), a)) ];
55204 num = sqrt(add(add(multiply(num[0], num[0]), multiply(num[1], num[1])), multiply(num[2], num[2])));
55205 var den = sqrt(add(add(multiply(a, a), multiply(b, b)), multiply(c, c)));
55206 var result = divide(num, den);
55207 return result;
55208 }
55209
55210 function _distance2d(x1, y1, x2, y2){
55211 var yDiff = subtract(y2, y1);
55212 var xDiff = subtract(x2, x1);
55213 var radicant = add(multiply(yDiff, yDiff), multiply(xDiff, xDiff));
55214 var result = sqrt(radicant);
55215 return result;
55216 }
55217
55218 function _distance3d(x1, y1, z1, x2, y2, z2){
55219 var zDiff = subtract(z2, z1);
55220 var yDiff = subtract(y2, y1);
55221 var xDiff = subtract(x2, x1);
55222 var radicant = add(add(multiply(zDiff, zDiff), multiply(yDiff, yDiff)), multiply(xDiff, xDiff));
55223 var result = sqrt(radicant);
55224 return result;
55225 }
55226
55227 function _distancePairwise(a){
55228 var result = [];
55229 for(var i = 0; i < a.length-1; i++){
55230 for(var j = i+1; j < a.length; j++){
55231 if (a[0].length == 2){
55232 result.push(_distance2d(a[i][0], a[i][1], a[j][0], a[j][1]));
55233 }
55234 else if (a[0].length == 3){
55235 result.push(_distance3d(a[i][0], a[i][1], a[i][2], a[j][0], a[j][1], a[j][2]));
55236 }
55237 }
55238 }
55239 return result;
55240 }
55241
55242 return distance;
55243}
55244
55245exports.name = 'distance';
55246exports.factory = factory;
55247
55248
55249/***/ }),
55250/* 471 */
55251/***/ (function(module, exports, __webpack_require__) {
55252
55253module.exports = [
55254 __webpack_require__(472),
55255 __webpack_require__(141),
55256 __webpack_require__(473),
55257 __webpack_require__(474)
55258];
55259
55260
55261/***/ }),
55262/* 472 */
55263/***/ (function(module, exports, __webpack_require__) {
55264
55265"use strict";
55266
55267
55268function factory (type, config, load, typed) {
55269 var latex = __webpack_require__(4);
55270
55271 var matrix = load(__webpack_require__(0));
55272 var zeros = load(__webpack_require__(40));
55273 var not = load(__webpack_require__(141));
55274 var isZero = load(__webpack_require__(83));
55275
55276 var algorithm02 = load(__webpack_require__(24));
55277 var algorithm06 = load(__webpack_require__(68));
55278 var algorithm11 = load(__webpack_require__(19));
55279 var algorithm13 = load(__webpack_require__(8));
55280 var algorithm14 = load(__webpack_require__(6));
55281
55282 /**
55283 * Logical `and`. Test whether two values are both defined with a nonzero/nonempty value.
55284 * For matrices, the function is evaluated element wise.
55285 *
55286 * Syntax:
55287 *
55288 * math.and(x, y)
55289 *
55290 * Examples:
55291 *
55292 * math.and(2, 4); // returns true
55293 *
55294 * a = [2, 0, 0];
55295 * b = [3, 7, 0];
55296 * c = 0;
55297 *
55298 * math.and(a, b); // returns [true, false, false]
55299 * math.and(a, c); // returns [false, false, false]
55300 *
55301 * See also:
55302 *
55303 * not, or, xor
55304 *
55305 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check
55306 * @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check
55307 * @return {boolean | Array | Matrix}
55308 * Returns true when both inputs are defined with a nonzero/nonempty value.
55309 */
55310 var and = typed('and', {
55311
55312 'number, number': function (x, y) {
55313 return !!(x && y);
55314 },
55315
55316 'Complex, Complex': function (x, y) {
55317 return (x.re !== 0 || x.im !== 0) && (y.re !== 0 || y.im !== 0);
55318 },
55319
55320 'BigNumber, BigNumber': function (x, y) {
55321 return !x.isZero() && !y.isZero() && !x.isNaN() && !y.isNaN();
55322 },
55323
55324 'Unit, Unit': function (x, y) {
55325 return and(x.value, y.value);
55326 },
55327
55328 'Matrix, Matrix': function (x, y) {
55329 // result
55330 var c;
55331
55332 // process matrix storage
55333 switch (x.storage()) {
55334 case 'sparse':
55335 switch (y.storage()) {
55336 case 'sparse':
55337 // sparse & sparse
55338 c = algorithm06(x, y, and, false);
55339 break;
55340 default:
55341 // sparse & dense
55342 c = algorithm02(y, x, and, true);
55343 break;
55344 }
55345 break;
55346 default:
55347 switch (y.storage()) {
55348 case 'sparse':
55349 // dense & sparse
55350 c = algorithm02(x, y, and, false);
55351 break;
55352 default:
55353 // dense & dense
55354 c = algorithm13(x, y, and);
55355 break;
55356 }
55357 break;
55358 }
55359 return c;
55360 },
55361
55362 'Array, Array': function (x, y) {
55363 // use matrix implementation
55364 return and(matrix(x), matrix(y)).valueOf();
55365 },
55366
55367 'Array, Matrix': function (x, y) {
55368 // use matrix implementation
55369 return and(matrix(x), y);
55370 },
55371
55372 'Matrix, Array': function (x, y) {
55373 // use matrix implementation
55374 return and(x, matrix(y));
55375 },
55376
55377 'Matrix, any': function (x, y) {
55378 // check scalar
55379 if (not(y)) {
55380 // return zero matrix
55381 return zeros(x.size(), x.storage());
55382 }
55383 // result
55384 var c;
55385 // check storage format
55386 switch (x.storage()) {
55387 case 'sparse':
55388 c = algorithm11(x, y, and, false);
55389 break;
55390 default:
55391 c = algorithm14(x, y, and, false);
55392 break;
55393 }
55394 return c;
55395 },
55396
55397 'any, Matrix': function (x, y) {
55398 // check scalar
55399 if (not(x)) {
55400 // return zero matrix
55401 return zeros(x.size(), x.storage());
55402 }
55403 // result
55404 var c;
55405 // check storage format
55406 switch (y.storage()) {
55407 case 'sparse':
55408 c = algorithm11(y, x, and, true);
55409 break;
55410 default:
55411 c = algorithm14(y, x, and, true);
55412 break;
55413 }
55414 return c;
55415 },
55416
55417 'Array, any': function (x, y) {
55418 // use matrix implementation
55419 return and(matrix(x), y).valueOf();
55420 },
55421
55422 'any, Array': function (x, y) {
55423 // use matrix implementation
55424 return and(x, matrix(y)).valueOf();
55425 }
55426 });
55427
55428 and.toTex = {
55429 2: '\\left(${args[0]}' + latex.operators['and'] + '${args[1]}\\right)'
55430 };
55431
55432 return and;
55433}
55434
55435exports.name = 'and';
55436exports.factory = factory;
55437
55438
55439/***/ }),
55440/* 473 */
55441/***/ (function(module, exports, __webpack_require__) {
55442
55443"use strict";
55444
55445
55446function factory (type, config, load, typed) {
55447 var latex = __webpack_require__(4);
55448
55449 var matrix = load(__webpack_require__(0));
55450
55451 var algorithm03 = load(__webpack_require__(17));
55452 var algorithm05 = load(__webpack_require__(61));
55453 var algorithm12 = load(__webpack_require__(18));
55454 var algorithm13 = load(__webpack_require__(8));
55455 var algorithm14 = load(__webpack_require__(6));
55456
55457 /**
55458 * Logical `or`. Test if at least one value is defined with a nonzero/nonempty value.
55459 * For matrices, the function is evaluated element wise.
55460 *
55461 * Syntax:
55462 *
55463 * math.or(x, y)
55464 *
55465 * Examples:
55466 *
55467 * math.or(2, 4); // returns true
55468 *
55469 * a = [2, 5, 0];
55470 * b = [0, 22, 0];
55471 * c = 0;
55472 *
55473 * math.or(a, b); // returns [true, true, false]
55474 * math.or(b, c); // returns [false, true, false]
55475 *
55476 * See also:
55477 *
55478 * and, not, xor
55479 *
55480 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check
55481 * @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check
55482 * @return {boolean | Array | Matrix}
55483 * Returns true when one of the inputs is defined with a nonzero/nonempty value.
55484 */
55485 var or = typed('or', {
55486
55487 'number, number': function (x, y) {
55488 return !!(x || y);
55489 },
55490
55491 'Complex, Complex': function (x, y) {
55492 return (x.re !== 0 || x.im !== 0) || (y.re !== 0 || y.im !== 0);
55493 },
55494
55495 'BigNumber, BigNumber': function (x, y) {
55496 return (!x.isZero() && !x.isNaN()) || (!y.isZero() && !y.isNaN());
55497 },
55498
55499 'Unit, Unit': function (x, y) {
55500 return or(x.value, y.value);
55501 },
55502
55503 'Matrix, Matrix': function (x, y) {
55504 // result
55505 var c;
55506
55507 // process matrix storage
55508 switch (x.storage()) {
55509 case 'sparse':
55510 switch (y.storage()) {
55511 case 'sparse':
55512 // sparse + sparse
55513 c = algorithm05(x, y, or);
55514 break;
55515 default:
55516 // sparse + dense
55517 c = algorithm03(y, x, or, true);
55518 break;
55519 }
55520 break;
55521 default:
55522 switch (y.storage()) {
55523 case 'sparse':
55524 // dense + sparse
55525 c = algorithm03(x, y, or, false);
55526 break;
55527 default:
55528 // dense + dense
55529 c = algorithm13(x, y, or);
55530 break;
55531 }
55532 break;
55533 }
55534 return c;
55535 },
55536
55537 'Array, Array': function (x, y) {
55538 // use matrix implementation
55539 return or(matrix(x), matrix(y)).valueOf();
55540 },
55541
55542 'Array, Matrix': function (x, y) {
55543 // use matrix implementation
55544 return or(matrix(x), y);
55545 },
55546
55547 'Matrix, Array': function (x, y) {
55548 // use matrix implementation
55549 return or(x, matrix(y));
55550 },
55551
55552 'Matrix, any': function (x, y) {
55553 // result
55554 var c;
55555 // check storage format
55556 switch (x.storage()) {
55557 case 'sparse':
55558 c = algorithm12(x, y, or, false);
55559 break;
55560 default:
55561 c = algorithm14(x, y, or, false);
55562 break;
55563 }
55564 return c;
55565 },
55566
55567 'any, Matrix': function (x, y) {
55568 // result
55569 var c;
55570 // check storage format
55571 switch (y.storage()) {
55572 case 'sparse':
55573 c = algorithm12(y, x, or, true);
55574 break;
55575 default:
55576 c = algorithm14(y, x, or, true);
55577 break;
55578 }
55579 return c;
55580 },
55581
55582 'Array, any': function (x, y) {
55583 // use matrix implementation
55584 return algorithm14(matrix(x), y, or, false).valueOf();
55585 },
55586
55587 'any, Array': function (x, y) {
55588 // use matrix implementation
55589 return algorithm14(matrix(y), x, or, true).valueOf();
55590 }
55591 });
55592
55593 or.toTex = {
55594 2: '\\left(${args[0]}' + latex.operators['or'] + '${args[1]}\\right)'
55595 };
55596
55597 return or;
55598}
55599
55600exports.name = 'or';
55601exports.factory = factory;
55602
55603
55604/***/ }),
55605/* 474 */
55606/***/ (function(module, exports, __webpack_require__) {
55607
55608"use strict";
55609
55610
55611function factory (type, config, load, typed) {
55612 var latex = __webpack_require__(4);
55613
55614 var matrix = load(__webpack_require__(0));
55615
55616 var algorithm03 = load(__webpack_require__(17));
55617 var algorithm07 = load(__webpack_require__(26));
55618 var algorithm12 = load(__webpack_require__(18));
55619 var algorithm13 = load(__webpack_require__(8));
55620 var algorithm14 = load(__webpack_require__(6));
55621
55622 /**
55623 * Logical `xor`. Test whether one and only one value is defined with a nonzero/nonempty value.
55624 * For matrices, the function is evaluated element wise.
55625 *
55626 * Syntax:
55627 *
55628 * math.xor(x, y)
55629 *
55630 * Examples:
55631 *
55632 * math.xor(2, 4); // returns false
55633 *
55634 * a = [2, 0, 0];
55635 * b = [2, 7, 0];
55636 * c = 0;
55637 *
55638 * math.xor(a, b); // returns [false, true, false]
55639 * math.xor(a, c); // returns [true, false, false]
55640 *
55641 * See also:
55642 *
55643 * and, not, or
55644 *
55645 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check
55646 * @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check
55647 * @return {boolean | Array | Matrix}
55648 * Returns true when one and only one input is defined with a nonzero/nonempty value.
55649 */
55650 var xor = typed('xor', {
55651
55652 'number, number': function (x, y) {
55653 return !!x !== !!y;
55654 },
55655
55656 'Complex, Complex': function (x, y) {
55657 return ((x.re !== 0 || x.im !== 0) !== (y.re !== 0 || y.im !== 0));
55658 },
55659
55660 'BigNumber, BigNumber': function (x, y) {
55661 return ((!x.isZero() && !x.isNaN()) !== (!y.isZero() && !y.isNaN()));
55662 },
55663
55664 'Unit, Unit': function (x, y) {
55665 return xor(x.value, y.value);
55666 },
55667
55668 'Matrix, Matrix': function (x, y) {
55669 // result
55670 var c;
55671
55672 // process matrix storage
55673 switch (x.storage()) {
55674 case 'sparse':
55675 switch (y.storage()) {
55676 case 'sparse':
55677 // sparse + sparse
55678 c = algorithm07(x, y, xor);
55679 break;
55680 default:
55681 // sparse + dense
55682 c = algorithm03(y, x, xor, true);
55683 break;
55684 }
55685 break;
55686 default:
55687 switch (y.storage()) {
55688 case 'sparse':
55689 // dense + sparse
55690 c = algorithm03(x, y, xor, false);
55691 break;
55692 default:
55693 // dense + dense
55694 c = algorithm13(x, y, xor);
55695 break;
55696 }
55697 break;
55698 }
55699 return c;
55700 },
55701
55702 'Array, Array': function (x, y) {
55703 // use matrix implementation
55704 return xor(matrix(x), matrix(y)).valueOf();
55705 },
55706
55707 'Array, Matrix': function (x, y) {
55708 // use matrix implementation
55709 return xor(matrix(x), y);
55710 },
55711
55712 'Matrix, Array': function (x, y) {
55713 // use matrix implementation
55714 return xor(x, matrix(y));
55715 },
55716
55717 'Matrix, any': function (x, y) {
55718 // result
55719 var c;
55720 // check storage format
55721 switch (x.storage()) {
55722 case 'sparse':
55723 c = algorithm12(x, y, xor, false);
55724 break;
55725 default:
55726 c = algorithm14(x, y, xor, false);
55727 break;
55728 }
55729 return c;
55730 },
55731
55732 'any, Matrix': function (x, y) {
55733 // result
55734 var c;
55735 // check storage format
55736 switch (y.storage()) {
55737 case 'sparse':
55738 c = algorithm12(y, x, xor, true);
55739 break;
55740 default:
55741 c = algorithm14(y, x, xor, true);
55742 break;
55743 }
55744 return c;
55745 },
55746
55747 'Array, any': function (x, y) {
55748 // use matrix implementation
55749 return algorithm14(matrix(x), y, xor, false).valueOf();
55750 },
55751
55752 'any, Array': function (x, y) {
55753 // use matrix implementation
55754 return algorithm14(matrix(y), x, xor, true).valueOf();
55755 }
55756 });
55757
55758 xor.toTex = {
55759 2: '\\left(${args[0]}' + latex.operators['xor'] + '${args[1]}\\right)'
55760 };
55761
55762 return xor;
55763}
55764
55765exports.name = 'xor';
55766exports.factory = factory;
55767
55768
55769/***/ }),
55770/* 475 */
55771/***/ (function(module, exports, __webpack_require__) {
55772
55773module.exports = [
55774 __webpack_require__(64),
55775 __webpack_require__(476),
55776 __webpack_require__(117),
55777 __webpack_require__(477),
55778 __webpack_require__(478),
55779 __webpack_require__(62),
55780 __webpack_require__(479),
55781 __webpack_require__(480),
55782 __webpack_require__(481),
55783 __webpack_require__(116),
55784 __webpack_require__(482),
55785 __webpack_require__(142),
55786 __webpack_require__(483),
55787 __webpack_require__(89),
55788 __webpack_require__(119),
55789 __webpack_require__(484),
55790 __webpack_require__(485),
55791 __webpack_require__(29),
55792 __webpack_require__(143),
55793 __webpack_require__(487),
55794 __webpack_require__(23),
55795 __webpack_require__(138),
55796 __webpack_require__(67),
55797 __webpack_require__(40)
55798];
55799
55800
55801/***/ }),
55802/* 476 */
55803/***/ (function(module, exports, __webpack_require__) {
55804
55805"use strict";
55806
55807
55808var array = __webpack_require__(2);
55809
55810function factory (type, config, load, typed) {
55811 var matrix = load(__webpack_require__(0));
55812 var subtract = load(__webpack_require__(21));
55813 var multiply = load(__webpack_require__(12));
55814
55815 /**
55816 * Calculate the cross product for two vectors in three dimensional space.
55817 * The cross product of `A = [a1, a2, a3]` and `B = [b1, b2, b3]` is defined
55818 * as:
55819 *
55820 * cross(A, B) = [
55821 * a2 * b3 - a3 * b2,
55822 * a3 * b1 - a1 * b3,
55823 * a1 * b2 - a2 * b1
55824 * ]
55825 *
55826 * If one of the input vectors has a dimension greater than 1, the output
55827 * vector will be a 1x3 (2-dimensional) matrix.
55828 *
55829 * Syntax:
55830 *
55831 * math.cross(x, y)
55832 *
55833 * Examples:
55834 *
55835 * math.cross([1, 1, 0], [0, 1, 1]); // Returns [1, -1, 1]
55836 * math.cross([3, -3, 1], [4, 9, 2]); // Returns [-15, -2, 39]
55837 * math.cross([2, 3, 4], [5, 6, 7]); // Returns [-3, 6, -3]
55838 * math.cross([[1, 2, 3]], [[4], [5], [6]]); // Returns [[-3, 6, -3]]
55839 *
55840 * See also:
55841 *
55842 * dot, multiply
55843 *
55844 * @param {Array | Matrix} x First vector
55845 * @param {Array | Matrix} y Second vector
55846 * @return {Array | Matrix} Returns the cross product of `x` and `y`
55847 */
55848 var cross = typed('cross', {
55849 'Matrix, Matrix': function (x, y) {
55850 return matrix(_cross(x.toArray(), y.toArray()));
55851 },
55852
55853 'Matrix, Array': function (x, y) {
55854 return matrix(_cross(x.toArray(), y));
55855 },
55856
55857 'Array, Matrix': function (x, y) {
55858 return matrix(_cross(x, y.toArray()));
55859 },
55860
55861 'Array, Array': _cross
55862 });
55863
55864 cross.toTex = {
55865 2: '\\left(${args[0]}\\right)\\times\\left(${args[1]}\\right)'
55866 };
55867
55868 return cross;
55869
55870 /**
55871 * Calculate the cross product for two arrays
55872 * @param {Array} x First vector
55873 * @param {Array} y Second vector
55874 * @returns {Array} Returns the cross product of x and y
55875 * @private
55876 */
55877 function _cross(x, y) {
55878 var highestDimension = Math.max(array.size(x).length, array.size(y).length);
55879
55880 x = array.squeeze(x);
55881 y = array.squeeze(y);
55882
55883 var xSize = array.size(x);
55884 var ySize = array.size(y);
55885
55886 if (xSize.length != 1 || ySize.length != 1 || xSize[0] != 3 || ySize[0] != 3) {
55887 throw new RangeError('Vectors with length 3 expected ' +
55888 '(Size A = [' + xSize.join(', ') + '], B = [' + ySize.join(', ') + '])');
55889 }
55890
55891 var product = [
55892 subtract(multiply(x[1], y[2]), multiply(x[2], y[1])),
55893 subtract(multiply(x[2], y[0]), multiply(x[0], y[2])),
55894 subtract(multiply(x[0], y[1]), multiply(x[1], y[0]))
55895 ];
55896
55897 if (highestDimension > 1) {
55898 return [product];
55899 } else {
55900 return product;
55901 }
55902 }
55903}
55904
55905exports.name = 'cross';
55906exports.factory = factory;
55907
55908
55909/***/ }),
55910/* 477 */
55911/***/ (function(module, exports, __webpack_require__) {
55912
55913"use strict";
55914
55915
55916var array = __webpack_require__(2);
55917var clone = __webpack_require__(5).clone;
55918var isInteger = __webpack_require__(3).isInteger;
55919
55920function factory (type, config, load, typed) {
55921
55922 var matrix = load(__webpack_require__(0));
55923
55924 /**
55925 * Create a diagonal matrix or retrieve the diagonal of a matrix
55926 *
55927 * When `x` is a vector, a matrix with vector `x` on the diagonal will be returned.
55928 * When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector.
55929 * When k is positive, the values are placed on the super diagonal.
55930 * When k is negative, the values are placed on the sub diagonal.
55931 *
55932 * Syntax:
55933 *
55934 * math.diag(X)
55935 * math.diag(X, format)
55936 * math.diag(X, k)
55937 * math.diag(X, k, format)
55938 *
55939 * Examples:
55940 *
55941 * // create a diagonal matrix
55942 * math.diag([1, 2, 3]); // returns [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
55943 * math.diag([1, 2, 3], 1); // returns [[0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]
55944 * math.diag([1, 2, 3], -1); // returns [[0, 0, 0], [1, 0, 0], [0, 2, 0], [0, 0, 3]]
55945 *
55946 * // retrieve the diagonal from a matrix
55947 * var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
55948 * math.diag(a); // returns [1, 5, 9]
55949 *
55950 * See also:
55951 *
55952 * ones, zeros, eye
55953 *
55954 * @param {Matrix | Array} x A two dimensional matrix or a vector
55955 * @param {number | BigNumber} [k=0] The diagonal where the vector will be filled
55956 * in or retrieved.
55957 * @param {string} [format='dense'] The matrix storage format.
55958 *
55959 * @returns {Matrix | Array} Diagonal matrix from input vector, or diagonal from input matrix.
55960 */
55961 var diag = typed('diag', {
55962 // FIXME: simplify this huge amount of signatures as soon as typed-function supports optional arguments
55963
55964 'Array': function (x) {
55965 return _diag(x, 0, array.size(x), null);
55966 },
55967
55968 'Array, number': function (x, k) {
55969 return _diag(x, k, array.size(x), null);
55970 },
55971
55972 'Array, BigNumber': function (x, k) {
55973 return _diag(x, k.toNumber(), array.size(x), null);
55974 },
55975
55976 'Array, string': function (x, format) {
55977 return _diag(x, 0, array.size(x), format);
55978 },
55979
55980 'Array, number, string': function (x, k, format) {
55981 return _diag(x, k, array.size(x), format);
55982 },
55983
55984 'Array, BigNumber, string': function (x, k, format) {
55985 return _diag(x, k.toNumber(), array.size(x), format);
55986 },
55987
55988 'Matrix': function (x) {
55989 return _diag(x, 0, x.size(), x.storage());
55990 },
55991
55992 'Matrix, number': function (x, k) {
55993 return _diag(x, k, x.size(), x.storage());
55994 },
55995
55996 'Matrix, BigNumber': function (x, k) {
55997 return _diag(x, k.toNumber(), x.size(), x.storage());
55998 },
55999
56000 'Matrix, string': function (x, format) {
56001 return _diag(x, 0, x.size(), format);
56002 },
56003
56004 'Matrix, number, string': function (x, k, format) {
56005 return _diag(x, k, x.size(), format);
56006 },
56007
56008 'Matrix, BigNumber, string': function (x, k, format) {
56009 return _diag(x, k.toNumber(), x.size(), format);
56010 }
56011 });
56012
56013 diag.toTex = undefined; // use default template
56014
56015 return diag;
56016
56017 /**
56018 * Creeate diagonal matrix from a vector or vice versa
56019 * @param {Array | Matrix} x
56020 * @param {number} k
56021 * @param {string} format Storage format for matrix. If null,
56022 * an Array is returned
56023 * @returns {Array | Matrix}
56024 * @private
56025 */
56026 function _diag (x, k, size, format) {
56027 if (!isInteger(k)) {
56028 throw new TypeError ('Second parameter in function diag must be an integer');
56029 }
56030
56031 var kSuper = k > 0 ? k : 0;
56032 var kSub = k < 0 ? -k : 0;
56033
56034 // check dimensions
56035 switch (size.length) {
56036 case 1:
56037 return _createDiagonalMatrix(x, k, format, size[0], kSub, kSuper);
56038 case 2:
56039 return _getDiagonal(x, k, format, size, kSub, kSuper);
56040 }
56041 throw new RangeError('Matrix for function diag must be 2 dimensional');
56042 }
56043
56044 function _createDiagonalMatrix(x, k, format, l, kSub, kSuper) {
56045 // matrix size
56046 var ms = [l + kSub, l + kSuper];
56047 // get matrix constructor
56048 var F = type.Matrix.storage(format || 'dense');
56049 // create diagonal matrix
56050 var m = F.diagonal(ms, x, k);
56051 // check we need to return a matrix
56052 return format !== null ? m : m.valueOf();
56053 }
56054
56055 function _getDiagonal(x, k, format, s, kSub, kSuper) {
56056 // check x is a Matrix
56057 if (type.isMatrix(x)) {
56058 // get diagonal matrix
56059 var dm = x.diagonal(k);
56060 // check we need to return a matrix
56061 if (format !== null) {
56062 // check we need to change matrix format
56063 if (format !== dm.storage())
56064 return matrix(dm, format);
56065 return dm;
56066 }
56067 return dm.valueOf();
56068 }
56069 // vector size
56070 var n = Math.min(s[0] - kSub, s[1] - kSuper);
56071 // diagonal values
56072 var vector = [];
56073 // loop diagonal
56074 for (var i = 0; i < n; i++) {
56075 vector[i] = x[i + kSub][i + kSuper];
56076 }
56077 // check we need to return a matrix
56078 return format !== null ? matrix(vector) : vector;
56079 }
56080}
56081
56082exports.name = 'diag';
56083exports.factory = factory;
56084
56085
56086/***/ }),
56087/* 478 */
56088/***/ (function(module, exports, __webpack_require__) {
56089
56090"use strict";
56091
56092
56093var size = __webpack_require__(2).size;
56094
56095function factory (type, config, load, typed) {
56096 var add = load(__webpack_require__(20));
56097 var multiply = load(__webpack_require__(12));
56098
56099 /**
56100 * Calculate the dot product of two vectors. The dot product of
56101 * `A = [a1, a2, a3, ..., an]` and `B = [b1, b2, b3, ..., bn]` is defined as:
56102 *
56103 * dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn
56104 *
56105 * Syntax:
56106 *
56107 * math.dot(x, y)
56108 *
56109 * Examples:
56110 *
56111 * math.dot([2, 4, 1], [2, 2, 3]); // returns number 15
56112 * math.multiply([2, 4, 1], [2, 2, 3]); // returns number 15
56113 *
56114 * See also:
56115 *
56116 * multiply, cross
56117 *
56118 * @param {Array | Matrix} x First vector
56119 * @param {Array | Matrix} y Second vector
56120 * @return {number} Returns the dot product of `x` and `y`
56121 */
56122 var dot = typed('dot', {
56123 'Matrix, Matrix': function (x, y) {
56124 return _dot(x.toArray(), y.toArray());
56125 },
56126
56127 'Matrix, Array': function (x, y) {
56128 return _dot(x.toArray(), y);
56129 },
56130
56131 'Array, Matrix': function (x, y) {
56132 return _dot(x, y.toArray());
56133 },
56134
56135 'Array, Array': _dot
56136 });
56137
56138 dot.toTex = {2: '\\left(${args[0]}\\cdot${args[1]}\\right)'};
56139
56140 return dot;
56141
56142 /**
56143 * Calculate the dot product for two arrays
56144 * @param {Array} x First vector
56145 * @param {Array} y Second vector
56146 * @returns {number} Returns the dot product of x and y
56147 * @private
56148 */
56149 // TODO: double code with math.multiply
56150 function _dot(x, y) {
56151 var xSize= size(x);
56152 var ySize = size(y);
56153 var len = xSize[0];
56154
56155 if (xSize.length !== 1 || ySize.length !== 1) throw new RangeError('Vector expected'); // TODO: better error message
56156 if (xSize[0] != ySize[0]) throw new RangeError('Vectors must have equal length (' + xSize[0] + ' != ' + ySize[0] + ')');
56157 if (len == 0) throw new RangeError('Cannot calculate the dot product of empty vectors');
56158
56159 var prod = 0;
56160 for (var i = 0; i < len; i++) {
56161 prod = add(prod, multiply(x[i], y[i]));
56162 }
56163
56164 return prod;
56165 }
56166}
56167
56168exports.name = 'dot';
56169exports.factory = factory;
56170
56171
56172/***/ }),
56173/* 479 */
56174/***/ (function(module, exports, __webpack_require__) {
56175
56176"use strict";
56177
56178
56179var filter = __webpack_require__(2).filter;
56180var filterRegExp = __webpack_require__(2).filterRegExp;
56181var maxArgumentCount = __webpack_require__(32).maxArgumentCount;
56182
56183function factory (type, config, load, typed) {
56184 var matrix = load(__webpack_require__(0));
56185
56186 /**
56187 * Filter the items in an array or one dimensional matrix.
56188 *
56189 * Syntax:
56190 *
56191 * math.filter(x, test)
56192 *
56193 * Examples:
56194 *
56195 * function isPositive (x) {
56196 * return x > 0;
56197 * }
56198 * math.filter([6, -2, -1, 4, 3], isPositive); // returns [6, 4, 3]
56199 *
56200 * math.filter(["23", "foo", "100", "55", "bar"], /[0-9]+/); // returns ["23", "100", "55"]
56201 *
56202 * See also:
56203 *
56204 * forEach, map, sort
56205 *
56206 * @param {Matrix | Array} x A one dimensional matrix or array to filter
56207 * @param {Function | RegExp} test
56208 * A function or regular expression to test items.
56209 * All entries for which `test` returns true are returned.
56210 * When `test` is a function, it is invoked with three parameters:
56211 * the value of the element, the index of the element, and the
56212 * matrix/array being traversed. The function must return a boolean.
56213 * @return {Matrix | Array} Returns the filtered matrix.
56214 */
56215 var filter = typed('filter', {
56216 'Array, function': _filterCallback,
56217
56218 'Matrix, function': function (x, test) {
56219 return matrix(_filterCallback(x.toArray(), test));
56220 },
56221
56222 'Array, RegExp': filterRegExp,
56223
56224 'Matrix, RegExp': function (x, test) {
56225 return matrix(filterRegExp(x.toArray(), test));
56226 }
56227 });
56228
56229 filter.toTex = undefined; // use default template
56230
56231 return filter;
56232}
56233
56234/**
56235 * Filter values in a callback given a callback function
56236 * @param {Array} x
56237 * @param {Function} callback
56238 * @return {Array} Returns the filtered array
56239 * @private
56240 */
56241function _filterCallback (x, callback) {
56242 // figure out what number of arguments the callback function expects
56243 var args = maxArgumentCount(callback);
56244
56245 return filter(x, function (value, index, array) {
56246 // invoke the callback function with the right number of arguments
56247 if (args === 1) {
56248 return callback(value);
56249 }
56250 else if (args === 2) {
56251 return callback(value, [index]);
56252 }
56253 else { // 3 or -1
56254 return callback(value, [index], array);
56255 }
56256 });
56257}
56258
56259exports.name = 'filter';
56260exports.factory = factory;
56261
56262
56263/***/ }),
56264/* 480 */
56265/***/ (function(module, exports, __webpack_require__) {
56266
56267"use strict";
56268
56269
56270var clone = __webpack_require__(5).clone;
56271var _flatten = __webpack_require__(2).flatten;
56272
56273function factory (type, config, load, typed) {
56274 var matrix = load(__webpack_require__(0));
56275
56276 /**
56277 * Flatten a multi dimensional matrix into a single dimensional matrix.
56278 *
56279 * Syntax:
56280 *
56281 * math.flatten(x)
56282 *
56283 * Examples:
56284 *
56285 * math.flatten([[1,2], [3,4]]); // returns [1, 2, 3, 4]
56286 *
56287 * See also:
56288 *
56289 * concat, resize, size, squeeze
56290 *
56291 * @param {Matrix | Array} x Matrix to be flattened
56292 * @return {Matrix | Array} Returns the flattened matrix
56293 */
56294 var flatten = typed('flatten', {
56295 'Array': function (x) {
56296 return _flatten(clone(x));
56297 },
56298
56299 'Matrix': function (x) {
56300 var flat = _flatten(clone(x.toArray()));
56301 // TODO: return the same matrix type as x
56302 return matrix(flat);
56303 }
56304 });
56305
56306 flatten.toTex = undefined; // use default template
56307
56308 return flatten;
56309}
56310
56311exports.name = 'flatten';
56312exports.factory = factory;
56313
56314
56315/***/ }),
56316/* 481 */
56317/***/ (function(module, exports, __webpack_require__) {
56318
56319"use strict";
56320
56321
56322var maxArgumentCount = __webpack_require__(32).maxArgumentCount;
56323var forEach = __webpack_require__(2).forEach;
56324
56325function factory (type, config, load, typed) {
56326 /**
56327 * Iterate over all elements of a matrix/array, and executes the given callback function.
56328 *
56329 * Syntax:
56330 *
56331 * math.forEach(x, callback)
56332 *
56333 * Examples:
56334 *
56335 * math.forEach([1, 2, 3], function(value) {
56336 * console.log(value);
56337 * });
56338 * // outputs 1, 2, 3
56339 *
56340 * See also:
56341 *
56342 * filter, map, sort
56343 *
56344 * @param {Matrix | Array} x The matrix to iterate on.
56345 * @param {Function} callback The callback function is invoked with three
56346 * parameters: the value of the element, the index
56347 * of the element, and the Matrix/array being traversed.
56348 */
56349 var forEach = typed('forEach', {
56350 'Array, function': _forEach,
56351
56352 'Matrix, function': function (x, callback) {
56353 return x.forEach(callback);
56354 }
56355 });
56356
56357 forEach.toTex = undefined; // use default template
56358
56359 return forEach;
56360}
56361
56362/**
56363 * forEach for a multi dimensional array
56364 * @param {Array} array
56365 * @param {Function} callback
56366 * @private
56367 */
56368function _forEach (array, callback) {
56369 // figure out what number of arguments the callback function expects
56370 var args = maxArgumentCount(callback);
56371
56372 var recurse = function (value, index) {
56373 if (Array.isArray(value)) {
56374 forEach(value, function (child, i) {
56375 // we create a copy of the index array and append the new index value
56376 recurse(child, index.concat(i));
56377 });
56378 }
56379 else {
56380 // invoke the callback function with the right number of arguments
56381 if (args === 1) {
56382 callback(value);
56383 }
56384 else if (args === 2) {
56385 callback(value, index);
56386 }
56387 else { // 3 or -1
56388 callback(value, index, array);
56389 }
56390 }
56391 };
56392 recurse(array, []);
56393}
56394
56395exports.name = 'forEach';
56396exports.factory = factory;
56397
56398
56399/***/ }),
56400/* 482 */
56401/***/ (function(module, exports, __webpack_require__) {
56402
56403"use strict";
56404
56405
56406var size = __webpack_require__(2).size;
56407
56408function factory(type, config, load, typed) {
56409 var matrix = load(__webpack_require__(0));
56410 var multiplyScalar = load(__webpack_require__(22))
56411 /**
56412 * Calculates the kronecker product of 2 matrices or vectors.
56413 *
56414 * NOTE: If a one dimensional vector / matrix is given, it will be
56415 * wrapped so its two dimensions.
56416 * See the examples.
56417 *
56418 * Syntax:
56419 *
56420 * math.kron(x, y)
56421 *
56422 * Examples:
56423 *
56424 * math.kron([[1, 0], [0, 1]], [[1, 2], [3, 4]]);
56425 * // returns [ [ 1, 2, 0, 0 ], [ 3, 4, 0, 0 ], [ 0, 0, 1, 2 ], [ 0, 0, 3, 4 ] ]
56426 *
56427 * math.kron([1,1], [2,3,4]);
56428 * // returns [ [ 2, 3, 4, 2, 3, 4 ] ]
56429 *
56430 * See also:
56431 *
56432 * multiply, dot, cross
56433 *
56434 * @param {Array | Matrix} x First vector
56435 * @param {Array | Matrix} y Second vector
56436 * @return {Array | Matrix} Returns the kronecker product of `x` and `y`
56437 */
56438 var kron = typed('kron', {
56439 'Matrix, Matrix': function(x, y) {
56440 return matrix(_kron(x.toArray(), y.toArray()));
56441 },
56442
56443 'Matrix, Array': function(x, y) {
56444 return matrix(_kron(x.toArray(), y));
56445 },
56446
56447 'Array, Matrix': function(x, y) {
56448 return matrix(_kron(x, y.toArray()));
56449 },
56450
56451 'Array, Array': _kron
56452 });
56453
56454 return kron;
56455
56456 /**
56457 * Calculate the kronecker product of two matrices / vectors
56458 * @param {Array} a First vector
56459 * @param {Array} b Second vector
56460 * @returns {Array} Returns the kronecker product of x and y
56461 * @private
56462 */
56463 function _kron(a, b) {
56464 // Deal with the dimensions of the matricies.
56465 if (size(a).length === 1) {
56466 // Wrap it in a 2D Matrix
56467 a = [a];
56468 }
56469 if (size(b).length === 1) {
56470 // Wrap it in a 2D Matrix
56471 b = [b]
56472 }
56473 if (size(a).length > 2 || size(b).length > 2) {
56474 throw new RangeError('Vectors with dimensions greater then 2 are not supported expected ' +
56475 '(Size x = ' + JSON.stringify(a.length) + ', y = ' + JSON.stringify(b.length) + ')');
56476 }
56477 var t = [];
56478 var r = [];
56479
56480 return a.map(function(a) {
56481 return b.map(function(b) {
56482 return a.map(function(y) {
56483 return b.map(function(x) {
56484 return r.push(multiplyScalar(y, x));
56485 });
56486 }, t.push(r = []));
56487 });
56488 }, t = []) && t;
56489 }
56490}
56491
56492exports.name = 'kron';
56493exports.factory = factory;
56494
56495
56496/***/ }),
56497/* 483 */
56498/***/ (function(module, exports, __webpack_require__) {
56499
56500"use strict";
56501
56502
56503var isInteger = __webpack_require__(3).isInteger;
56504var resize = __webpack_require__(2).resize;
56505
56506function factory (type, config, load, typed) {
56507 var matrix = load(__webpack_require__(0));
56508
56509 /**
56510 * Create a matrix filled with ones. The created matrix can have one or
56511 * multiple dimensions.
56512 *
56513 * Syntax:
56514 *
56515 * math.ones(m)
56516 * math.ones(m, format)
56517 * math.ones(m, n)
56518 * math.ones(m, n, format)
56519 * math.ones([m, n])
56520 * math.ones([m, n], format)
56521 * math.ones([m, n, p, ...])
56522 * math.ones([m, n, p, ...], format)
56523 *
56524 * Examples:
56525 *
56526 * math.ones(3); // returns [1, 1, 1]
56527 * math.ones(3, 2); // returns [[1, 1], [1, 1], [1, 1]]
56528 * math.ones(3, 2, 'dense'); // returns Dense Matrix [[1, 1], [1, 1], [1, 1]]
56529 *
56530 * var A = [[1, 2, 3], [4, 5, 6]];
56531 * math.ones(math.size(A)); // returns [[1, 1, 1], [1, 1, 1]]
56532 *
56533 * See also:
56534 *
56535 * zeros, eye, size, range
56536 *
56537 * @param {...number | Array} size The size of each dimension of the matrix
56538 * @param {string} [format] The Matrix storage format
56539 *
56540 * @return {Array | Matrix | number} A matrix filled with ones
56541 */
56542 var ones = typed('ones', {
56543 '': function () {
56544 return (config.matrix === 'Array')
56545 ? _ones([])
56546 : _ones([], 'default');
56547 },
56548
56549 // math.ones(m, n, p, ..., format)
56550 // TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this
56551 '...number | BigNumber | string': function (size) {
56552 var last = size[size.length - 1];
56553 if (typeof last === 'string') {
56554 var format = size.pop();
56555 return _ones(size, format);
56556 }
56557 else if (config.matrix === 'Array') {
56558 return _ones(size);
56559 }
56560 else {
56561 return _ones(size, 'default');
56562 }
56563 },
56564
56565 'Array': _ones,
56566
56567 'Matrix': function (size) {
56568 var format = size.storage();
56569 return _ones(size.valueOf(), format);
56570 },
56571
56572 'Array | Matrix, string': function (size, format) {
56573 return _ones (size.valueOf(), format);
56574 }
56575 });
56576
56577 ones.toTex = undefined; // use default template
56578
56579 return ones;
56580
56581 /**
56582 * Create an Array or Matrix with ones
56583 * @param {Array} size
56584 * @param {string} [format='default']
56585 * @return {Array | Matrix}
56586 * @private
56587 */
56588 function _ones(size, format) {
56589 var hasBigNumbers = _normalize(size);
56590 var defaultValue = hasBigNumbers ? new type.BigNumber(1) : 1;
56591 _validate(size);
56592
56593 if (format) {
56594 // return a matrix
56595 var m = matrix(format);
56596 if (size.length > 0) {
56597 return m.resize(size, defaultValue);
56598 }
56599 return m;
56600 }
56601 else {
56602 // return an Array
56603 var arr = [];
56604 if (size.length > 0) {
56605 return resize(arr, size, defaultValue);
56606 }
56607 return arr;
56608 }
56609 }
56610
56611 // replace BigNumbers with numbers, returns true if size contained BigNumbers
56612 function _normalize(size) {
56613 var hasBigNumbers = false;
56614 size.forEach(function (value, index, arr) {
56615 if (type.isBigNumber(value)) {
56616 hasBigNumbers = true;
56617 arr[index] = value.toNumber();
56618 }
56619 });
56620 return hasBigNumbers;
56621 }
56622
56623 // validate arguments
56624 function _validate (size) {
56625 size.forEach(function (value) {
56626 if (typeof value !== 'number' || !isInteger(value) || value < 0) {
56627 throw new Error('Parameters in function ones must be positive integers');
56628 }
56629 });
56630 }
56631}
56632
56633exports.name = 'ones';
56634exports.factory = factory;
56635
56636
56637/***/ }),
56638/* 484 */
56639/***/ (function(module, exports, __webpack_require__) {
56640
56641"use strict";
56642
56643
56644var DimensionError = __webpack_require__(11);
56645
56646var isInteger = __webpack_require__(3).isInteger;
56647var array = __webpack_require__(2);
56648
56649function factory (type, config, load, typed) {
56650 var matrix = load(__webpack_require__(0));
56651
56652 /**
56653 * Reshape a multi dimensional array to fit the specified dimensions
56654 *
56655 * Syntax:
56656 *
56657 * math.reshape(x, sizes)
56658 *
56659 * Examples:
56660 *
56661 * math.reshape([1, 2, 3, 4, 5, 6], [2, 3]);
56662 * // returns Array [[1, 2, 3], [4, 5, 6]]
56663 *
56664 * math.reshape([[1, 2], [3, 4]], [1, 4]);
56665 * // returns Array [[1, 2, 3, 4]]
56666 *
56667 * math.reshape([[1, 2], [3, 4]], [4]);
56668 * // returns Array [1, 2, 3, 4]
56669 *
56670 * var x = math.matrix([1, 2, 3, 4, 5, 6, 7, 8]);
56671 * math.reshape(x, [2, 2, 2]);
56672 * // returns Matrix [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
56673 *
56674 * See also:
56675 *
56676 * size, squeeze, resize
56677 *
56678 * @param {Array | Matrix | *} x Matrix to be reshaped
56679 * @param {number[]} sizes One dimensional array with integral sizes for
56680 * each dimension
56681 *
56682 * @return {* | Array | Matrix} A reshaped clone of matrix `x`
56683 *
56684 * @throws {TypeError} If `sizes` does not contain solely integers
56685 * @throws {DimensionError} If the product of the new dimension sizes does
56686 * not equal that of the old ones
56687 */
56688 var reshape = typed('reshape', {
56689
56690 'Matrix, Array': function (x, sizes) {
56691 if(x.reshape) {
56692 return x.reshape(sizes);
56693 } else {
56694 return matrix(array.reshape(x.valueOf(), sizes));
56695 }
56696 },
56697
56698 'Array, Array': function (x, sizes) {
56699 sizes.forEach(function (size) {
56700 if (!isInteger(size)) {
56701 throw new TypeError('Invalid size for dimension: ' + size);
56702 }
56703 });
56704 return array.reshape(x, sizes);
56705 }
56706
56707 });
56708
56709 reshape.toTex = undefined; // use default template
56710
56711 return reshape;
56712}
56713
56714exports.name = 'reshape';
56715exports.factory = factory;
56716
56717
56718/***/ }),
56719/* 485 */
56720/***/ (function(module, exports, __webpack_require__) {
56721
56722"use strict";
56723
56724
56725var DimensionError = __webpack_require__(11);
56726var ArgumentsError = __webpack_require__(44);
56727
56728var isInteger = __webpack_require__(3).isInteger;
56729var format = __webpack_require__(9).format;
56730var clone = __webpack_require__(5).clone;
56731var array = __webpack_require__(2);
56732
56733function factory (type, config, load, typed) {
56734 var matrix = load(__webpack_require__(0));
56735
56736 /**
56737 * Resize a matrix
56738 *
56739 * Syntax:
56740 *
56741 * math.resize(x, size)
56742 * math.resize(x, size, defaultValue)
56743 *
56744 * Examples:
56745 *
56746 * math.resize([1, 2, 3, 4, 5], [3]); // returns Array [1, 2, 3]
56747 * math.resize([1, 2, 3], [5], 0); // returns Array [1, 2, 3, 0, 0]
56748 * math.resize(2, [2, 3], 0); // returns Matrix [[2, 0, 0], [0, 0, 0]]
56749 * math.resize("hello", [8], "!"); // returns string 'hello!!!'
56750 *
56751 * See also:
56752 *
56753 * size, squeeze, subset, reshape
56754 *
56755 * @param {Array | Matrix | *} x Matrix to be resized
56756 * @param {Array | Matrix} size One dimensional array with numbers
56757 * @param {number | string} [defaultValue=0] Zero by default, except in
56758 * case of a string, in that case
56759 * defaultValue = ' '
56760 * @return {* | Array | Matrix} A resized clone of matrix `x`
56761 */
56762 // TODO: rework resize to a typed-function
56763 var resize = function resize (x, size, defaultValue) {
56764 if (arguments.length != 2 && arguments.length != 3) {
56765 throw new ArgumentsError('resize', arguments.length, 2, 3);
56766 }
56767
56768 if (type.isMatrix(size)) {
56769 size = size.valueOf(); // get Array
56770 }
56771
56772 if (type.isBigNumber(size[0])) {
56773 // convert bignumbers to numbers
56774 size = size.map(function (value) {
56775 return type.isBigNumber(value) ? value.toNumber() : value;
56776 });
56777 }
56778
56779 // check x is a Matrix
56780 if (type.isMatrix(x)) {
56781 // use optimized matrix implementation, return copy
56782 return x.resize(size, defaultValue, true);
56783 }
56784
56785 if (typeof x === 'string') {
56786 // resize string
56787 return _resizeString(x, size, defaultValue);
56788 }
56789
56790 // check result should be a matrix
56791 var asMatrix = Array.isArray(x) ? false : (config.matrix !== 'Array');
56792
56793 if (size.length == 0) {
56794 // output a scalar
56795 while (Array.isArray(x)) {
56796 x = x[0];
56797 }
56798
56799 return clone(x);
56800 }
56801 else {
56802 // output an array/matrix
56803 if (!Array.isArray(x)) {
56804 x = [x];
56805 }
56806 x = clone(x);
56807
56808 var res = array.resize(x, size, defaultValue);
56809 return asMatrix ? matrix(res) : res;
56810 }
56811 };
56812
56813 resize.toTex = undefined; // use default template
56814
56815 return resize;
56816
56817 /**
56818 * Resize a string
56819 * @param {string} str
56820 * @param {number[]} size
56821 * @param {string} [defaultChar=' ']
56822 * @private
56823 */
56824 function _resizeString(str, size, defaultChar) {
56825 if (defaultChar !== undefined) {
56826 if (typeof defaultChar !== 'string' || defaultChar.length !== 1) {
56827 throw new TypeError('Single character expected as defaultValue');
56828 }
56829 }
56830 else {
56831 defaultChar = ' ';
56832 }
56833
56834 if (size.length !== 1) {
56835 throw new DimensionError(size.length, 1);
56836 }
56837 var len = size[0];
56838 if (typeof len !== 'number' || !isInteger(len)) {
56839 throw new TypeError('Invalid size, must contain positive integers ' +
56840 '(size: ' + format(size) + ')');
56841 }
56842
56843 if (str.length > len) {
56844 return str.substring(0, len);
56845 }
56846 else if (str.length < len) {
56847 var res = str;
56848 for (var i = 0, ii = len - str.length; i < ii; i++) {
56849 res += defaultChar;
56850 }
56851 return res;
56852 }
56853 else {
56854 return str;
56855 }
56856 }
56857}
56858
56859exports.name = 'resize';
56860exports.factory = factory;
56861
56862
56863/***/ }),
56864/* 486 */
56865/***/ (function(module, exports) {
56866
56867/*
56868 * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
56869 * Author: Jim Palmer (based on chunking idea from Dave Koelle)
56870 */
56871/*jshint unused:false */
56872module.exports = function naturalSort (a, b) {
56873 "use strict";
56874 var re = /(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,
56875 sre = /(^[ ]*|[ ]*$)/g,
56876 dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
56877 hre = /^0x[0-9a-f]+$/i,
56878 ore = /^0/,
56879 i = function(s) { return naturalSort.insensitive && ('' + s).toLowerCase() || '' + s; },
56880 // convert all to strings strip whitespace
56881 x = i(a).replace(sre, '') || '',
56882 y = i(b).replace(sre, '') || '',
56883 // chunk/tokenize
56884 xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
56885 yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
56886 // numeric, hex or date detection
56887 xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && x.match(dre) && Date.parse(x)),
56888 yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null,
56889 oFxNcL, oFyNcL;
56890 // first try and sort Hex codes or Dates
56891 if (yD) {
56892 if ( xD < yD ) { return -1; }
56893 else if ( xD > yD ) { return 1; }
56894 }
56895 // natural sorting through split numeric strings and default strings
56896 for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
56897 // find floats not starting with '0', string or 0 if not defined (Clint Priest)
56898 oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
56899 oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
56900 // handle numeric vs string comparison - number < string - (Kyle Adams)
56901 if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; }
56902 // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
56903 else if (typeof oFxNcL !== typeof oFyNcL) {
56904 oFxNcL += '';
56905 oFyNcL += '';
56906 }
56907 if (oFxNcL < oFyNcL) { return -1; }
56908 if (oFxNcL > oFyNcL) { return 1; }
56909 }
56910 return 0;
56911};
56912
56913
56914/***/ }),
56915/* 487 */
56916/***/ (function(module, exports, __webpack_require__) {
56917
56918"use strict";
56919
56920
56921var object = __webpack_require__(5);
56922var array = __webpack_require__(2);
56923
56924function factory (type, config, load, typed) {
56925 var matrix = load(__webpack_require__(0));
56926
56927 /**
56928 * Squeeze a matrix, remove inner and outer singleton dimensions from a matrix.
56929 *
56930 * Syntax:
56931 *
56932 * math.squeeze(x)
56933 *
56934 * Examples:
56935 *
56936 * math.squeeze([3]); // returns 3
56937 * math.squeeze([[3]]); // returns 3
56938 *
56939 * var A = math.zeros(3, 1); // returns [[0], [0], [0]] (size 3x1)
56940 * math.squeeze(A); // returns [0, 0, 0] (size 3)
56941 *
56942 * var B = math.zeros(1, 3); // returns [[0, 0, 0]] (size 1x3)
56943 * math.squeeze(B); // returns [0, 0, 0] (size 3)
56944 *
56945 * // only inner and outer dimensions are removed
56946 * var C = math.zeros(2, 1, 3); // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3)
56947 * math.squeeze(C); // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3)
56948 *
56949 * See also:
56950 *
56951 * subset
56952 *
56953 * @param {Matrix | Array} x Matrix to be squeezed
56954 * @return {Matrix | Array} Squeezed matrix
56955 */
56956 var squeeze = typed('squeeze', {
56957 'Array': function (x) {
56958 return array.squeeze(object.clone(x));
56959 },
56960
56961 'Matrix': function (x) {
56962 var res = array.squeeze(x.toArray());
56963 // FIXME: return the same type of matrix as the input
56964 return Array.isArray(res) ? matrix(res) : res;
56965 },
56966
56967 'any': function (x) {
56968 // scalar
56969 return object.clone(x);
56970 }
56971 });
56972
56973 squeeze.toTex = undefined; // use default template
56974
56975 return squeeze;
56976}
56977
56978exports.name = 'squeeze';
56979exports.factory = factory;
56980
56981
56982/***/ }),
56983/* 488 */
56984/***/ (function(module, exports, __webpack_require__) {
56985
56986module.exports = [
56987 //require('./distribution'), // TODO: rethink math.distribution
56988 __webpack_require__(70),
56989 __webpack_require__(69),
56990 __webpack_require__(140),
56991 __webpack_require__(489),
56992 __webpack_require__(490),
56993 __webpack_require__(491),
56994 __webpack_require__(492),
56995 __webpack_require__(496),
56996 __webpack_require__(497)
56997];
56998
56999
57000/***/ }),
57001/* 489 */
57002/***/ (function(module, exports, __webpack_require__) {
57003
57004"use strict";
57005
57006
57007
57008function factory(type, config, load, typed) {
57009 var matrix = load(__webpack_require__(0));
57010 var divide = load(__webpack_require__(49));
57011 var sum = load(__webpack_require__(144));
57012 var multiply = load(__webpack_require__(12));
57013 var dotDivide = load(__webpack_require__(135));
57014 var log = load(__webpack_require__(137));
57015 var isNumeric = load(__webpack_require__(75));
57016
57017 /**
57018 * Calculate the Kullback-Leibler (KL) divergence between two distributions
57019 *
57020 * Syntax:
57021 *
57022 * math.kldivergence(x, y)
57023 *
57024 * Examples:
57025 *
57026 * math.kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5]); //returns 0.24376698773121153
57027 *
57028 *
57029 * @param {Array | Matrix} q First vector
57030 * @param {Array | Matrix} p Second vector
57031 * @return {number} Returns distance between q and p
57032 */
57033 var kldivergence = typed('kldivergence', {
57034 'Array, Array': function(q, p) {
57035 return _kldiv(matrix(q), matrix(p));
57036 },
57037
57038 'Matrix, Array': function(q, p) {
57039 return _kldiv(q, matrix(p));
57040 },
57041
57042 'Array, Matrix': function(q, p){
57043 return _kldiv(matrix(q), p);
57044 },
57045
57046 'Matrix, Matrix': function(q, p){
57047 return _kldiv(q, p);
57048 }
57049
57050 });
57051
57052 function _kldiv(q, p) {
57053 var plength = p.size().length;
57054 var qlength = q.size().length;
57055 if (plength > 1) {
57056 throw new Error('first object must be one dimensional');
57057 }
57058
57059 if (qlength > 1) {
57060 throw new Error('second object must be one dimensional');
57061 }
57062
57063 if(plength !== qlength){
57064 throw new Error("Length of two vectors must be equal");
57065 }
57066
57067 //Before calculation, apply normalization
57068 var sumq = sum(q);
57069 if (sumq === 0) {
57070 throw new Error("Sum of elements in first object must be non zero");
57071 }
57072
57073 var sump = sum(p);
57074 if (sump === 0) {
57075 throw new Error("Sum of elements in second object must be non zero");
57076 }
57077 var qnorm = divide(q, sum(q));
57078 var pnorm = divide(p, sum(p));
57079
57080 var result = sum(multiply(qnorm, log(dotDivide(qnorm, pnorm))));
57081 if (isNumeric(result)) {
57082 return result;
57083 }
57084 else {
57085 return Number.NaN;
57086 }
57087 }
57088
57089 return kldivergence;
57090}
57091
57092
57093exports.name = 'kldivergence';
57094exports.factory = factory;
57095
57096
57097
57098/***/ }),
57099/* 490 */
57100/***/ (function(module, exports, __webpack_require__) {
57101
57102"use strict";
57103
57104
57105var deepForEach = __webpack_require__(43);
57106
57107function factory (type, config, load, typed) {
57108 var add = load(__webpack_require__(20));
57109 var multiply = load(__webpack_require__(12));
57110 var divide = load(__webpack_require__(49));
57111 var factorial = load(__webpack_require__(69));
57112 var isInteger = load(__webpack_require__(51));
57113 var isPositive = load(__webpack_require__(57));
57114
57115 /**
57116 * Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities.
57117 *
57118 * multinomial takes one array of integers as an argument.
57119 * The following condition must be enforced: every ai <= 0
57120 *
57121 * Syntax:
57122 *
57123 * math.multinomial(a) // a is an array type
57124 *
57125 * Examples:
57126 *
57127 * math.multinomial([1,2,1]); // returns 12
57128 *
57129 * See also:
57130 *
57131 * combinations, factorial
57132 *
57133 * @param {number[] | BigNumber[]} a Integer numbers of objects in the subset
57134 * @return {Number | BigNumber} Multinomial coefficient.
57135 */
57136 return typed('multinomial', {
57137 'Array | Matrix': function (a) {
57138 var sum = 0;
57139 var denom = 1;
57140
57141 deepForEach(a, function(ai) {
57142 if(!isInteger(ai) || !isPositive(ai)) {
57143 throw new TypeError('Positive integer value expected in function multinomial');
57144 }
57145 sum = add(sum, ai);
57146 denom = multiply(denom, factorial(ai));
57147 });
57148
57149 return divide(factorial(sum), denom);
57150 }
57151 });
57152}
57153
57154exports.name = 'multinomial';
57155exports.factory = factory;
57156
57157
57158/***/ }),
57159/* 491 */
57160/***/ (function(module, exports, __webpack_require__) {
57161
57162"use strict";
57163
57164
57165var isInteger = __webpack_require__(3).isInteger;
57166
57167function factory (type, config, load, typed) {
57168 var factorial = load(__webpack_require__(69));
57169
57170 /**
57171 * Compute the number of ways of obtaining an ordered subset of `k` elements
57172 * from a set of `n` elements.
57173 *
57174 * Permutations only takes integer arguments.
57175 * The following condition must be enforced: k <= n.
57176 *
57177 * Syntax:
57178 *
57179 * math.permutations(n)
57180 * math.permutations(n, k)
57181 *
57182 * Examples:
57183 *
57184 * math.permutations(5); // 120
57185 * math.permutations(5, 3); // 60
57186 *
57187 * See also:
57188 *
57189 * combinations, factorial
57190 *
57191 * @param {number | BigNumber} n The number of objects in total
57192 * @param {number | BigNumber} [k] The number of objects in the subset
57193 * @return {number | BigNumber} The number of permutations
57194 */
57195 var permutations = typed('permutations', {
57196 'number | BigNumber': factorial,
57197
57198 'number, number': function (n, k) {
57199 var result, i;
57200
57201 if (!isInteger(n) || n < 0) {
57202 throw new TypeError('Positive integer value expected in function permutations');
57203 }
57204 if (!isInteger(k) || k < 0) {
57205 throw new TypeError('Positive integer value expected in function permutations');
57206 }
57207 if (k > n) {
57208 throw new TypeError('second argument k must be less than or equal to first argument n');
57209 }
57210
57211 // Permute n objects, k at a time
57212 result = 1;
57213 for (i = n - k + 1; i <= n; i++) {
57214 result = result * i;
57215 }
57216
57217 return result;
57218 },
57219
57220 'BigNumber, BigNumber': function (n, k) {
57221 var result, i;
57222
57223 if (!isPositiveInteger(n) || !isPositiveInteger(k)) {
57224 throw new TypeError('Positive integer value expected in function permutations');
57225 }
57226 if (k.gt(n)) {
57227 throw new TypeError('second argument k must be less than or equal to first argument n');
57228 }
57229
57230 result = new type.BigNumber(1);
57231 for (i = n.minus(k).plus(1); i.lte(n); i = i.plus(1)) {
57232 result = result.times(i);
57233 }
57234
57235 return result;
57236 }
57237
57238 // TODO: implement support for collection in permutations
57239 });
57240
57241 permutations.toTex = undefined; // use default template
57242
57243 return permutations;
57244}
57245
57246/**
57247 * Test whether BigNumber n is a positive integer
57248 * @param {BigNumber} n
57249 * @returns {boolean} isPositiveInteger
57250 */
57251function isPositiveInteger(n) {
57252 return n.isInteger() && n.gte(0);
57253}
57254
57255exports.name = 'permutations';
57256exports.factory = factory;
57257
57258
57259/***/ }),
57260/* 492 */
57261/***/ (function(module, exports, __webpack_require__) {
57262
57263"use strict";
57264
57265
57266function factory (type, config, load, typed) {
57267 var distribution = load(__webpack_require__(90));
57268
57269 /**
57270 * Random pick one or more values from a one dimensional array.
57271 * Array elements are picked using a random function with uniform or weighted distribution.
57272 *
57273 * Syntax:
57274 *
57275 * math.pickRandom(array)
57276 * math.pickRandom(array, number)
57277 * math.pickRandom(array, weights)
57278 * math.pickRandom(array, number, weights)
57279 * math.pickRandom(array, weights, number)
57280 *
57281 * Examples:
57282 *
57283 * math.pickRandom([3, 6, 12, 2]); // returns one of the values in the array
57284 * math.pickRandom([3, 6, 12, 2], 2); // returns an array of two of the values in the array
57285 * math.pickRandom([3, 6, 12, 2], [1, 3, 2, 1]); // returns one of the values in the array with weighted distribution
57286 * 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
57287 * 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
57288 *
57289 * See also:
57290 *
57291 * random, randomInt
57292 *
57293 * @param {Array} array A one dimensional array
57294 * @param {Int} number An int or float
57295 * @param {Array} weights An array of ints or floats
57296 * @return {number | Array} Returns a single random value from array when number is 1 or undefined.
57297 * Returns an array with the configured number of elements when number is > 1.
57298 */
57299 // TODO: rework pickRandom to a typed-function
57300 var pickRandom = distribution('uniform').pickRandom;
57301
57302 pickRandom.toTex = undefined; // use default template
57303
57304 return pickRandom;
57305}
57306
57307exports.name = 'pickRandom';
57308exports.factory = factory;
57309
57310
57311/***/ }),
57312/* 493 */
57313/***/ (function(module, exports, __webpack_require__) {
57314
57315"use strict";
57316
57317
57318var seedrandom = __webpack_require__(494);
57319
57320// create a random seed here to prevent an infinite loop from seed-random
57321// inside the factory. Reason is that math.random is defined as a getter/setter
57322// and seed-random generates a seed from the local entropy by reading every
57323// defined object including `math` itself. That means that whilst getting
57324// math.random, it tries to get math.random, etc... an infinite loop.
57325// See https://github.com/ForbesLindesay/seed-random/issues/6
57326var singletonRandom = seedrandom();
57327
57328function factory (type, config, load, typed, math) {
57329 var random;
57330
57331 // create a new random generator with given seed
57332 function setSeed (seed) {
57333 random = seed === null ? singletonRandom : seedrandom(String(seed));
57334 }
57335
57336 // initialize a seeded pseudo random number generator with config's random seed
57337 setSeed(config.randomSeed)
57338
57339 // wrapper function so the rng can be updated via generator
57340 function rng() {
57341 return random();
57342 }
57343
57344 // updates generator with a new instance of a seeded pseudo random number generator
57345 math.on('config', function (curr, prev, changes) {
57346 // if the user specified a randomSeed
57347 if(changes.randomSeed !== undefined) {
57348 // update generator with a new instance of a seeded pseudo random number generator
57349 setSeed(curr.randomSeed)
57350 }
57351 });
57352
57353 return rng;
57354}
57355
57356exports.factory = factory;
57357exports.math = true;
57358
57359
57360/***/ }),
57361/* 494 */
57362/***/ (function(module, exports, __webpack_require__) {
57363
57364"use strict";
57365/* WEBPACK VAR INJECTION */(function(global) {
57366
57367var width = 256;// each RC4 output is 0 <= x < 256
57368var chunks = 6;// at least six RC4 outputs for each double
57369var digits = 52;// there are 52 significant digits in a double
57370var pool = [];// pool: entropy pool starts empty
57371var GLOBAL = typeof global === 'undefined' ? window : global;
57372
57373//
57374// The following constants are related to IEEE 754 limits.
57375//
57376var startdenom = Math.pow(width, chunks),
57377 significance = Math.pow(2, digits),
57378 overflow = significance * 2,
57379 mask = width - 1;
57380
57381
57382var oldRandom = Math.random;
57383
57384//
57385// seedrandom()
57386// This is the seedrandom function described above.
57387//
57388module.exports = function(seed, options) {
57389 if (options && options.global === true) {
57390 options.global = false;
57391 Math.random = module.exports(seed, options);
57392 options.global = true;
57393 return Math.random;
57394 }
57395 var use_entropy = (options && options.entropy) || false;
57396 var key = [];
57397
57398 // Flatten the seed string or build one from local entropy if needed.
57399 var shortseed = mixkey(flatten(
57400 use_entropy ? [seed, tostring(pool)] :
57401 0 in arguments ? seed : autoseed(), 3), key);
57402
57403 // Use the seed to initialize an ARC4 generator.
57404 var arc4 = new ARC4(key);
57405
57406 // Mix the randomness into accumulated entropy.
57407 mixkey(tostring(arc4.S), pool);
57408
57409 // Override Math.random
57410
57411 // This function returns a random double in [0, 1) that contains
57412 // randomness in every bit of the mantissa of the IEEE 754 value.
57413
57414 return function() { // Closure to return a random double:
57415 var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
57416 d = startdenom, // and denominator d = 2 ^ 48.
57417 x = 0; // and no 'extra last byte'.
57418 while (n < significance) { // Fill up all significant digits by
57419 n = (n + x) * width; // shifting numerator and
57420 d *= width; // denominator and generating a
57421 x = arc4.g(1); // new least-significant-byte.
57422 }
57423 while (n >= overflow) { // To avoid rounding up, before adding
57424 n /= 2; // last byte, shift everything
57425 d /= 2; // right using integer Math until
57426 x >>>= 1; // we have exactly the desired bits.
57427 }
57428 return (n + x) / d; // Form the number within [0, 1).
57429 };
57430};
57431
57432module.exports.resetGlobal = function () {
57433 Math.random = oldRandom;
57434};
57435
57436//
57437// ARC4
57438//
57439// An ARC4 implementation. The constructor takes a key in the form of
57440// an array of at most (width) integers that should be 0 <= x < (width).
57441//
57442// The g(count) method returns a pseudorandom integer that concatenates
57443// the next (count) outputs from ARC4. Its return value is a number x
57444// that is in the range 0 <= x < (width ^ count).
57445//
57446/** @constructor */
57447function ARC4(key) {
57448 var t, keylen = key.length,
57449 me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
57450
57451 // The empty key [] is treated as [0].
57452 if (!keylen) { key = [keylen++]; }
57453
57454 // Set up S using the standard key scheduling algorithm.
57455 while (i < width) {
57456 s[i] = i++;
57457 }
57458 for (i = 0; i < width; i++) {
57459 s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
57460 s[j] = t;
57461 }
57462
57463 // The "g" method returns the next (count) outputs as one number.
57464 (me.g = function(count) {
57465 // Using instance members instead of closure state nearly doubles speed.
57466 var t, r = 0,
57467 i = me.i, j = me.j, s = me.S;
57468 while (count--) {
57469 t = s[i = mask & (i + 1)];
57470 r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
57471 }
57472 me.i = i; me.j = j;
57473 return r;
57474 // For robust unpredictability discard an initial batch of values.
57475 // See http://www.rsa.com/rsalabs/node.asp?id=2009
57476 })(width);
57477}
57478
57479//
57480// flatten()
57481// Converts an object tree to nested arrays of strings.
57482//
57483function flatten(obj, depth) {
57484 var result = [], typ = (typeof obj)[0], prop;
57485 if (depth && typ == 'o') {
57486 for (prop in obj) {
57487 try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
57488 }
57489 }
57490 return (result.length ? result : typ == 's' ? obj : obj + '\0');
57491}
57492
57493//
57494// mixkey()
57495// Mixes a string seed into a key that is an array of integers, and
57496// returns a shortened string seed that is equivalent to the result key.
57497//
57498function mixkey(seed, key) {
57499 var stringseed = seed + '', smear, j = 0;
57500 while (j < stringseed.length) {
57501 key[mask & j] =
57502 mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
57503 }
57504 return tostring(key);
57505}
57506
57507//
57508// autoseed()
57509// Returns an object for autoseeding, using window.crypto if available.
57510//
57511/** @param {Uint8Array=} seed */
57512function autoseed(seed) {
57513 try {
57514 GLOBAL.crypto.getRandomValues(seed = new Uint8Array(width));
57515 return tostring(seed);
57516 } catch (e) {
57517 return [+new Date, GLOBAL, GLOBAL.navigator && GLOBAL.navigator.plugins,
57518 GLOBAL.screen, tostring(pool)];
57519 }
57520}
57521
57522//
57523// tostring()
57524// Converts an array of charcodes to a string
57525//
57526function tostring(a) {
57527 return String.fromCharCode.apply(0, a);
57528}
57529
57530//
57531// When seedrandom.js is loaded, we immediately mix a few bits
57532// from the built-in RNG into the entropy pool. Because we do
57533// not want to intefere with determinstic PRNG state later,
57534// seedrandom will not call Math.random on its own again after
57535// initialization.
57536//
57537mixkey(Math.random(), pool);
57538
57539/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(495)))
57540
57541/***/ }),
57542/* 495 */
57543/***/ (function(module, exports) {
57544
57545var g;
57546
57547// This works in non-strict mode
57548g = (function() {
57549 return this;
57550})();
57551
57552try {
57553 // This works if eval is allowed (see CSP)
57554 g = g || Function("return this")() || (1,eval)("this");
57555} catch(e) {
57556 // This works if the window reference is available
57557 if(typeof window === "object")
57558 g = window;
57559}
57560
57561// g can still be undefined, but nothing to do about it...
57562// We return undefined, instead of nothing here, so it's
57563// easier to handle this case. if(!global) { ...}
57564
57565module.exports = g;
57566
57567
57568/***/ }),
57569/* 496 */
57570/***/ (function(module, exports, __webpack_require__) {
57571
57572"use strict";
57573
57574
57575function factory (type, config, load, typed) {
57576 var distribution = load(__webpack_require__(90));
57577
57578 /**
57579 * Return a random number larger or equal to `min` and smaller than `max`
57580 * using a uniform distribution.
57581 *
57582 * Syntax:
57583 *
57584 * math.random() // generate a random number between 0 and 1
57585 * math.random(max) // generate a random number between 0 and max
57586 * math.random(min, max) // generate a random number between min and max
57587 * math.random(size) // generate a matrix with random numbers between 0 and 1
57588 * math.random(size, max) // generate a matrix with random numbers between 0 and max
57589 * math.random(size, min, max) // generate a matrix with random numbers between min and max
57590 *
57591 * Examples:
57592 *
57593 * math.random(); // returns a random number between 0 and 1
57594 * math.random(100); // returns a random number between 0 and 100
57595 * math.random(30, 40); // returns a random number between 30 and 40
57596 * math.random([2, 3]); // returns a 2x3 matrix with random numbers between 0 and 1
57597 *
57598 * See also:
57599 *
57600 * randomInt, pickRandom
57601 *
57602 * @param {Array | Matrix} [size] If provided, an array or matrix with given
57603 * size and filled with random values is returned
57604 * @param {number} [min] Minimum boundary for the random value, included
57605 * @param {number} [max] Maximum boundary for the random value, excluded
57606 * @return {number | Array | Matrix} A random number
57607 */
57608 // TODO: rework random to a typed-function
57609 var random = distribution('uniform').random;
57610
57611 random.toTex = undefined; // use default template
57612
57613 return random;
57614}
57615
57616exports.name = 'random';
57617exports.factory = factory;
57618
57619
57620/***/ }),
57621/* 497 */
57622/***/ (function(module, exports, __webpack_require__) {
57623
57624"use strict";
57625
57626
57627function factory (type, config, load, typed) {
57628 var distribution = load(__webpack_require__(90));
57629
57630 /**
57631 * Return a random integer number larger or equal to `min` and smaller than `max`
57632 * using a uniform distribution.
57633 *
57634 * Syntax:
57635 *
57636 * math.randomInt(max) // generate a random integer between 0 and max
57637 * math.randomInt(min, max) // generate a random integer between min and max
57638 * math.randomInt(size) // generate a matrix with random integer between 0 and 1
57639 * math.randomInt(size, max) // generate a matrix with random integer between 0 and max
57640 * math.randomInt(size, min, max) // generate a matrix with random integer between min and max
57641 *
57642 * Examples:
57643 *
57644 * math.randomInt(100); // returns a random integer between 0 and 100
57645 * math.randomInt(30, 40); // returns a random integer between 30 and 40
57646 * math.randomInt([2, 3]); // returns a 2x3 matrix with random integers between 0 and 1
57647 *
57648 * See also:
57649 *
57650 * random, pickRandom
57651 *
57652 * @param {Array | Matrix} [size] If provided, an array or matrix with given
57653 * size and filled with random values is returned
57654 * @param {number} [min] Minimum boundary for the random value, included
57655 * @param {number} [max] Maximum boundary for the random value, excluded
57656 * @return {number | Array | Matrix} A random integer value
57657 */
57658 // TODO: rework randomInt to a typed-function
57659 var randomInt = distribution('uniform').randomInt;
57660
57661 randomInt.toTex = undefined; // use default template
57662
57663 return randomInt;
57664}
57665
57666exports.name = 'randomInt';
57667exports.factory = factory;
57668
57669
57670/***/ }),
57671/* 498 */
57672/***/ (function(module, exports, __webpack_require__) {
57673
57674module.exports = [
57675 __webpack_require__(52),
57676 __webpack_require__(31),
57677 __webpack_require__(499),
57678 __webpack_require__(30),
57679 __webpack_require__(34),
57680 __webpack_require__(130),
57681 __webpack_require__(39),
57682 __webpack_require__(500),
57683 __webpack_require__(124)
57684];
57685
57686
57687/***/ }),
57688/* 499 */
57689/***/ (function(module, exports, __webpack_require__) {
57690
57691"use strict";
57692
57693
57694function factory (type, config, load, typed) {
57695 var equal = load(__webpack_require__(30));
57696
57697 /**
57698 * Test element wise whether two matrices are equal.
57699 * The function accepts both matrices and scalar values.
57700 *
57701 * Syntax:
57702 *
57703 * math.deepEqual(x, y)
57704 *
57705 * Examples:
57706 *
57707 * math.deepEqual(2, 4); // returns false
57708 *
57709 * a = [2, 5, 1];
57710 * b = [2, 7, 1];
57711 *
57712 * math.deepEqual(a, b); // returns false
57713 * math.equal(a, b); // returns [true, false, true]
57714 *
57715 * See also:
57716 *
57717 * equal, unequal
57718 *
57719 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First matrix to compare
57720 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second matrix to compare
57721 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix}
57722 * Returns true when the input matrices have the same size and each of their elements is equal.
57723 */
57724 var deepEqual = typed('deepEqual', {
57725 'any, any': function (x, y) {
57726 return _deepEqual(x.valueOf(), y.valueOf());
57727 }
57728 });
57729
57730 deepEqual.toTex = undefined; // use default template
57731
57732 return deepEqual;
57733
57734 /**
57735 * Test whether two arrays have the same size and all elements are equal
57736 * @param {Array | *} x
57737 * @param {Array | *} y
57738 * @return {boolean} Returns true if both arrays are deep equal
57739 */
57740 function _deepEqual(x, y) {
57741 if (Array.isArray(x)) {
57742 if (Array.isArray(y)) {
57743 var len = x.length;
57744 if (len !== y.length) {
57745 return false;
57746 }
57747
57748 for (var i = 0; i < len; i++) {
57749 if (!_deepEqual(x[i], y[i])) {
57750 return false;
57751 }
57752 }
57753
57754 return true;
57755 }
57756 else {
57757 return false;
57758 }
57759 }
57760 else {
57761 if (Array.isArray(y)) {
57762 return false;
57763 }
57764 else {
57765 return equal(x, y);
57766 }
57767 }
57768 }
57769}
57770
57771exports.name = 'deepEqual';
57772exports.factory = factory;
57773
57774
57775/***/ }),
57776/* 500 */
57777/***/ (function(module, exports, __webpack_require__) {
57778
57779"use strict";
57780
57781
57782var nearlyEqual = __webpack_require__(3).nearlyEqual;
57783var bigNearlyEqual = __webpack_require__(37);
57784
57785function factory (type, config, load, typed) {
57786
57787 var matrix = load(__webpack_require__(0));
57788
57789 var algorithm03 = load(__webpack_require__(17));
57790 var algorithm07 = load(__webpack_require__(26));
57791 var algorithm12 = load(__webpack_require__(18));
57792 var algorithm13 = load(__webpack_require__(8));
57793 var algorithm14 = load(__webpack_require__(6));
57794
57795 var latex = __webpack_require__(4);
57796
57797 /**
57798 * Test whether value x is smaller or equal to y.
57799 *
57800 * The function returns true when x is smaller than y or the relative
57801 * difference between x and y is smaller than the configured epsilon. The
57802 * function cannot be used to compare values smaller than approximately 2.22e-16.
57803 * For matrices, the function is evaluated element wise.
57804 *
57805 * Syntax:
57806 *
57807 * math.smallerEq(x, y)
57808 *
57809 * Examples:
57810 *
57811 * math.smaller(1 + 2, 3); // returns false
57812 * math.smallerEq(1 + 2, 3); // returns true
57813 *
57814 * See also:
57815 *
57816 * equal, unequal, smaller, larger, largerEq, compare
57817 *
57818 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
57819 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
57820 * @return {boolean | Array | Matrix} Returns true when the x is smaller than y, else returns false
57821 */
57822 var smallerEq = typed('smallerEq', {
57823
57824 'boolean, boolean': function (x, y) {
57825 return x <= y;
57826 },
57827
57828 'number, number': function (x, y) {
57829 return x <= y || nearlyEqual(x, y, config.epsilon);
57830 },
57831
57832 'BigNumber, BigNumber': function (x, y) {
57833 return x.lte(y) || bigNearlyEqual(x, y, config.epsilon);
57834 },
57835
57836 'Fraction, Fraction': function (x, y) {
57837 return x.compare(y) !== 1;
57838 },
57839
57840 'Complex, Complex': function () {
57841 throw new TypeError('No ordering relation is defined for complex numbers');
57842 },
57843
57844 'Unit, Unit': function (x, y) {
57845 if (!x.equalBase(y)) {
57846 throw new Error('Cannot compare units with different base');
57847 }
57848 return smallerEq(x.value, y.value);
57849 },
57850
57851 'string, string': function (x, y) {
57852 return x <= y;
57853 },
57854
57855 'Matrix, Matrix': function (x, y) {
57856 // result
57857 var c;
57858
57859 // process matrix storage
57860 switch (x.storage()) {
57861 case 'sparse':
57862 switch (y.storage()) {
57863 case 'sparse':
57864 // sparse + sparse
57865 c = algorithm07(x, y, smallerEq);
57866 break;
57867 default:
57868 // sparse + dense
57869 c = algorithm03(y, x, smallerEq, true);
57870 break;
57871 }
57872 break;
57873 default:
57874 switch (y.storage()) {
57875 case 'sparse':
57876 // dense + sparse
57877 c = algorithm03(x, y, smallerEq, false);
57878 break;
57879 default:
57880 // dense + dense
57881 c = algorithm13(x, y, smallerEq);
57882 break;
57883 }
57884 break;
57885 }
57886 return c;
57887 },
57888
57889 'Array, Array': function (x, y) {
57890 // use matrix implementation
57891 return smallerEq(matrix(x), matrix(y)).valueOf();
57892 },
57893
57894 'Array, Matrix': function (x, y) {
57895 // use matrix implementation
57896 return smallerEq(matrix(x), y);
57897 },
57898
57899 'Matrix, Array': function (x, y) {
57900 // use matrix implementation
57901 return smallerEq(x, matrix(y));
57902 },
57903
57904 'Matrix, any': function (x, y) {
57905 // result
57906 var c;
57907 // check storage format
57908 switch (x.storage()) {
57909 case 'sparse':
57910 c = algorithm12(x, y, smallerEq, false);
57911 break;
57912 default:
57913 c = algorithm14(x, y, smallerEq, false);
57914 break;
57915 }
57916 return c;
57917 },
57918
57919 'any, Matrix': function (x, y) {
57920 // result
57921 var c;
57922 // check storage format
57923 switch (y.storage()) {
57924 case 'sparse':
57925 c = algorithm12(y, x, smallerEq, true);
57926 break;
57927 default:
57928 c = algorithm14(y, x, smallerEq, true);
57929 break;
57930 }
57931 return c;
57932 },
57933
57934 'Array, any': function (x, y) {
57935 // use matrix implementation
57936 return algorithm14(matrix(x), y, smallerEq, false).valueOf();
57937 },
57938
57939 'any, Array': function (x, y) {
57940 // use matrix implementation
57941 return algorithm14(matrix(y), x, smallerEq, true).valueOf();
57942 }
57943 });
57944
57945 smallerEq.toTex = {
57946 2: '\\left(${args[0]}' + latex.operators['smallerEq'] + '${args[1]}\\right)'
57947 };
57948
57949 return smallerEq;
57950}
57951
57952exports.name = 'smallerEq';
57953exports.factory = factory;
57954
57955
57956/***/ }),
57957/* 501 */
57958/***/ (function(module, exports, __webpack_require__) {
57959
57960module.exports = [
57961 __webpack_require__(502),
57962 __webpack_require__(145),
57963 __webpack_require__(503),
57964 __webpack_require__(146),
57965 __webpack_require__(504),
57966 __webpack_require__(505),
57967 __webpack_require__(506),
57968 __webpack_require__(507),
57969 __webpack_require__(147),
57970 __webpack_require__(508)
57971];
57972
57973
57974/***/ }),
57975/* 502 */
57976/***/ (function(module, exports, __webpack_require__) {
57977
57978"use strict";
57979
57980
57981var flatten = __webpack_require__(2).flatten;
57982
57983function factory (type, config, load, typed) {
57984 var index = load(__webpack_require__(27));
57985 var matrix = load(__webpack_require__(45));
57986 var size = load(__webpack_require__(29));
57987 var subset = load(__webpack_require__(23));
57988 var compareNatural = load(__webpack_require__(31));
57989
57990 /**
57991 * Create the cartesian product of two (multi)sets.
57992 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
57993 *
57994 * Syntax:
57995 *
57996 * math.setCartesian(set1, set2)
57997 *
57998 * Examples:
57999 *
58000 * math.setCartesian([1, 2], [3, 4]); // returns [[1, 3], [1, 4], [2, 3], [2, 4]]
58001 *
58002 * See also:
58003 *
58004 * setUnion, setIntersect, setDifference, setPowerset
58005 *
58006 * @param {Array | Matrix} a1 A (multi)set
58007 * @param {Array | Matrix} a2 A (multi)set
58008 * @return {Array | Matrix} The cartesian product of two (multi)sets
58009 */
58010 var setCartesian = typed('setCartesian', {
58011 'Array | Matrix, Array | Matrix': function (a1, a2) {
58012 if (subset(size(a1), new index(0)) === 0 || subset(size(a2), new index(0)) === 0) { // if any of them is empty, return empty
58013 var result = [];
58014 }
58015 else {
58016 var b1 = flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural);
58017 var b2 = flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural);
58018 var result = [];
58019 for (var i=0; i<b1.length; i++) {
58020 for (var j=0; j<b2.length; j++) {
58021 result.push([b1[i], b2[j]]);
58022 }
58023 }
58024 }
58025 // return an array, if both inputs were arrays
58026 if (Array.isArray(a1) && Array.isArray(a2)) {
58027 return result;
58028 }
58029 // return a matrix otherwise
58030 return new matrix(result);
58031 }
58032 });
58033
58034 return setCartesian;
58035}
58036
58037exports.name = 'setCartesian';
58038exports.factory = factory;
58039
58040
58041/***/ }),
58042/* 503 */
58043/***/ (function(module, exports, __webpack_require__) {
58044
58045"use strict";
58046
58047
58048var flatten = __webpack_require__(2).flatten;
58049
58050function factory (type, config, load, typed) {
58051 var equal = load(__webpack_require__(30));
58052 var index = load(__webpack_require__(27));
58053 var matrix = load(__webpack_require__(45));
58054 var size = load(__webpack_require__(29));
58055 var subset = load(__webpack_require__(23));
58056 var compareNatural = load(__webpack_require__(31));
58057
58058 /**
58059 * Collect the distinct elements of a multiset.
58060 * A multi-dimension array will be converted to a single-dimension array before the operation.
58061 *
58062 * Syntax:
58063 *
58064 * math.setDistinct(set)
58065 *
58066 * Examples:
58067 *
58068 * math.setDistinct([1, 1, 1, 2, 2, 3]); // returns [1, 2, 3]
58069 *
58070 * See also:
58071 *
58072 * setMultiplicity
58073 *
58074 * @param {Array | Matrix} a A multiset
58075 * @return {Array | Matrix} A set containing the distinc elements of the multiset
58076 */
58077 var setDistinct = typed('setDistinct', {
58078 'Array | Matrix': function (a) {
58079 if (subset(size(a), new index(0)) === 0) { // if empty, return empty
58080 var result = [];
58081 }
58082 else {
58083 var b = flatten(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
58084 var result = [];
58085 result.push(b[0]);
58086 for (var i=1; i<b.length; i++) {
58087 if (!equal(b[i], b[i-1])) {
58088 result.push(b[i]);
58089 }
58090 }
58091 }
58092 // return an array, if the input was an array
58093 if (Array.isArray(a)) {
58094 return result;
58095 }
58096 // return a matrix otherwise
58097 return new matrix(result);
58098 }
58099 });
58100
58101 return setDistinct;
58102}
58103
58104exports.name = 'setDistinct';
58105exports.factory = factory;
58106
58107
58108/***/ }),
58109/* 504 */
58110/***/ (function(module, exports, __webpack_require__) {
58111
58112"use strict";
58113
58114
58115var flatten = __webpack_require__(2).flatten;
58116var identify = __webpack_require__(2).identify;
58117
58118function factory (type, config, load, typed) {
58119 var equal = load(__webpack_require__(30));
58120 var index = load(__webpack_require__(27));
58121 var size = load(__webpack_require__(29));
58122 var subset = load(__webpack_require__(23));
58123 var compareNatural = load(__webpack_require__(31));
58124
58125 /**
58126 * Check whether a (multi)set is a subset of another (multi)set. (Every element of set1 is the element of set2.)
58127 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
58128 *
58129 * Syntax:
58130 *
58131 * math.setIsSubset(set1, set2)
58132 *
58133 * Examples:
58134 *
58135 * math.setIsSubset([1, 2], [3, 4, 5, 6]); // returns false
58136 * math.setIsSubset([3, 4], [3, 4, 5, 6]); // returns true
58137 *
58138 * See also:
58139 *
58140 * setUnion, setIntersect, setDifference
58141 *
58142 * @param {Array | Matrix} a1 A (multi)set
58143 * @param {Array | Matrix} a2 A (multi)set
58144 * @return {boolean} true | false
58145 */
58146 var setIsSubset = typed('setIsSubset', {
58147 'Array | Matrix, Array | Matrix': function (a1, a2) {
58148 if (subset(size(a1), new index(0)) === 0) { // empty is a subset of anything
58149 return true;
58150 }
58151 else if (subset(size(a2), new index(0)) === 0) { // anything is not a subset of empty
58152 return false;
58153 }
58154 var b1 = identify(flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural));
58155 var b2 = identify(flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural));
58156 var inb2;
58157 for (var i=0; i<b1.length; i++) {
58158 inb2 = false;
58159 for (var j=0; j<b2.length; j++) {
58160 if (equal(b1[i].value, b2[j].value) && b1[i].identifier === b2[j].identifier) { // the identifier is always a decimal int
58161 inb2 = true;
58162 break;
58163 }
58164 }
58165 if (inb2 === false) {
58166 return false;
58167 }
58168 }
58169 return true;
58170 }
58171 });
58172
58173 return setIsSubset;
58174}
58175
58176exports.name = 'setIsSubset';
58177exports.factory = factory;
58178
58179
58180/***/ }),
58181/* 505 */
58182/***/ (function(module, exports, __webpack_require__) {
58183
58184"use strict";
58185
58186
58187var flatten = __webpack_require__(2).flatten;
58188
58189function factory (type, config, load, typed) {
58190 var equal = load(__webpack_require__(30));
58191 var index = load(__webpack_require__(27));
58192 var size = load(__webpack_require__(29));
58193 var subset = load(__webpack_require__(23));
58194
58195 /**
58196 * Count the multiplicity of an element in a multiset.
58197 * A multi-dimension array will be converted to a single-dimension array before the operation.
58198 *
58199 * Syntax:
58200 *
58201 * math.setMultiplicity(element, set)
58202 *
58203 * Examples:
58204 *
58205 * math.setMultiplicity(1, [1, 2, 2, 4]); // returns 1
58206 * math.setMultiplicity(2, [1, 2, 2, 4]); // returns 2
58207 *
58208 * See also:
58209 *
58210 * setDistinct, setSize
58211 *
58212 * @param {number | BigNumber | Fraction | Complex} e An element in the multiset
58213 * @param {Array | Matrix} a A multiset
58214 * @return {number} The number of how many times the multiset contains the element
58215 */
58216 var setMultiplicity = typed('setMultiplicity', {
58217 'number | BigNumber | Fraction | Complex, Array | Matrix': function (e, a) {
58218 if (subset(size(a), new index(0)) === 0) { // if empty, return 0
58219 return 0;
58220 }
58221 var b = flatten(Array.isArray(a) ? a : a.toArray());
58222 var count = 0;
58223 for (var i=0; i<b.length; i++) {
58224 if (equal(b[i], e)) {
58225 count++;
58226 }
58227 }
58228 return count;
58229 }
58230 });
58231
58232 return setMultiplicity;
58233}
58234
58235exports.name = 'setMultiplicity';
58236exports.factory = factory;
58237
58238
58239/***/ }),
58240/* 506 */
58241/***/ (function(module, exports, __webpack_require__) {
58242
58243"use strict";
58244
58245
58246var flatten = __webpack_require__(2).flatten;
58247
58248function factory (type, config, load, typed) {
58249 var index = load(__webpack_require__(27));
58250 var size = load(__webpack_require__(29));
58251 var subset = load(__webpack_require__(23));
58252 var compareNatural = load(__webpack_require__(31));
58253
58254 /**
58255 * Create the powerset of a (multi)set. (The powerset contains very possible subsets of a (multi)set.)
58256 * A multi-dimension array will be converted to a single-dimension array before the operation.
58257 *
58258 * Syntax:
58259 *
58260 * math.setPowerset(set)
58261 *
58262 * Examples:
58263 *
58264 * math.setPowerset([1, 2, 3]); // returns [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
58265 *
58266 * See also:
58267 *
58268 * setCartesian
58269 *
58270 * @param {Array | Matrix} a A (multi)set
58271 * @return {Array} The powerset of the (multi)set
58272 */
58273 var setPowerset = typed('setPowerset', {
58274 'Array | Matrix': function (a) {
58275 if (subset(size(a), new index(0)) === 0) { // if empty, return empty
58276 return [];
58277 }
58278 var b = flatten(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
58279 var result = [];
58280 var number = 0;
58281 while (number.toString(2).length <= b.length) {
58282 result.push(_subset(b, number.toString(2).split("").reverse()));
58283 number++;
58284 }
58285 // can not return a matrix, because of the different size of the subarrays
58286 return _sort(result);
58287 }
58288 });
58289
58290 return setPowerset;
58291
58292 // create subset
58293 function _subset(array, bitarray) {
58294 var result = [];
58295 for (var i=0; i<bitarray.length; i++) {
58296 if (bitarray[i] === "1") {
58297 result.push(array[i]);
58298 }
58299 }
58300 return result;
58301 }
58302
58303 // sort subsests by length
58304 function _sort(array) {
58305 var temp = [];
58306 for (var i=array.length-1; i>0; i--) {
58307 for (var j=0; j<i; j++) {
58308 if (array[j].length > array[j+1].length) {
58309 temp = array[j];
58310 array[j] = array[j+1];
58311 array[j+1] = temp;
58312 }
58313 }
58314 }
58315 return array;
58316 }
58317}
58318
58319exports.name = 'setPowerset';
58320exports.factory = factory;
58321
58322
58323/***/ }),
58324/* 507 */
58325/***/ (function(module, exports, __webpack_require__) {
58326
58327"use strict";
58328
58329
58330var flatten = __webpack_require__(2).flatten;
58331
58332function factory (type, config, load, typed) {
58333 var equal = load(__webpack_require__(30));
58334 var compareNatural = load(__webpack_require__(31));
58335
58336 /**
58337 * Count the number of elements of a (multi)set. When a second parameter is 'true', count only the unique values.
58338 * A multi-dimension array will be converted to a single-dimension array before the operation.
58339 *
58340 * Syntax:
58341 *
58342 * math.setSize(set)
58343 * math.setSize(set, unique)
58344 *
58345 * Examples:
58346 *
58347 * math.setSize([1, 2, 2, 4]); // returns 4
58348 * math.setSize([1, 2, 2, 4], true); // returns 3
58349 *
58350 * See also:
58351 *
58352 * setUnion, setIntersect, setDifference
58353 *
58354 * @param {Array | Matrix} a A multiset
58355 * @return {number} The number of elements of the (multi)set
58356 */
58357 var setSize = typed('setSize', {
58358 'Array | Matrix': function (a) {
58359 return Array.isArray(a) ? flatten(a).length : flatten(a.toArray()).length;
58360 },
58361 'Array | Matrix, boolean': function (a, unique) {
58362 if (unique === false || a.length === 0) {
58363 return Array.isArray(a) ? flatten(a).length : flatten(a.toArray()).length;
58364 }
58365 else {
58366 var b = flatten(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
58367 var count = 1;
58368 for (var i=1; i<b.length; i++) {
58369 if (!equal(b[i], b[i-1])) {
58370 count++;
58371 }
58372 }
58373 return count;
58374 }
58375 }
58376 });
58377
58378 return setSize;
58379}
58380
58381exports.name = 'setSize';
58382exports.factory = factory;
58383
58384
58385/***/ }),
58386/* 508 */
58387/***/ (function(module, exports, __webpack_require__) {
58388
58389"use strict";
58390
58391
58392var flatten = __webpack_require__(2).flatten;
58393
58394function factory (type, config, load, typed) {
58395 var index = load(__webpack_require__(27));
58396 var concat = load(__webpack_require__(64));
58397 var size = load(__webpack_require__(29));
58398 var subset = load(__webpack_require__(23));
58399 var setIntersect = load(__webpack_require__(146));
58400 var setSymDifference = load(__webpack_require__(147));
58401
58402 /**
58403 * Create the union of two (multi)sets.
58404 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
58405 *
58406 * Syntax:
58407 *
58408 * math.setUnion(set1, set2)
58409 *
58410 * Examples:
58411 *
58412 * math.setUnion([1, 2, 3, 4], [3, 4, 5, 6]); // returns [1, 2, 3, 4, 5, 6]
58413 * math.setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]]); // returns [1, 2, 3, 4, 5, 6]
58414 *
58415 * See also:
58416 *
58417 * setIntersect, setDifference
58418 *
58419 * @param {Array | Matrix} a1 A (multi)set
58420 * @param {Array | Matrix} a2 A (multi)set
58421 * @return {Array | Matrix} The union of two (multi)sets
58422 */
58423 var setUnion = typed('setUnion', {
58424 'Array | Matrix, Array | Matrix': function (a1, a2) {
58425 if (subset(size(a1), new index(0)) === 0) { // if any of them is empty, return the other one
58426 return flatten(a2);
58427 }
58428 else if (subset(size(a2), new index(0)) === 0) {
58429 return flatten(a1);
58430 }
58431 var b1 = flatten(a1);
58432 var b2 = flatten(a2);
58433 return concat(setSymDifference(b1, b2), setIntersect(b1, b2));
58434 }
58435 });
58436
58437 return setUnion;
58438}
58439
58440exports.name = 'setUnion';
58441exports.factory = factory;
58442
58443
58444/***/ }),
58445/* 509 */
58446/***/ (function(module, exports, __webpack_require__) {
58447
58448module.exports = [
58449 __webpack_require__(510)
58450];
58451
58452
58453/***/ }),
58454/* 510 */
58455/***/ (function(module, exports, __webpack_require__) {
58456
58457"use strict";
58458
58459
58460var deepMap = __webpack_require__(1);
58461var sign = __webpack_require__(3).sign;
58462
58463
58464function factory (type, config, load, typed) {
58465 /**
58466 * Compute the erf function of a value using a rational Chebyshev
58467 * approximations for different intervals of x.
58468 *
58469 * This is a translation of W. J. Cody's Fortran implementation from 1987
58470 * ( http://www.netlib.org/specfun/erf ). See the AMS publication
58471 * "Rational Chebyshev Approximations for the Error Function" by W. J. Cody
58472 * for an explanation of this process.
58473 *
58474 * For matrices, the function is evaluated element wise.
58475 *
58476 * Syntax:
58477 *
58478 * math.erf(x)
58479 *
58480 * Examples:
58481 *
58482 * math.erf(0.2); // returns 0.22270258921047847
58483 * math.erf(-0.5); // returns -0.5204998778130465
58484 * math.erf(4); // returns 0.9999999845827421
58485 *
58486 * @param {number | Array | Matrix} x A real number
58487 * @return {number | Array | Matrix} The erf of `x`
58488 */
58489 var erf = typed('erf', {
58490 'number': function (x) {
58491 var y = Math.abs(x);
58492
58493 if (y >= MAX_NUM) {
58494 return sign(x);
58495 }
58496 if (y <= THRESH) {
58497 return sign(x) * erf1(y);
58498 }
58499 if (y <= 4.0) {
58500 return sign(x) * (1 - erfc2(y));
58501 }
58502 return sign(x) * (1 - erfc3(y));
58503 },
58504
58505 // TODO: Not sure if there's a way to guarantee some degree of accuracy here.
58506 // Perhaps it would be best to set the precision of the number to that which
58507 // is guaranteed by erf()
58508 'BigNumber': function (n) {
58509 return new type.BigNumber(erf(n.toNumber()));
58510 },
58511
58512 'Array | Matrix': function (n) {
58513 return deepMap(n, erf);
58514 }
58515
58516 // TODO: For complex numbers, use the approximation for the Faddeeva function
58517 // from "More Efficient Computation of the Complex Error Function" (AMS)
58518
58519 });
58520
58521 /**
58522 * Approximates the error function erf() for x <= 0.46875 using this function:
58523 * n
58524 * erf(x) = x * sum (p_j * x^(2j)) / (q_j * x^(2j))
58525 * j=0
58526 */
58527 function erf1(y) {
58528 var ysq = y * y;
58529 var xnum = P[0][4]*ysq;
58530 var xden = ysq;
58531 var i;
58532
58533 for (i = 0; i < 3; i += 1) {
58534 xnum = (xnum + P[0][i]) * ysq;
58535 xden = (xden + Q[0][i]) * ysq;
58536 }
58537 return y * (xnum + P[0][3]) / (xden + Q[0][3]);
58538 }
58539
58540 /**
58541 * Approximates the complement of the error function erfc() for
58542 * 0.46875 <= x <= 4.0 using this function:
58543 * n
58544 * erfc(x) = e^(-x^2) * sum (p_j * x^j) / (q_j * x^j)
58545 * j=0
58546 */
58547 function erfc2(y) {
58548 var xnum = P[1][8] * y;
58549 var xden = y;
58550 var i;
58551
58552 for (i = 0; i < 7; i += 1) {
58553 xnum = (xnum + P[1][i]) * y;
58554 xden = (xden + Q[1][i]) * y;
58555 }
58556 var result = (xnum + P[1][7]) / (xden + Q[1][7]);
58557 var ysq = parseInt(y * 16) / 16;
58558 var del = (y - ysq) * (y + ysq);
58559 return Math.exp(-ysq*ysq) * Math.exp(-del) * result;
58560 }
58561
58562 /**
58563 * Approximates the complement of the error function erfc() for x > 4.0 using
58564 * this function:
58565 *
58566 * erfc(x) = (e^(-x^2) / x) * [ 1/sqrt(pi) +
58567 * n
58568 * 1/(x^2) * sum (p_j * x^(-2j)) / (q_j * x^(-2j)) ]
58569 * j=0
58570 */
58571 function erfc3(y) {
58572 var ysq = 1 / (y * y);
58573 var xnum = P[2][5] * ysq;
58574 var xden = ysq;
58575 var i;
58576
58577 for (i = 0; i < 4; i += 1) {
58578 xnum = (xnum + P[2][i]) * ysq;
58579 xden = (xden + Q[2][i]) * ysq;
58580 }
58581 var result = ysq * (xnum + P[2][4]) / (xden + Q[2][4]);
58582 result = (SQRPI - result) / y;
58583 ysq = parseInt(y * 16) / 16;
58584 var del = (y - ysq) * (y + ysq);
58585 return Math.exp(-ysq*ysq) * Math.exp(-del) * result;
58586 }
58587
58588 erf.toTex = {1: 'erf\\left(${args[0]}\\right)'};
58589
58590 return erf;
58591}
58592
58593/**
58594 * Upper bound for the first approximation interval, 0 <= x <= THRESH
58595 * @constant
58596 */
58597var THRESH = 0.46875;
58598
58599/**
58600 * Constant used by W. J. Cody's Fortran77 implementation to denote sqrt(pi)
58601 * @constant
58602 */
58603var SQRPI = 5.6418958354775628695e-1;
58604
58605/**
58606 * Coefficients for each term of the numerator sum (p_j) for each approximation
58607 * interval (see W. J. Cody's paper for more details)
58608 * @constant
58609 */
58610var P = [[
58611 3.16112374387056560e00, 1.13864154151050156e02,
58612 3.77485237685302021e02, 3.20937758913846947e03,
58613 1.85777706184603153e-1
58614], [
58615 5.64188496988670089e-1, 8.88314979438837594e00,
58616 6.61191906371416295e01, 2.98635138197400131e02,
58617 8.81952221241769090e02, 1.71204761263407058e03,
58618 2.05107837782607147e03, 1.23033935479799725e03,
58619 2.15311535474403846e-8
58620], [
58621 3.05326634961232344e-1, 3.60344899949804439e-1,
58622 1.25781726111229246e-1, 1.60837851487422766e-2,
58623 6.58749161529837803e-4, 1.63153871373020978e-2
58624]];
58625
58626/**
58627 * Coefficients for each term of the denominator sum (q_j) for each approximation
58628 * interval (see W. J. Cody's paper for more details)
58629 * @constant
58630 */
58631var Q = [[
58632 2.36012909523441209e01, 2.44024637934444173e02,
58633 1.28261652607737228e03, 2.84423683343917062e03
58634], [
58635 1.57449261107098347e01, 1.17693950891312499e02,
58636 5.37181101862009858e02, 1.62138957456669019e03,
58637 3.29079923573345963e03, 4.36261909014324716e03,
58638 3.43936767414372164e03, 1.23033935480374942e03
58639], [
58640 2.56852019228982242e00, 1.87295284992346047e00,
58641 5.27905102951428412e-1, 6.05183413124413191e-2,
58642 2.33520497626869185e-3
58643]];
58644
58645/**
58646 * Maximum/minimum safe numbers to input to erf() (in ES6+, this number is
58647 * Number.[MAX|MIN]_SAFE_INTEGER). erf() for all numbers beyond this limit will
58648 * return 1
58649 */
58650var MAX_NUM = Math.pow(2, 53);
58651
58652
58653exports.name = 'erf';
58654exports.factory = factory;
58655
58656
58657/***/ }),
58658/* 511 */
58659/***/ (function(module, exports, __webpack_require__) {
58660
58661module.exports = [
58662 __webpack_require__(512),
58663 __webpack_require__(114),
58664 __webpack_require__(115),
58665 __webpack_require__(148),
58666 __webpack_require__(118),
58667 __webpack_require__(513),
58668 __webpack_require__(514),
58669 __webpack_require__(515),
58670 __webpack_require__(516),
58671 __webpack_require__(144),
58672 __webpack_require__(149)
58673];
58674
58675
58676/***/ }),
58677/* 512 */
58678/***/ (function(module, exports, __webpack_require__) {
58679
58680"use strict";
58681
58682
58683var flatten = __webpack_require__(2).flatten;
58684
58685function factory (type, config, load, typed) {
58686 var abs = load(__webpack_require__(28));
58687 var map = load(__webpack_require__(142));
58688 var median = load(__webpack_require__(148));
58689 var subtract = load(__webpack_require__(21));
58690
58691 /**
58692 * Compute the median absolute deviation of a matrix or a list with values.
58693 * The median absolute deviation is defined as the median of the absolute
58694 * deviations from the median.
58695 *
58696 * Syntax:
58697 *
58698 * math.mad(a, b, c, ...)
58699 * math.mad(A)
58700 *
58701 * Examples:
58702 *
58703 * math.mad(10, 20, 30); // returns 10
58704 * math.mad([1, 2, 3]); // returns 1
58705 * math.mad([[1, 2, 3], [4, 5, 6]]); // returns 1.5
58706 *
58707 * See also:
58708 *
58709 * median, mean, std, abs
58710 *
58711 * @param {Array | Matrix} array
58712 * A single matrix or multiple scalar values.
58713 * @return {*} The median absolute deviation.
58714 */
58715 var mad = typed('mad', {
58716 // mad([a, b, c, d, ...])
58717 'Array | Matrix': _mad,
58718
58719 // mad(a, b, c, d, ...)
58720 '...': function (args) {
58721 return _mad(args);
58722 }
58723 });
58724
58725 mad.toTex = undefined; // use default template
58726
58727 return mad;
58728
58729 function _mad(array) {
58730 array = flatten(array.valueOf());
58731
58732 if (array.length === 0) {
58733 throw new Error('Cannot calculate median absolute deviation of an empty array');
58734 }
58735
58736 var med = median(array);
58737 return median(map(array, function (value) {
58738 return abs(subtract(value, med));
58739 }));
58740 }
58741}
58742
58743exports.name = 'mad';
58744exports.factory = factory;
58745
58746
58747/***/ }),
58748/* 513 */
58749/***/ (function(module, exports, __webpack_require__) {
58750
58751"use strict";
58752
58753
58754var flatten = __webpack_require__(2).flatten;
58755
58756function factory (type, config, load, typed) {
58757
58758 /**
58759 * Computes the mode of a set of numbers or a list with values(numbers or characters).
58760 * If there are more than one modes, it returns a list of those values.
58761 *
58762 * Syntax:
58763 *
58764 * math.mode(a, b, c, ...)
58765 * math.mode(A)
58766 *
58767 * Examples:
58768 *
58769 * math.mode(2, 1, 4, 3, 1); // returns [1]
58770 * math.mode([1, 2.7, 3.2, 4, 2.7]); // returns [2.7]
58771 * math.mode(1, 4, 6, 1, 6) // returns [1, 6]
58772 * math.mode('a','a','b','c') // returns ["a"]
58773 * math.mode(1, 1.5, 'abc') // returns [1, 1.5, "abc"]
58774 *
58775 * See also:
58776 *
58777 * median,
58778 * mean
58779 *
58780 * @param {... *} args A single matrix
58781 * @return {*} The mode of all values
58782 */
58783
58784 var mode = typed('mode', {
58785 'Array | Matrix' : _mode,
58786
58787 '...': function (args) {
58788 return _mode(args);
58789 }
58790 });
58791
58792 return mode;
58793
58794 /**
58795 * Calculates the mode in an 1-dimensional array
58796 * @param {Array} values
58797 * @return {number} mode
58798 * @private
58799 */
58800 function _mode(values) {
58801 values = flatten(values.valueOf());
58802 var num = values.length;
58803 if (num == 0) {
58804 throw new Error('Cannot calculate mode of an empty array');
58805 }
58806
58807 var count = {},
58808 mode = [],
58809 max = 0;
58810 for (var i in values) {
58811 if (!(values[i] in count)){
58812 count[values[i]] = 0;
58813 }
58814 count[values[i]]++;
58815 if (count[values[i]] == max){
58816 mode.push(values[i]);
58817 }
58818 else if (count[values[i]] > max) {
58819 max = count[values[i]];
58820 mode = [values[i]];
58821 }
58822 }
58823 return mode;
58824 };
58825}
58826
58827exports.name = 'mode';
58828exports.factory = factory;
58829
58830/***/ }),
58831/* 514 */
58832/***/ (function(module, exports, __webpack_require__) {
58833
58834"use strict";
58835
58836
58837var deepForEach = __webpack_require__(43);
58838
58839function factory (type, config, load, typed) {
58840 var multiply = load(__webpack_require__(22));
58841
58842 /**
58843 * Compute the product of a matrix or a list with values.
58844 * In case of a (multi dimensional) array or matrix, the sum of all
58845 * elements will be calculated.
58846 *
58847 * Syntax:
58848 *
58849 * math.prod(a, b, c, ...)
58850 * math.prod(A)
58851 *
58852 * Examples:
58853 *
58854 * math.multiply(2, 3); // returns 6
58855 * math.prod(2, 3); // returns 6
58856 * math.prod(2, 3, 4); // returns 24
58857 * math.prod([2, 3, 4]); // returns 24
58858 * math.prod([[2, 5], [4, 3]]); // returns 120
58859 *
58860 * See also:
58861 *
58862 * mean, median, min, max, sum, std, var
58863 *
58864 * @param {... *} args A single matrix or or multiple scalar values
58865 * @return {*} The product of all values
58866 */
58867 var prod = typed('prod', {
58868 // prod([a, b, c, d, ...])
58869 'Array | Matrix': _prod,
58870
58871 // prod([a, b, c, d, ...], dim)
58872 'Array | Matrix, number | BigNumber': function (array, dim) {
58873 // TODO: implement prod(A, dim)
58874 throw new Error('prod(A, dim) is not yet supported');
58875 //return reduce(arguments[0], arguments[1], math.prod);
58876 },
58877
58878 // prod(a, b, c, d, ...)
58879 '...': function (args) {
58880 return _prod(args);
58881 }
58882 });
58883
58884 prod.toTex = undefined; // use default template
58885
58886 return prod;
58887
58888 /**
58889 * Recursively calculate the product of an n-dimensional array
58890 * @param {Array} array
58891 * @return {number} prod
58892 * @private
58893 */
58894 function _prod(array) {
58895 var prod = undefined;
58896
58897 deepForEach(array, function (value) {
58898 prod = (prod === undefined) ? value : multiply(prod, value);
58899 });
58900
58901 if (prod === undefined) {
58902 throw new Error('Cannot calculate prod of an empty array');
58903 }
58904
58905 return prod;
58906 }
58907}
58908
58909exports.name = 'prod';
58910exports.factory = factory;
58911
58912
58913/***/ }),
58914/* 515 */
58915/***/ (function(module, exports, __webpack_require__) {
58916
58917"use strict";
58918
58919
58920var isInteger = __webpack_require__(3).isInteger;
58921var isNumber = __webpack_require__(3).isNumber;
58922var flatten = __webpack_require__(2).flatten;
58923var isCollection = __webpack_require__(48);
58924
58925function factory (type, config, load, typed) {
58926 var add = load(__webpack_require__(20));
58927 var multiply = load(__webpack_require__(12));
58928 var partitionSelect = load(__webpack_require__(89));
58929 var compare = load(__webpack_require__(52));
58930
58931 /**
58932 * Compute the prob order quantile of a matrix or a list with values.
58933 * The sequence is sorted and the middle value is returned.
58934 * Supported types of sequence values are: Number, BigNumber, Unit
58935 * Supported types of probability are: Number, BigNumber
58936 *
58937 * In case of a (multi dimensional) array or matrix, the prob order quantile
58938 * of all elements will be calculated.
58939 *
58940 * Syntax:
58941 *
58942 * math.quantileSeq(A, prob[, sorted])
58943 * math.quantileSeq(A, [prob1, prob2, ...][, sorted])
58944 * math.quantileSeq(A, N[, sorted])
58945 *
58946 * Examples:
58947 *
58948 * math.quantileSeq([3, -1, 5, 7], 0.5); // returns 4
58949 * math.quantileSeq([3, -1, 5, 7], [1/3, 2/3]); // returns [3, 5]
58950 * math.quantileSeq([3, -1, 5, 7], 2); // returns [3, 5]
58951 * math.quantileSeq([-1, 3, 5, 7], 0.5, true); // returns 4
58952 *
58953 * See also:
58954 *
58955 * median, mean, min, max, sum, prod, std, var
58956 *
58957 * @param {Array, Matrix} data A single matrix or Array
58958 * @param {Number, BigNumber, Array} probOrN prob is the order of the quantile, while N is
58959 * the amount of evenly distributed steps of
58960 * probabilities; only one of these options can
58961 * be provided
58962 * @param {Boolean} sorted=false is data sorted in ascending order
58963 * @return {Number, BigNumber, Unit, Array} Quantile(s)
58964 */
58965 function quantileSeq(data, probOrN, sorted) {
58966 var probArr, dataArr, one;
58967
58968 if (arguments.length < 2 || arguments.length > 3) {
58969 throw new SyntaxError('Function quantileSeq requires two or three parameters');
58970 }
58971
58972 if (isCollection(data)) {
58973 sorted = sorted || false;
58974 if (typeof sorted === 'boolean') {
58975 dataArr = data.valueOf();
58976 if (isNumber(probOrN)) {
58977 if (probOrN < 0) {
58978 throw new Error('N/prob must be non-negative');
58979 }
58980
58981 if (probOrN <= 1) {
58982 // quantileSeq([a, b, c, d, ...], prob[,sorted])
58983 return _quantileSeq(dataArr, probOrN, sorted);
58984 }
58985
58986 if (probOrN > 1) {
58987 // quantileSeq([a, b, c, d, ...], N[,sorted])
58988 if (!isInteger(probOrN)) {
58989 throw new Error('N must be a positive integer');
58990 }
58991
58992 var nPlusOne = probOrN + 1;
58993 probArr = new Array(probOrN);
58994 for (var i = 0; i < probOrN;) {
58995 probArr[i] = _quantileSeq(dataArr, (++i) / nPlusOne, sorted);
58996 }
58997 return probArr;
58998 }
58999 }
59000
59001 if (type.isBigNumber(probOrN)) {
59002 if (probOrN.isNegative()) {
59003 throw new Error('N/prob must be non-negative');
59004 }
59005
59006 one = new probOrN.constructor(1);
59007
59008 if (probOrN.lte(one)) {
59009 // quantileSeq([a, b, c, d, ...], prob[,sorted])
59010 return _quantileSeq(dataArr, probOrN, sorted);
59011 }
59012
59013 if (probOrN.gt(one)) {
59014 // quantileSeq([a, b, c, d, ...], N[,sorted])
59015 if (!probOrN.isInteger()) {
59016 throw new Error('N must be a positive integer');
59017 }
59018
59019 // largest possible Array length is 2^32-1;
59020 // 2^32 < 10^15, thus safe conversion guaranteed
59021 var intN = probOrN.toNumber();
59022 if (intN > 4294967295) {
59023 throw new Error('N must be less than or equal to 2^32-1, as that is the maximum length of an Array');
59024 }
59025
59026 var nPlusOne = new type.BigNumber(intN + 1);
59027 probArr = new Array(intN);
59028 for (var i = 0; i < intN;) {
59029 probArr[i] = _quantileSeq(dataArr, new type.BigNumber(++i).div(nPlusOne), sorted);
59030 }
59031 return probArr;
59032 }
59033 }
59034
59035 if (Array.isArray(probOrN)) {
59036 // quantileSeq([a, b, c, d, ...], [prob1, prob2, ...][,sorted])
59037 probArr = new Array(probOrN.length);
59038 for (var i = 0; i < probArr.length; ++i) {
59039 var currProb = probOrN[i];
59040 if (isNumber(currProb)) {
59041 if (currProb < 0 || currProb > 1) {
59042 throw new Error('Probability must be between 0 and 1, inclusive');
59043 }
59044 } else if (type.isBigNumber(currProb)) {
59045 one = new currProb.constructor(1);
59046 if (currProb.isNegative() || currProb.gt(one)) {
59047 throw new Error('Probability must be between 0 and 1, inclusive');
59048 }
59049 } else {
59050 throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function
59051 }
59052
59053 probArr[i] = _quantileSeq(dataArr, currProb, sorted);
59054 }
59055 return probArr;
59056 }
59057
59058 throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function
59059 }
59060
59061 throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function
59062 }
59063
59064 throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function
59065 }
59066
59067 /**
59068 * Calculate the prob order quantile of an n-dimensional array.
59069 *
59070 * @param {Array} array
59071 * @param {Number, BigNumber} prob
59072 * @param {Boolean} sorted
59073 * @return {Number, BigNumber, Unit} prob order quantile
59074 * @private
59075 */
59076 function _quantileSeq(array, prob, sorted) {
59077 var flat = flatten(array);
59078 var len = flat.length;
59079 if (len === 0) {
59080 throw new Error('Cannot calculate quantile of an empty sequence');
59081 }
59082
59083 if (isNumber(prob)) {
59084 var index = prob * (len-1);
59085 var fracPart = index % 1;
59086 if (fracPart === 0) {
59087 var value = sorted ? flat[index] : partitionSelect(flat, index);
59088
59089 validate(value);
59090
59091 return value;
59092 }
59093
59094 var integerPart = Math.floor(index);
59095
59096 var left, right;
59097 if (sorted) {
59098 left = flat[integerPart];
59099 right = flat[integerPart+1];
59100 } else {
59101 right = partitionSelect(flat, integerPart+1);
59102
59103 // max of partition is kth largest
59104 left = flat[integerPart];
59105 for (var i = 0; i < integerPart; ++i) {
59106 if (compare(flat[i], left) > 0) {
59107 left = flat[i];
59108 }
59109 }
59110 }
59111
59112 validate(left);
59113 validate(right);
59114
59115 // Q(prob) = (1-f)*A[floor(index)] + f*A[floor(index)+1]
59116 return add(multiply(left, 1 - fracPart), multiply(right, fracPart));
59117 }
59118
59119 // If prob is a BigNumber
59120 var index = prob.times(len-1);
59121 if (index.isInteger()) {
59122 index = index.toNumber();
59123 var value = sorted ? flat[index] : partitionSelect(flat, index);
59124
59125 validate(value);
59126
59127 return value;
59128 }
59129
59130 var integerPart = index.floor();
59131 var fracPart = index.minus(integerPart);
59132 var integerPartNumber = integerPart.toNumber();
59133
59134 var left, right;
59135 if (sorted) {
59136 left = flat[integerPartNumber];
59137 right = flat[integerPartNumber+1];
59138 } else {
59139 right = partitionSelect(flat, integerPartNumber+1);
59140
59141 // max of partition is kth largest
59142 left = flat[integerPartNumber];
59143 for (var i = 0; i < integerPartNumber; ++i) {
59144 if (compare(flat[i], left) > 0) {
59145 left = flat[i];
59146 }
59147 }
59148 }
59149
59150 validate(left);
59151 validate(right);
59152
59153 // Q(prob) = (1-f)*A[floor(index)] + f*A[floor(index)+1]
59154 var one = new fracPart.constructor(1);
59155 return add(multiply(left, one.minus(fracPart)), multiply(right, fracPart));
59156 }
59157
59158 /**
59159 * Check if array value types are valid, throw error otherwise.
59160 * @param {number | BigNumber | Unit} x
59161 * @param {number | BigNumber | Unit} x
59162 * @private
59163 */
59164 var validate = typed({
59165 'number | BigNumber | Unit': function (x) {
59166 return x;
59167 }
59168 });
59169
59170 return quantileSeq;
59171}
59172
59173exports.name = 'quantileSeq';
59174exports.factory = factory;
59175
59176
59177/***/ }),
59178/* 516 */
59179/***/ (function(module, exports, __webpack_require__) {
59180
59181"use strict";
59182
59183
59184function factory (type, config, load, typed) {
59185 var sqrt = load(__webpack_require__(50));
59186 var variance = load(__webpack_require__(149));
59187
59188 /**
59189 * Compute the standard deviation of a matrix or a list with values.
59190 * The standard deviations is defined as the square root of the variance:
59191 * `std(A) = sqrt(var(A))`.
59192 * In case of a (multi dimensional) array or matrix, the standard deviation
59193 * over all elements will be calculated.
59194 *
59195 * Optionally, the type of normalization can be specified as second
59196 * parameter. The parameter `normalization` can be one of the following values:
59197 *
59198 * - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
59199 * - 'uncorrected' The sum of squared errors is divided by n
59200 * - 'biased' The sum of squared errors is divided by (n + 1)
59201 *
59202 * Syntax:
59203 *
59204 * math.std(a, b, c, ...)
59205 * math.std(A)
59206 * math.std(A, normalization)
59207 *
59208 * Examples:
59209 *
59210 * math.std(2, 4, 6); // returns 2
59211 * math.std([2, 4, 6, 8]); // returns 2.581988897471611
59212 * math.std([2, 4, 6, 8], 'uncorrected'); // returns 2.23606797749979
59213 * math.std([2, 4, 6, 8], 'biased'); // returns 2
59214 *
59215 * math.std([[1, 2, 3], [4, 5, 6]]); // returns 1.8708286933869707
59216 *
59217 * See also:
59218 *
59219 * mean, median, max, min, prod, sum, var
59220 *
59221 * @param {Array | Matrix} array
59222 * A single matrix or or multiple scalar values
59223 * @param {string} [normalization='unbiased']
59224 * Determines how to normalize the variance.
59225 * Choose 'unbiased' (default), 'uncorrected', or 'biased'.
59226 * @return {*} The standard deviation
59227 */
59228 var std = typed('std', {
59229 // std([a, b, c, d, ...])
59230 'Array | Matrix': _std,
59231
59232 // std([a, b, c, d, ...], normalization)
59233 'Array | Matrix, string': _std,
59234
59235 // std(a, b, c, d, ...)
59236 '...': function (args) {
59237 return _std(args);
59238 }
59239 });
59240
59241 std.toTex = undefined; // use default template
59242
59243 return std;
59244
59245 function _std(array, normalization) {
59246 if (array.length == 0) {
59247 throw new SyntaxError('Function std requires one or more parameters (0 provided)');
59248 }
59249
59250 return sqrt(variance.apply(null, arguments));
59251 }
59252}
59253
59254exports.name = 'std';
59255exports.factory = factory;
59256
59257
59258/***/ }),
59259/* 517 */
59260/***/ (function(module, exports, __webpack_require__) {
59261
59262module.exports = [
59263 __webpack_require__(99),
59264 __webpack_require__(518)
59265];
59266
59267
59268/***/ }),
59269/* 518 */
59270/***/ (function(module, exports, __webpack_require__) {
59271
59272"use strict";
59273
59274
59275var isString = __webpack_require__(9).isString;
59276var format = __webpack_require__(9).format;
59277
59278function factory (type, config, load, typed) {
59279 /**
59280 * Interpolate values into a string template.
59281 *
59282 * Syntax:
59283 *
59284 * math.print(template, values)
59285 * math.print(template, values, precision)
59286 * math.print(template, values, options)
59287 *
59288 * Example usage:
59289 *
59290 * // the following outputs: 'Lucy is 5 years old'
59291 * math.print('Lucy is $age years old', {age: 5});
59292 *
59293 * // the following outputs: 'The value of pi is 3.141592654'
59294 * math.print('The value of pi is $pi', {pi: math.pi}, 10);
59295 *
59296 * // the following outputs: 'hello Mary! The date is 2013-03-23'
59297 * math.print('Hello $user.name! The date is $date', {
59298 * user: {
59299 * name: 'Mary',
59300 * },
59301 * date: new Date(2013, 2, 23).toISOString().substring(0, 10)
59302 * });
59303 *
59304 * See also:
59305 *
59306 * format
59307 *
59308 * @param {string} template A string containing variable placeholders.
59309 * @param {Object} values An object containing variables which will
59310 * be filled in in the template.
59311 * @param {number | Object} [options] Formatting options,
59312 * or the number of digits to format numbers.
59313 * See function math.format for a description
59314 * of all options.
59315 * @return {string} Interpolated string
59316 */
59317 var print = typed ('print', {
59318 'string, Object': _print,
59319 'string, Object, number | Object': _print
59320 });
59321
59322 print.toTex = undefined; // use default template
59323
59324 return print;
59325}
59326
59327/**
59328 * Interpolate values into a string template.
59329 * @param {string} template
59330 * @param {Object} values
59331 * @param {number | Object} [options]
59332 * @returns {string} Interpolated string
59333 * @private
59334 */
59335function _print(template, values, options) {
59336 return template.replace(/\$([\w\.]+)/g, function (original, key) {
59337 var keys = key.split('.');
59338 var value = values[keys.shift()];
59339 while (keys.length && value !== undefined) {
59340 var k = keys.shift();
59341 value = k ? value[k] : value + '.';
59342 }
59343
59344 if (value !== undefined) {
59345 if (!isString(value)) {
59346 return format(value, options);
59347 }
59348 else {
59349 return value;
59350 }
59351 }
59352
59353 return original;
59354 }
59355 );
59356}
59357
59358exports.name = 'print';
59359exports.factory = factory;
59360
59361
59362/***/ }),
59363/* 519 */
59364/***/ (function(module, exports, __webpack_require__) {
59365
59366module.exports = [
59367 __webpack_require__(520),
59368 __webpack_require__(150),
59369 __webpack_require__(521),
59370 __webpack_require__(522),
59371 __webpack_require__(523),
59372 __webpack_require__(524),
59373 __webpack_require__(525),
59374 __webpack_require__(526),
59375 __webpack_require__(527),
59376 __webpack_require__(528),
59377 __webpack_require__(529),
59378 __webpack_require__(530),
59379 __webpack_require__(531),
59380 __webpack_require__(532),
59381 __webpack_require__(533),
59382 __webpack_require__(534),
59383 __webpack_require__(535),
59384 __webpack_require__(536),
59385 __webpack_require__(537),
59386 __webpack_require__(538),
59387 __webpack_require__(539),
59388 __webpack_require__(540),
59389 __webpack_require__(541),
59390 __webpack_require__(542),
59391 __webpack_require__(543)
59392];
59393
59394
59395/***/ }),
59396/* 520 */
59397/***/ (function(module, exports, __webpack_require__) {
59398
59399"use strict";
59400
59401
59402var deepMap = __webpack_require__(1);
59403
59404function factory (type, config, load, typed) {
59405
59406 /**
59407 * Calculate the inverse cosine of a value.
59408 *
59409 * For matrices, the function is evaluated element wise.
59410 *
59411 * Syntax:
59412 *
59413 * math.acos(x)
59414 *
59415 * Examples:
59416 *
59417 * math.acos(0.5); // returns number 1.0471975511965979
59418 * math.acos(math.cos(1.5)); // returns number 1.5
59419 *
59420 * math.acos(2); // returns Complex 0 + 1.3169578969248166 i
59421 *
59422 * See also:
59423 *
59424 * cos, atan, asin
59425 *
59426 * @param {number | BigNumber | Complex | Array | Matrix} x Function input
59427 * @return {number | BigNumber | Complex | Array | Matrix} The arc cosine of x
59428 */
59429 var acos = typed('acos', {
59430 'number': function (x) {
59431 if ((x >= -1 && x <= 1) || config.predictable) {
59432 return Math.acos(x);
59433 }
59434 else {
59435 return new type.Complex(x, 0).acos();
59436 }
59437 },
59438
59439 'Complex': function (x) {
59440 return x.acos();
59441 },
59442
59443 'BigNumber': function (x) {
59444 return x.acos();
59445 },
59446
59447 'Array | Matrix': function (x) {
59448 return deepMap(x, acos);
59449 }
59450 });
59451
59452 acos.toTex = {1: '\\cos^{-1}\\left(${args[0]}\\right)'};
59453
59454 return acos;
59455}
59456
59457exports.name = 'acos';
59458exports.factory = factory;
59459
59460
59461/***/ }),
59462/* 521 */
59463/***/ (function(module, exports, __webpack_require__) {
59464
59465"use strict";
59466
59467
59468var deepMap = __webpack_require__(1);
59469
59470function factory (type, config, load, typed) {
59471
59472 /**
59473 * Calculate the inverse cotangent of a value, defined as `acot(x) = atan(1/x)`.
59474 *
59475 * For matrices, the function is evaluated element wise.
59476 *
59477 * Syntax:
59478 *
59479 * math.acot(x)
59480 *
59481 * Examples:
59482 *
59483 * math.acot(0.5); // returns number 0.4636476090008061
59484 * math.acot(math.cot(1.5)); // returns number 1.5
59485 *
59486 * math.acot(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
59487 *
59488 * See also:
59489 *
59490 * cot, atan
59491 *
59492 * @param {number | Complex | Array | Matrix} x Function input
59493 * @return {number | Complex | Array | Matrix} The arc cotangent of x
59494 */
59495 var acot = typed('acot', {
59496 'number': function (x) {
59497 return Math.atan(1 / x);
59498 },
59499
59500 'Complex': function (x) {
59501 return x.acot();
59502 },
59503
59504 'BigNumber': function (x) {
59505 return new type.BigNumber(1).div(x).atan();
59506 },
59507
59508 'Array | Matrix': function (x) {
59509 return deepMap(x, acot);
59510 }
59511 });
59512
59513 acot.toTex = {1: '\\cot^{-1}\\left(${args[0]}\\right)'};
59514
59515 return acot;
59516}
59517
59518exports.name = 'acot';
59519exports.factory = factory;
59520
59521
59522/***/ }),
59523/* 522 */
59524/***/ (function(module, exports, __webpack_require__) {
59525
59526"use strict";
59527
59528
59529var deepMap = __webpack_require__(1);
59530
59531function factory (type, config, load, typed) {
59532
59533 /**
59534 * Calculate the hyperbolic arccotangent of a value,
59535 * defined as `acoth(x) = atanh(1/x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.
59536 *
59537 * For matrices, the function is evaluated element wise.
59538 *
59539 * Syntax:
59540 *
59541 * math.acoth(x)
59542 *
59543 * Examples:
59544 *
59545 * math.acoth(0.5); // returns 0.8047189562170503
59546 *
59547 * See also:
59548 *
59549 * acsch, asech
59550 *
59551 * @param {number | Complex | Array | Matrix} x Function input
59552 * @return {number | Complex | Array | Matrix} Hyperbolic arccotangent of x
59553 */
59554 var acoth = typed('acoth', {
59555 'number': function (x) {
59556 if (x >= 1 || x <= -1 || config.predictable) {
59557 return isFinite(x) ? (Math.log((x+1)/x) + Math.log(x/(x-1))) / 2 : 0;
59558 }
59559 return new type.Complex(x, 0).acoth();
59560 },
59561
59562 'Complex': function (x) {
59563 return x.acoth();
59564 },
59565
59566 'BigNumber': function (x) {
59567 return new type.BigNumber(1).div(x).atanh();
59568 },
59569
59570 'Array | Matrix': function (x) {
59571 return deepMap(x, acoth);
59572 }
59573 });
59574
59575 acoth.toTex = {1: '\\coth^{-1}\\left(${args[0]}\\right)'};
59576
59577 return acoth;
59578}
59579
59580exports.name = 'acoth';
59581exports.factory = factory;
59582
59583
59584/***/ }),
59585/* 523 */
59586/***/ (function(module, exports, __webpack_require__) {
59587
59588"use strict";
59589
59590
59591var deepMap = __webpack_require__(1);
59592
59593
59594function factory (type, config, load, typed) {
59595
59596 /**
59597 * Calculate the inverse cosecant of a value, defined as `acsc(x) = asin(1/x)`.
59598 *
59599 * For matrices, the function is evaluated element wise.
59600 *
59601 * Syntax:
59602 *
59603 * math.acsc(x)
59604 *
59605 * Examples:
59606 *
59607 * math.acsc(0.5); // returns number 0.5235987755982989
59608 * math.acsc(math.csc(1.5)); // returns number ~1.5
59609 *
59610 * math.acsc(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
59611 *
59612 * See also:
59613 *
59614 * csc, asin, asec
59615 *
59616 * @param {number | Complex | Array | Matrix} x Function input
59617 * @return {number | Complex | Array | Matrix} The arc cosecant of x
59618 */
59619 var acsc = typed('acsc', {
59620 'number': function (x) {
59621 if (x <= -1 || x >= 1 || config.predictable) {
59622 return Math.asin(1 / x);
59623 }
59624 return new type.Complex(x, 0).acsc();
59625 },
59626
59627 'Complex': function (x) {
59628 return x.acsc();
59629 },
59630
59631 'BigNumber': function (x) {
59632 return new type.BigNumber(1).div(x).asin();
59633 },
59634
59635 'Array | Matrix': function (x) {
59636 return deepMap(x, acsc);
59637 }
59638 });
59639
59640 acsc.toTex = {1: '\\csc^{-1}\\left(${args[0]}\\right)'};
59641
59642 return acsc;
59643}
59644
59645exports.name = 'acsc';
59646exports.factory = factory;
59647
59648
59649/***/ }),
59650/* 524 */
59651/***/ (function(module, exports, __webpack_require__) {
59652
59653"use strict";
59654
59655
59656var deepMap = __webpack_require__(1);
59657
59658function factory (type, config, load, typed) {
59659
59660 /**
59661 * Calculate the hyperbolic arccosecant of a value,
59662 * defined as `acsch(x) = asinh(1/x) = ln(1/x + sqrt(1/x^2 + 1))`.
59663 *
59664 * For matrices, the function is evaluated element wise.
59665 *
59666 * Syntax:
59667 *
59668 * math.acsch(x)
59669 *
59670 * Examples:
59671 *
59672 * math.acsch(0.5); // returns 1.4436354751788103
59673 *
59674 * See also:
59675 *
59676 * asech, acoth
59677 *
59678 * @param {number | Complex | Array | Matrix} x Function input
59679 * @return {number | Complex | Array | Matrix} Hyperbolic arccosecant of x
59680 */
59681 var acsch = typed('acsch', {
59682 'number': function (x) {
59683 x = 1 / x;
59684 return Math.log(x + Math.sqrt(x*x + 1));
59685 },
59686
59687 'Complex': function (x) {
59688 return x.acsch();
59689 },
59690
59691 'BigNumber': function (x) {
59692 return new type.BigNumber(1).div(x).asinh();
59693 },
59694
59695 'Array | Matrix': function (x) {
59696 return deepMap(x, acsch);
59697 }
59698 });
59699
59700 acsch.toTex = {1: '\\mathrm{csch}^{-1}\\left(${args[0]}\\right)'};
59701
59702 return acsch;
59703}
59704
59705exports.name = 'acsch';
59706exports.factory = factory;
59707
59708
59709/***/ }),
59710/* 525 */
59711/***/ (function(module, exports, __webpack_require__) {
59712
59713"use strict";
59714
59715
59716var deepMap = __webpack_require__(1);
59717
59718function factory (type, config, load, typed) {
59719
59720 /**
59721 * Calculate the inverse secant of a value. Defined as `asec(x) = acos(1/x)`.
59722 *
59723 * For matrices, the function is evaluated element wise.
59724 *
59725 * Syntax:
59726 *
59727 * math.asec(x)
59728 *
59729 * Examples:
59730 *
59731 * math.asec(0.5); // returns 1.0471975511965979
59732 * math.asec(math.sec(1.5)); // returns 1.5
59733 *
59734 * math.asec(2); // returns 0 + 1.3169578969248166 i
59735 *
59736 * See also:
59737 *
59738 * acos, acot, acsc
59739 *
59740 * @param {number | Complex | Array | Matrix} x Function input
59741 * @return {number | Complex | Array | Matrix} The arc secant of x
59742 */
59743 var asec = typed('asec', {
59744 'number': function (x) {
59745 if (x <= -1 || x >= 1 || config.predictable) {
59746 return Math.acos(1 / x);
59747 }
59748 return new type.Complex(x, 0).asec();
59749 },
59750
59751 'Complex': function (x) {
59752 return x.asec();
59753 },
59754
59755 'BigNumber': function (x) {
59756 return new type.BigNumber(1).div(x).acos();
59757 },
59758
59759 'Array | Matrix': function (x) {
59760 return deepMap(x, asec);
59761 }
59762 });
59763
59764 asec.toTex = {1: '\\sec^{-1}\\left(${args[0]}\\right)'};
59765
59766 return asec;
59767}
59768
59769exports.name = 'asec';
59770exports.factory = factory;
59771
59772
59773/***/ }),
59774/* 526 */
59775/***/ (function(module, exports, __webpack_require__) {
59776
59777"use strict";
59778
59779
59780var deepMap = __webpack_require__(1);
59781
59782function factory (type, config, load, typed) {
59783 var acosh = typed.find(load(__webpack_require__(150)), ['Complex']);
59784
59785 /**
59786 * Calculate the hyperbolic arcsecant of a value,
59787 * defined as `asech(x) = acosh(1/x) = ln(sqrt(1/x^2 - 1) + 1/x)`.
59788 *
59789 * For matrices, the function is evaluated element wise.
59790 *
59791 * Syntax:
59792 *
59793 * math.asech(x)
59794 *
59795 * Examples:
59796 *
59797 * math.asech(0.5); // returns 1.3169578969248166
59798 *
59799 * See also:
59800 *
59801 * acsch, acoth
59802 *
59803 * @param {number | Complex | Array | Matrix} x Function input
59804 * @return {number | Complex | Array | Matrix} Hyperbolic arcsecant of x
59805 */
59806 var asech = typed('asech', {
59807 'number': function (x) {
59808 if ((x <= 1 && x >= -1) || config.predictable) {
59809 x = 1 / x;
59810
59811 var ret = Math.sqrt(x*x - 1);
59812 if (x > 0 || config.predictable) {
59813 return Math.log(ret + x);
59814 }
59815
59816 return new type.Complex(Math.log(ret - x), Math.PI);
59817 }
59818
59819 return new type.Complex(x, 0).asech();
59820 },
59821
59822 'Complex': function (x) {
59823 return x.asech()
59824 },
59825
59826 'BigNumber': function (x) {
59827 return new type.BigNumber(1).div(x).acosh();
59828 },
59829
59830 'Array | Matrix': function (x) {
59831 return deepMap(x, asech);
59832 }
59833 });
59834
59835 asech.toTex = {1: '\\mathrm{sech}^{-1}\\left(${args[0]}\\right)'};
59836
59837 return asech;
59838}
59839
59840exports.name = 'asech';
59841exports.factory = factory;
59842
59843
59844/***/ }),
59845/* 527 */
59846/***/ (function(module, exports, __webpack_require__) {
59847
59848"use strict";
59849
59850
59851var deepMap = __webpack_require__(1);
59852
59853function factory (type, config, load, typed) {
59854
59855 /**
59856 * Calculate the inverse sine of a value.
59857 *
59858 * For matrices, the function is evaluated element wise.
59859 *
59860 * Syntax:
59861 *
59862 * math.asin(x)
59863 *
59864 * Examples:
59865 *
59866 * math.asin(0.5); // returns number 0.5235987755982989
59867 * math.asin(math.sin(1.5)); // returns number ~1.5
59868 *
59869 * math.asin(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
59870 *
59871 * See also:
59872 *
59873 * sin, atan, acos
59874 *
59875 * @param {number | BigNumber | Complex | Array | Matrix} x Function input
59876 * @return {number | BigNumber | Complex | Array | Matrix} The arc sine of x
59877 */
59878 var asin = typed('asin', {
59879 'number': function (x) {
59880 if ((x >= -1 && x <= 1) || config.predictable) {
59881 return Math.asin(x);
59882 }
59883 else {
59884 return new type.Complex(x, 0).asin();
59885 }
59886 },
59887
59888 'Complex': function (x) {
59889 return x.asin();
59890 },
59891
59892 'BigNumber': function (x) {
59893 return x.asin();
59894 },
59895
59896 'Array | Matrix': function (x) {
59897 // deep map collection, skip zeros since asin(0) = 0
59898 return deepMap(x, asin, true);
59899 }
59900 });
59901
59902 asin.toTex = {1: '\\sin^{-1}\\left(${args[0]}\\right)'};
59903
59904 return asin;
59905}
59906
59907exports.name = 'asin';
59908exports.factory = factory;
59909
59910
59911/***/ }),
59912/* 528 */
59913/***/ (function(module, exports, __webpack_require__) {
59914
59915"use strict";
59916
59917
59918var deepMap = __webpack_require__(1);
59919
59920function factory (type, config, load, typed) {
59921
59922 /**
59923 * Calculate the hyperbolic arcsine of a value,
59924 * defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.
59925 *
59926 * For matrices, the function is evaluated element wise.
59927 *
59928 * Syntax:
59929 *
59930 * math.asinh(x)
59931 *
59932 * Examples:
59933 *
59934 * math.asinh(0.5); // returns 0.48121182505960347
59935 *
59936 * See also:
59937 *
59938 * acosh, atanh
59939 *
59940 * @param {number | Complex | Array | Matrix} x Function input
59941 * @return {number | Complex | Array | Matrix} Hyperbolic arcsine of x
59942 */
59943 var asinh = typed('asinh', {
59944 'number': Math.asinh || function (x) {
59945 return Math.log(Math.sqrt(x*x + 1) + x);
59946 },
59947
59948 'Complex': function (x) {
59949 return x.asinh();
59950 },
59951
59952 'BigNumber': function (x) {
59953 return x.asinh();
59954 },
59955
59956 'Array | Matrix': function (x) {
59957 // deep map collection, skip zeros since asinh(0) = 0
59958 return deepMap(x, asinh, true);
59959 }
59960 });
59961
59962 asinh.toTex = {1: '\\sinh^{-1}\\left(${args[0]}\\right)'};
59963
59964 return asinh;
59965}
59966
59967exports.name = 'asinh';
59968exports.factory = factory;
59969
59970
59971/***/ }),
59972/* 529 */
59973/***/ (function(module, exports, __webpack_require__) {
59974
59975"use strict";
59976
59977
59978var deepMap = __webpack_require__(1);
59979
59980function factory (type, config, load, typed) {
59981
59982 /**
59983 * Calculate the inverse tangent of a value.
59984 *
59985 * For matrices, the function is evaluated element wise.
59986 *
59987 * Syntax:
59988 *
59989 * math.atan(x)
59990 *
59991 * Examples:
59992 *
59993 * math.atan(0.5); // returns number 0.4636476090008061
59994 * math.atan(math.tan(1.5)); // returns number 1.5
59995 *
59996 * math.atan(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
59997 *
59998 * See also:
59999 *
60000 * tan, asin, acos
60001 *
60002 * @param {number | BigNumber | Complex | Array | Matrix} x Function input
60003 * @return {number | BigNumber | Complex | Array | Matrix} The arc tangent of x
60004 */
60005 var atan = typed('atan', {
60006 'number': function (x) {
60007 return Math.atan(x);
60008 },
60009
60010 'Complex': function (x) {
60011 return x.atan();
60012 },
60013
60014 'BigNumber': function (x) {
60015 return x.atan();
60016 },
60017
60018 'Array | Matrix': function (x) {
60019 // deep map collection, skip zeros since atan(0) = 0
60020 return deepMap(x, atan, true);
60021 }
60022 });
60023
60024 atan.toTex = {1: '\\tan^{-1}\\left(${args[0]}\\right)'};
60025
60026 return atan;
60027}
60028
60029exports.name = 'atan';
60030exports.factory = factory;
60031
60032
60033/***/ }),
60034/* 530 */
60035/***/ (function(module, exports, __webpack_require__) {
60036
60037"use strict";
60038
60039
60040function factory (type, config, load, typed) {
60041
60042 var matrix = load(__webpack_require__(0));
60043
60044 var algorithm02 = load(__webpack_require__(24));
60045 var algorithm03 = load(__webpack_require__(17));
60046 var algorithm09 = load(__webpack_require__(136));
60047 var algorithm11 = load(__webpack_require__(19));
60048 var algorithm12 = load(__webpack_require__(18));
60049 var algorithm13 = load(__webpack_require__(8));
60050 var algorithm14 = load(__webpack_require__(6));
60051
60052 /**
60053 * Calculate the inverse tangent function with two arguments, y/x.
60054 * By providing two arguments, the right quadrant of the computed angle can be
60055 * determined.
60056 *
60057 * For matrices, the function is evaluated element wise.
60058 *
60059 * Syntax:
60060 *
60061 * math.atan2(y, x)
60062 *
60063 * Examples:
60064 *
60065 * math.atan2(2, 2) / math.pi; // returns number 0.25
60066 *
60067 * var angle = math.unit(60, 'deg'); // returns Unit 60 deg
60068 * var x = math.cos(angle);
60069 * var y = math.sin(angle);
60070 *
60071 * math.atan(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
60072 *
60073 * See also:
60074 *
60075 * tan, atan, sin, cos
60076 *
60077 * @param {number | Array | Matrix} y Second dimension
60078 * @param {number | Array | Matrix} x First dimension
60079 * @return {number | Array | Matrix} Four-quadrant inverse tangent
60080 */
60081 var atan2 = typed('atan2', {
60082
60083 'number, number': Math.atan2,
60084
60085 // Complex numbers doesn't seem to have a reasonable implementation of
60086 // atan2(). Even Matlab removed the support, after they only calculated
60087 // the atan only on base of the real part of the numbers and ignored the imaginary.
60088
60089 'BigNumber, BigNumber': function (y, x) {
60090 return type.BigNumber.atan2(y, x);
60091 },
60092
60093 'Matrix, Matrix': function (x, y) {
60094 // result
60095 var c;
60096
60097 // process matrix storage
60098 switch (x.storage()) {
60099 case 'sparse':
60100 switch (y.storage()) {
60101 case 'sparse':
60102 // sparse .* sparse
60103 c = algorithm09(x, y, atan2, false);
60104 break;
60105 default:
60106 // sparse .* dense
60107 c = algorithm02(y, x, atan2, true);
60108 break;
60109 }
60110 break;
60111 default:
60112 switch (y.storage()) {
60113 case 'sparse':
60114 // dense .* sparse
60115 c = algorithm03(x, y, atan2, false);
60116 break;
60117 default:
60118 // dense .* dense
60119 c = algorithm13(x, y, atan2);
60120 break;
60121 }
60122 break;
60123 }
60124 return c;
60125 },
60126
60127 'Array, Array': function (x, y) {
60128 // use matrix implementation
60129 return atan2(matrix(x), matrix(y)).valueOf();
60130 },
60131
60132 'Array, Matrix': function (x, y) {
60133 // use matrix implementation
60134 return atan2(matrix(x), y);
60135 },
60136
60137 'Matrix, Array': function (x, y) {
60138 // use matrix implementation
60139 return atan2(x, matrix(y));
60140 },
60141
60142 'Matrix, number | BigNumber': function (x, y) {
60143 // result
60144 var c;
60145 // check storage format
60146 switch (x.storage()) {
60147 case 'sparse':
60148 c = algorithm11(x, y, atan2, false);
60149 break;
60150 default:
60151 c = algorithm14(x, y, atan2, false);
60152 break;
60153 }
60154 return c;
60155 },
60156
60157 'number | BigNumber, Matrix': function (x, y) {
60158 // result
60159 var c;
60160 // check storage format
60161 switch (y.storage()) {
60162 case 'sparse':
60163 c = algorithm12(y, x, atan2, true);
60164 break;
60165 default:
60166 c = algorithm14(y, x, atan2, true);
60167 break;
60168 }
60169 return c;
60170 },
60171
60172 'Array, number | BigNumber': function (x, y) {
60173 // use matrix implementation
60174 return algorithm14(matrix(x), y, atan2, false).valueOf();
60175 },
60176
60177 'number | BigNumber, Array': function (x, y) {
60178 // use matrix implementation
60179 return algorithm14(matrix(y), x, atan2, true).valueOf();
60180 }
60181 });
60182
60183 atan2.toTex = {2: '\\mathrm{atan2}\\left(${args}\\right)'};
60184
60185 return atan2;
60186}
60187
60188exports.name = 'atan2';
60189exports.factory = factory;
60190
60191
60192/***/ }),
60193/* 531 */
60194/***/ (function(module, exports, __webpack_require__) {
60195
60196"use strict";
60197
60198
60199var deepMap = __webpack_require__(1);
60200
60201function factory (type, config, load, typed) {
60202 /**
60203 * Calculate the hyperbolic arctangent of a value,
60204 * defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.
60205 *
60206 * For matrices, the function is evaluated element wise.
60207 *
60208 * Syntax:
60209 *
60210 * math.atanh(x)
60211 *
60212 * Examples:
60213 *
60214 * math.atanh(0.5); // returns 0.5493061443340549
60215 *
60216 * See also:
60217 *
60218 * acosh, asinh
60219 *
60220 * @param {number | Complex | Array | Matrix} x Function input
60221 * @return {number | Complex | Array | Matrix} Hyperbolic arctangent of x
60222 */
60223 var atanh = typed('atanh', {
60224 'number': function (x) {
60225 if ((x <= 1 && x >= -1) || config.predictable) {
60226 return _atanh(x);
60227 }
60228 return new type.Complex(x, 0).atanh();
60229 },
60230
60231 'Complex': function (x) {
60232 return x.atanh();
60233 },
60234
60235 'BigNumber': function (x) {
60236 return x.atanh();
60237 },
60238
60239 'Array | Matrix': function (x) {
60240 // deep map collection, skip zeros since atanh(0) = 0
60241 return deepMap(x, atanh, true);
60242 }
60243 });
60244
60245 atanh.toTex = {1: '\\tanh^{-1}\\left(${args[0]}\\right)'};
60246
60247 return atanh;
60248}
60249
60250/**
60251 * Calculate the hyperbolic arctangent of a number
60252 * @param {number} x
60253 * @return {number}
60254 * @private
60255 */
60256var _atanh = Math.atanh || function (x) {
60257 return Math.log((1 + x)/(1 - x)) / 2
60258};
60259
60260exports.name = 'atanh';
60261exports.factory = factory;
60262
60263
60264/***/ }),
60265/* 532 */
60266/***/ (function(module, exports, __webpack_require__) {
60267
60268"use strict";
60269
60270
60271var deepMap = __webpack_require__(1);
60272
60273function factory (type, config, load, typed) {
60274
60275 /**
60276 * Calculate the cosine of a value.
60277 *
60278 * For matrices, the function is evaluated element wise.
60279 *
60280 * Syntax:
60281 *
60282 * math.cos(x)
60283 *
60284 * Examples:
60285 *
60286 * math.cos(2); // returns number -0.4161468365471422
60287 * math.cos(math.pi / 4); // returns number 0.7071067811865475
60288 * math.cos(math.unit(180, 'deg')); // returns number -1
60289 * math.cos(math.unit(60, 'deg')); // returns number 0.5
60290 *
60291 * var angle = 0.2;
60292 * math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2); // returns number ~1
60293 *
60294 * See also:
60295 *
60296 * cos, tan
60297 *
60298 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
60299 * @return {number | BigNumber | Complex | Array | Matrix} Cosine of x
60300 */
60301 var cos = typed('cos', {
60302 'number': Math.cos,
60303
60304 'Complex': function (x) {
60305 return x.cos();
60306 },
60307
60308 'BigNumber': function (x) {
60309 return x.cos();
60310 },
60311
60312 'Unit': function (x) {
60313 if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
60314 throw new TypeError ('Unit in function cos is no angle');
60315 }
60316 return cos(x.value);
60317 },
60318
60319 'Array | Matrix': function (x) {
60320 return deepMap(x, cos);
60321 }
60322 });
60323
60324 cos.toTex = {1: '\\cos\\left(${args[0]}\\right)'};
60325
60326 return cos;
60327}
60328
60329exports.name = 'cos';
60330exports.factory = factory;
60331
60332
60333/***/ }),
60334/* 533 */
60335/***/ (function(module, exports, __webpack_require__) {
60336
60337"use strict";
60338
60339
60340var deepMap = __webpack_require__(1);
60341
60342function factory (type, config, load, typed) {
60343 /**
60344 * Calculate the hyperbolic cosine of a value,
60345 * defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`.
60346 *
60347 * For matrices, the function is evaluated element wise.
60348 *
60349 * Syntax:
60350 *
60351 * math.cosh(x)
60352 *
60353 * Examples:
60354 *
60355 * math.cosh(0.5); // returns number 1.1276259652063807
60356 *
60357 * See also:
60358 *
60359 * sinh, tanh
60360 *
60361 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
60362 * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic cosine of x
60363 */
60364 var cosh = typed('cosh', {
60365 'number': _cosh,
60366
60367 'Complex': function (x) {
60368 return x.cosh();
60369 },
60370
60371 'BigNumber': function (x) {
60372 return x.cosh();
60373 },
60374
60375 'Unit': function (x) {
60376 if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
60377 throw new TypeError ('Unit in function cosh is no angle');
60378 }
60379 return cosh(x.value);
60380 },
60381
60382 'Array | Matrix': function (x) {
60383 return deepMap(x, cosh);
60384 }
60385 });
60386
60387 cosh.toTex = {1: '\\cosh\\left(${args[0]}\\right)'};
60388
60389 return cosh;
60390}
60391
60392/**
60393 * Calculate the hyperbolic cosine of a number
60394 * @param {number} x
60395 * @returns {number}
60396 * @private
60397 */
60398var _cosh = Math.cosh || function (x) {
60399 return (Math.exp(x) + Math.exp(-x)) / 2;
60400};
60401
60402exports.name = 'cosh';
60403exports.factory = factory;
60404
60405
60406/***/ }),
60407/* 534 */
60408/***/ (function(module, exports, __webpack_require__) {
60409
60410"use strict";
60411
60412
60413var deepMap = __webpack_require__(1);
60414
60415function factory (type, config, load, typed) {
60416 /**
60417 * Calculate the cotangent of a value. Defined as `cot(x) = 1 / tan(x)`.
60418 *
60419 * For matrices, the function is evaluated element wise.
60420 *
60421 * Syntax:
60422 *
60423 * math.cot(x)
60424 *
60425 * Examples:
60426 *
60427 * math.cot(2); // returns number -0.45765755436028577
60428 * 1 / math.tan(2); // returns number -0.45765755436028577
60429 *
60430 * See also:
60431 *
60432 * tan, sec, csc
60433 *
60434 * @param {number | Complex | Unit | Array | Matrix} x Function input
60435 * @return {number | Complex | Array | Matrix} Cotangent of x
60436 */
60437 var cot = typed('cot', {
60438 'number': function (x) {
60439 return 1 / Math.tan(x);
60440 },
60441
60442 'Complex': function (x) {
60443 return x.cot();
60444 },
60445
60446 'BigNumber': function (x) {
60447 return new type.BigNumber(1).div(x.tan());
60448 },
60449
60450 'Unit': function (x) {
60451 if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
60452 throw new TypeError ('Unit in function cot is no angle');
60453 }
60454 return cot(x.value);
60455 },
60456
60457 'Array | Matrix': function (x) {
60458 return deepMap(x, cot);
60459 }
60460 });
60461
60462 cot.toTex = {1: '\\cot\\left(${args[0]}\\right)'};
60463
60464 return cot;
60465}
60466
60467exports.name = 'cot';
60468exports.factory = factory;
60469
60470
60471/***/ }),
60472/* 535 */
60473/***/ (function(module, exports, __webpack_require__) {
60474
60475"use strict";
60476
60477
60478var deepMap = __webpack_require__(1);
60479
60480function factory (type, config, load, typed) {
60481 /**
60482 * Calculate the hyperbolic cotangent of a value,
60483 * defined as `coth(x) = 1 / tanh(x)`.
60484 *
60485 * For matrices, the function is evaluated element wise.
60486 *
60487 * Syntax:
60488 *
60489 * math.coth(x)
60490 *
60491 * Examples:
60492 *
60493 * // coth(x) = 1 / tanh(x)
60494 * math.coth(2); // returns 1.0373147207275482
60495 * 1 / math.tanh(2); // returns 1.0373147207275482
60496 *
60497 * See also:
60498 *
60499 * sinh, tanh, cosh
60500 *
60501 * @param {number | Complex | Unit | Array | Matrix} x Function input
60502 * @return {number | Complex | Array | Matrix} Hyperbolic cotangent of x
60503 */
60504 var coth = typed('coth', {
60505 'number': _coth,
60506
60507 'Complex': function (x) {
60508 return x.coth();
60509 },
60510
60511 'BigNumber': function (x) {
60512 return new type.BigNumber(1).div(x.tanh());
60513 },
60514
60515 'Unit': function (x) {
60516 if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
60517 throw new TypeError ('Unit in function coth is no angle');
60518 }
60519 return coth(x.value);
60520 },
60521
60522 'Array | Matrix': function (x) {
60523 return deepMap(x, coth);
60524 }
60525 });
60526
60527 coth.toTex = {1: '\\coth\\left(${args[0]}\\right)'};
60528
60529 return coth;
60530}
60531
60532/**
60533 * Calculate the hyperbolic cosine of a number
60534 * @param {number} x
60535 * @returns {number}
60536 * @private
60537 */
60538function _coth(x) {
60539 var e = Math.exp(2 * x);
60540 return (e + 1) / (e - 1);
60541}
60542
60543exports.name = 'coth';
60544exports.factory = factory;
60545
60546
60547/***/ }),
60548/* 536 */
60549/***/ (function(module, exports, __webpack_require__) {
60550
60551"use strict";
60552
60553
60554var deepMap = __webpack_require__(1);
60555
60556function factory (type, config, load, typed) {
60557 /**
60558 * Calculate the cosecant of a value, defined as `csc(x) = 1/sin(x)`.
60559 *
60560 * For matrices, the function is evaluated element wise.
60561 *
60562 * Syntax:
60563 *
60564 * math.csc(x)
60565 *
60566 * Examples:
60567 *
60568 * math.csc(2); // returns number 1.099750170294617
60569 * 1 / math.sin(2); // returns number 1.099750170294617
60570 *
60571 * See also:
60572 *
60573 * sin, sec, cot
60574 *
60575 * @param {number | Complex | Unit | Array | Matrix} x Function input
60576 * @return {number | Complex | Array | Matrix} Cosecant of x
60577 */
60578 var csc = typed('csc', {
60579 'number': function (x) {
60580 return 1 / Math.sin(x);
60581 },
60582
60583 'Complex': function (x) {
60584 return x.csc();
60585 },
60586
60587 'BigNumber': function (x) {
60588 return new type.BigNumber(1).div(x.sin());
60589 },
60590
60591 'Unit': function (x) {
60592 if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
60593 throw new TypeError ('Unit in function csc is no angle');
60594 }
60595 return csc(x.value);
60596 },
60597
60598 'Array | Matrix': function (x) {
60599 return deepMap(x, csc);
60600 }
60601 });
60602
60603 csc.toTex = {1: '\\csc\\left(${args[0]}\\right)'};
60604
60605 return csc;
60606}
60607
60608exports.name = 'csc';
60609exports.factory = factory;
60610
60611
60612/***/ }),
60613/* 537 */
60614/***/ (function(module, exports, __webpack_require__) {
60615
60616"use strict";
60617
60618
60619var deepMap = __webpack_require__(1);
60620var sign = __webpack_require__(3).sign;
60621
60622function factory (type, config, load, typed) {
60623 /**
60624 * Calculate the hyperbolic cosecant of a value,
60625 * defined as `csch(x) = 1 / sinh(x)`.
60626 *
60627 * For matrices, the function is evaluated element wise.
60628 *
60629 * Syntax:
60630 *
60631 * math.csch(x)
60632 *
60633 * Examples:
60634 *
60635 * // csch(x) = 1/ sinh(x)
60636 * math.csch(0.5); // returns 1.9190347513349437
60637 * 1 / math.sinh(0.5); // returns 1.9190347513349437
60638 *
60639 * See also:
60640 *
60641 * sinh, sech, coth
60642 *
60643 * @param {number | Complex | Unit | Array | Matrix} x Function input
60644 * @return {number | Complex | Array | Matrix} Hyperbolic cosecant of x
60645 */
60646 var csch = typed('csch', {
60647 'number': _csch,
60648
60649 'Complex': function (x) {
60650 return x.csch();
60651 },
60652
60653 'BigNumber': function (x) {
60654 return new type.BigNumber(1).div(x.sinh());
60655 },
60656
60657 'Unit': function (x) {
60658 if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
60659 throw new TypeError ('Unit in function csch is no angle');
60660 }
60661 return csch(x.value);
60662 },
60663
60664 'Array | Matrix': function (x) {
60665 return deepMap(x, csch);
60666 }
60667 });
60668
60669 csch.toTex = {1: '\\mathrm{csch}\\left(${args[0]}\\right)'};
60670
60671 return csch;
60672}
60673
60674/**
60675 * Calculate the hyperbolic cosecant of a number
60676 * @param {number} x
60677 * @returns {number}
60678 * @private
60679 */
60680function _csch(x) {
60681 // consider values close to zero (+/-)
60682 if (x == 0) {
60683 return Number.POSITIVE_INFINITY;
60684 }
60685 else {
60686 return Math.abs(2 / (Math.exp(x) - Math.exp(-x))) * sign(x);
60687 }
60688}
60689
60690exports.name = 'csch';
60691exports.factory = factory;
60692
60693
60694/***/ }),
60695/* 538 */
60696/***/ (function(module, exports, __webpack_require__) {
60697
60698"use strict";
60699
60700
60701var deepMap = __webpack_require__(1);
60702
60703function factory (type, config, load, typed) {
60704 /**
60705 * Calculate the secant of a value, defined as `sec(x) = 1/cos(x)`.
60706 *
60707 * For matrices, the function is evaluated element wise.
60708 *
60709 * Syntax:
60710 *
60711 * math.sec(x)
60712 *
60713 * Examples:
60714 *
60715 * math.sec(2); // returns number -2.4029979617223822
60716 * 1 / math.cos(2); // returns number -2.4029979617223822
60717 *
60718 * See also:
60719 *
60720 * cos, csc, cot
60721 *
60722 * @param {number | Complex | Unit | Array | Matrix} x Function input
60723 * @return {number | Complex | Array | Matrix} Secant of x
60724 */
60725 var sec = typed('sec', {
60726 'number': function (x) {
60727 return 1 / Math.cos(x);
60728 },
60729
60730 'Complex': function (x) {
60731 return x.sec();
60732 },
60733
60734 'BigNumber': function (x) {
60735 return new type.BigNumber(1).div(x.cos());
60736 },
60737
60738 'Unit': function (x) {
60739 if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
60740 throw new TypeError ('Unit in function sec is no angle');
60741 }
60742 return sec(x.value);
60743 },
60744
60745 'Array | Matrix': function (x) {
60746 return deepMap(x, sec);
60747 }
60748 });
60749
60750 sec.toTex = {1: '\\sec\\left(${args[0]}\\right)'};
60751
60752 return sec;
60753}
60754
60755exports.name = 'sec';
60756exports.factory = factory;
60757
60758
60759/***/ }),
60760/* 539 */
60761/***/ (function(module, exports, __webpack_require__) {
60762
60763"use strict";
60764
60765
60766var deepMap = __webpack_require__(1);
60767
60768function factory (type, config, load, typed) {
60769 /**
60770 * Calculate the hyperbolic secant of a value,
60771 * defined as `sech(x) = 1 / cosh(x)`.
60772 *
60773 * For matrices, the function is evaluated element wise.
60774 *
60775 * Syntax:
60776 *
60777 * math.sech(x)
60778 *
60779 * Examples:
60780 *
60781 * // sech(x) = 1/ cosh(x)
60782 * math.sech(0.5); // returns 0.886818883970074
60783 * 1 / math.cosh(0.5); // returns 0.886818883970074
60784 *
60785 * See also:
60786 *
60787 * cosh, csch, coth
60788 *
60789 * @param {number | Complex | Unit | Array | Matrix} x Function input
60790 * @return {number | Complex | Array | Matrix} Hyperbolic secant of x
60791 */
60792 var sech = typed('sech', {
60793 'number': _sech,
60794
60795 'Complex': function (x) {
60796 return x.sech();
60797 },
60798
60799 'BigNumber': function (x) {
60800 return new type.BigNumber(1).div(x.cosh());
60801 },
60802
60803 'Unit': function (x) {
60804 if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
60805 throw new TypeError ('Unit in function sech is no angle');
60806 }
60807 return sech(x.value);
60808 },
60809
60810 'Array | Matrix': function (x) {
60811 return deepMap(x, sech);
60812 }
60813 });
60814
60815 sech.toTex = {1: '\\mathrm{sech}\\left(${args[0]}\\right)'};
60816
60817 return sech;
60818}
60819
60820/**
60821 * Calculate the hyperbolic secant of a number
60822 * @param {number} x
60823 * @returns {number}
60824 * @private
60825 */
60826function _sech(x) {
60827 return 2 / (Math.exp(x) + Math.exp(-x));
60828}
60829
60830exports.name = 'sech';
60831exports.factory = factory;
60832
60833
60834/***/ }),
60835/* 540 */
60836/***/ (function(module, exports, __webpack_require__) {
60837
60838"use strict";
60839
60840
60841var deepMap = __webpack_require__(1);
60842
60843function factory (type, config, load, typed) {
60844
60845 /**
60846 * Calculate the sine of a value.
60847 *
60848 * For matrices, the function is evaluated element wise.
60849 *
60850 * Syntax:
60851 *
60852 * math.sin(x)
60853 *
60854 * Examples:
60855 *
60856 * math.sin(2); // returns number 0.9092974268256813
60857 * math.sin(math.pi / 4); // returns number 0.7071067811865475
60858 * math.sin(math.unit(90, 'deg')); // returns number 1
60859 * math.sin(math.unit(30, 'deg')); // returns number 0.5
60860 *
60861 * var angle = 0.2;
60862 * math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2); // returns number ~1
60863 *
60864 * See also:
60865 *
60866 * cos, tan
60867 *
60868 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
60869 * @return {number | BigNumber | Complex | Array | Matrix} Sine of x
60870 */
60871 var sin = typed('sin', {
60872 'number': Math.sin,
60873
60874 'Complex': function (x) {
60875 return x.sin();
60876 },
60877
60878 'BigNumber': function (x) {
60879 return x.sin();
60880 },
60881
60882 'Unit': function (x) {
60883 if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
60884 throw new TypeError ('Unit in function sin is no angle');
60885 }
60886 return sin(x.value);
60887 },
60888
60889 'Array | Matrix': function (x) {
60890 // deep map collection, skip zeros since sin(0) = 0
60891 return deepMap(x, sin, true);
60892 }
60893 });
60894
60895 sin.toTex = {1: '\\sin\\left(${args[0]}\\right)'};
60896
60897 return sin;
60898}
60899
60900exports.name = 'sin';
60901exports.factory = factory;
60902
60903
60904/***/ }),
60905/* 541 */
60906/***/ (function(module, exports, __webpack_require__) {
60907
60908"use strict";
60909
60910
60911var deepMap = __webpack_require__(1);
60912
60913function factory (type, config, load, typed) {
60914 /**
60915 * Calculate the hyperbolic sine of a value,
60916 * defined as `sinh(x) = 1/2 * (exp(x) - exp(-x))`.
60917 *
60918 * For matrices, the function is evaluated element wise.
60919 *
60920 * Syntax:
60921 *
60922 * math.sinh(x)
60923 *
60924 * Examples:
60925 *
60926 * math.sinh(0.5); // returns number 0.5210953054937474
60927 *
60928 * See also:
60929 *
60930 * cosh, tanh
60931 *
60932 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
60933 * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic sine of x
60934 */
60935 var sinh = typed('sinh', {
60936 'number': _sinh,
60937
60938 'Complex': function (x) {
60939 return x.sinh();
60940 },
60941
60942 'BigNumber': function (x) {
60943 return x.sinh();
60944 },
60945
60946 'Unit': function (x) {
60947 if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
60948 throw new TypeError ('Unit in function sinh is no angle');
60949 }
60950 return sinh(x.value);
60951 },
60952
60953 'Array | Matrix': function (x) {
60954 // deep map collection, skip zeros since sinh(0) = 0
60955 return deepMap(x, sinh, true);
60956 }
60957 });
60958
60959 sinh.toTex = {1: '\\sinh\\left(${args[0]}\\right)'};
60960
60961 return sinh;
60962}
60963
60964/**
60965 * Calculate the hyperbolic sine of a number
60966 * @param {number} x
60967 * @returns {number}
60968 * @private
60969 */
60970var _sinh = Math.sinh || function (x) {
60971 return (Math.exp(x) - Math.exp(-x)) / 2;
60972};
60973
60974exports.name = 'sinh';
60975exports.factory = factory;
60976
60977
60978/***/ }),
60979/* 542 */
60980/***/ (function(module, exports, __webpack_require__) {
60981
60982"use strict";
60983
60984
60985var deepMap = __webpack_require__(1);
60986
60987function factory (type, config, load, typed) {
60988 /**
60989 * Calculate the tangent of a value. `tan(x)` is equal to `sin(x) / cos(x)`.
60990 *
60991 * For matrices, the function is evaluated element wise.
60992 *
60993 * Syntax:
60994 *
60995 * math.tan(x)
60996 *
60997 * Examples:
60998 *
60999 * math.tan(0.5); // returns number 0.5463024898437905
61000 * math.sin(0.5) / math.cos(0.5); // returns number 0.5463024898437905
61001 * math.tan(math.pi / 4); // returns number 1
61002 * math.tan(math.unit(45, 'deg')); // returns number 1
61003 *
61004 * See also:
61005 *
61006 * atan, sin, cos
61007 *
61008 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
61009 * @return {number | BigNumber | Complex | Array | Matrix} Tangent of x
61010 */
61011 var tan = typed('tan', {
61012 'number': Math.tan,
61013
61014 'Complex': function (x) {
61015 return x.tan();
61016 },
61017
61018 'BigNumber': function (x) {
61019 return x.tan();
61020 },
61021
61022 'Unit': function (x) {
61023 if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
61024 throw new TypeError ('Unit in function tan is no angle');
61025 }
61026 return tan(x.value);
61027 },
61028
61029 'Array | Matrix': function (x) {
61030 // deep map collection, skip zeros since tan(0) = 0
61031 return deepMap(x, tan, true);
61032 }
61033 });
61034
61035 tan.toTex = {1: '\\tan\\left(${args[0]}\\right)'};
61036
61037 return tan;
61038}
61039
61040exports.name = 'tan';
61041exports.factory = factory;
61042
61043
61044/***/ }),
61045/* 543 */
61046/***/ (function(module, exports, __webpack_require__) {
61047
61048"use strict";
61049
61050
61051var deepMap = __webpack_require__(1);
61052
61053function factory (type, config, load, typed) {
61054 /**
61055 * Calculate the hyperbolic tangent of a value,
61056 * defined as `tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1)`.
61057 *
61058 * For matrices, the function is evaluated element wise.
61059 *
61060 * Syntax:
61061 *
61062 * math.tanh(x)
61063 *
61064 * Examples:
61065 *
61066 * // tanh(x) = sinh(x) / cosh(x) = 1 / coth(x)
61067 * math.tanh(0.5); // returns 0.46211715726000974
61068 * math.sinh(0.5) / math.cosh(0.5); // returns 0.46211715726000974
61069 * 1 / math.coth(0.5); // returns 0.46211715726000974
61070 *
61071 * See also:
61072 *
61073 * sinh, cosh, coth
61074 *
61075 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
61076 * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic tangent of x
61077 */
61078 var tanh = typed('tanh', {
61079 'number': _tanh,
61080
61081 'Complex': function (x) {
61082 return x.tanh();
61083 },
61084
61085 'BigNumber': function (x) {
61086 return x.tanh();
61087 },
61088
61089 'Unit': function (x) {
61090 if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
61091 throw new TypeError ('Unit in function tanh is no angle');
61092 }
61093 return tanh(x.value);
61094 },
61095
61096 'Array | Matrix': function (x) {
61097 // deep map collection, skip zeros since tanh(0) = 0
61098 return deepMap(x, tanh, true);
61099 }
61100 });
61101
61102 tanh.toTex = {1: '\\tanh\\left(${args[0]}\\right)'};
61103
61104 return tanh;
61105}
61106
61107/**
61108 * Calculate the hyperbolic tangent of a number
61109 * @param {number} x
61110 * @returns {number}
61111 * @private
61112 */
61113var _tanh = Math.tanh || function (x) {
61114 var e = Math.exp(2 * x);
61115 return (e - 1) / (e + 1);
61116};
61117
61118exports.name = 'tanh';
61119exports.factory = factory;
61120
61121
61122/***/ }),
61123/* 544 */
61124/***/ (function(module, exports, __webpack_require__) {
61125
61126module.exports = [
61127 __webpack_require__(545)
61128];
61129
61130/***/ }),
61131/* 545 */
61132/***/ (function(module, exports, __webpack_require__) {
61133
61134"use strict";
61135
61136
61137function factory (type, config, load, typed) {
61138 var latex = __webpack_require__(4);
61139
61140 var matrix = load(__webpack_require__(0));
61141
61142 var algorithm13 = load(__webpack_require__(8));
61143 var algorithm14 = load(__webpack_require__(6));
61144
61145 /**
61146 * Change the unit of a value.
61147 *
61148 * For matrices, the function is evaluated element wise.
61149 *
61150 * Syntax:
61151 *
61152 * math.to(x, unit)
61153 *
61154 * Examples:
61155 *
61156 * math.to(math.unit('2 inch'), 'cm'); // returns Unit 5.08 cm
61157 * math.to(math.unit('2 inch'), math.unit(null, 'cm')); // returns Unit 5.08 cm
61158 * math.to(math.unit(16, 'bytes'), 'bits'); // returns Unit 128 bits
61159 *
61160 * See also:
61161 *
61162 * unit
61163 *
61164 * @param {Unit | Array | Matrix} x The unit to be converted.
61165 * @param {Unit | Array | Matrix} unit New unit. Can be a string like "cm"
61166 * or a unit without value.
61167 * @return {Unit | Array | Matrix} value with changed, fixed unit.
61168 */
61169 var to = typed('to', {
61170
61171 'Unit, Unit | string': function (x, unit) {
61172 return x.to(unit);
61173 },
61174
61175 'Matrix, Matrix': function (x, y) {
61176 // SparseMatrix does not support Units
61177 return algorithm13(x, y, to);
61178 },
61179
61180 'Array, Array': function (x, y) {
61181 // use matrix implementation
61182 return to(matrix(x), matrix(y)).valueOf();
61183 },
61184
61185 'Array, Matrix': function (x, y) {
61186 // use matrix implementation
61187 return to(matrix(x), y);
61188 },
61189
61190 'Matrix, Array': function (x, y) {
61191 // use matrix implementation
61192 return to(x, matrix(y));
61193 },
61194
61195 'Matrix, any': function (x, y) {
61196 // SparseMatrix does not support Units
61197 return algorithm14(x, y, to, false);
61198 },
61199
61200 'any, Matrix': function (x, y) {
61201 // SparseMatrix does not support Units
61202 return algorithm14(y, x, to, true);
61203 },
61204
61205 'Array, any': function (x, y) {
61206 // use matrix implementation
61207 return algorithm14(matrix(x), y, to, false).valueOf();
61208 },
61209
61210 'any, Array': function (x, y) {
61211 // use matrix implementation
61212 return algorithm14(matrix(y), x, to, true).valueOf();
61213 }
61214 });
61215
61216 to.toTex = {
61217 2: '\\left(${args[0]}' + latex.operators['to'] + '${args[1]}\\right)'
61218 };
61219
61220 return to;
61221}
61222
61223exports.name = 'to';
61224exports.factory = factory;
61225
61226
61227/***/ }),
61228/* 546 */
61229/***/ (function(module, exports, __webpack_require__) {
61230
61231module.exports = [
61232 __webpack_require__(123),
61233 __webpack_require__(51),
61234 __webpack_require__(58),
61235 __webpack_require__(75),
61236 __webpack_require__(57),
61237 __webpack_require__(547),
61238 __webpack_require__(83),
61239 __webpack_require__(548),
61240 __webpack_require__(76)
61241];
61242
61243
61244/***/ }),
61245/* 547 */
61246/***/ (function(module, exports, __webpack_require__) {
61247
61248"use strict";
61249
61250
61251var deepMap = __webpack_require__(1);
61252
61253
61254function factory (type, config, load, typed) {
61255 /**
61256 * Test whether a value is prime: has no divisors other than itself and one.
61257 * The function supports type `number`, `bignumber`.
61258 *
61259 * The function is evaluated element-wise in case of Array or Matrix input.
61260 *
61261 * Syntax:
61262 *
61263 * math.isPrime(x)
61264 *
61265 * Examples:
61266 *
61267 * math.isPrime(3); // returns true
61268 * math.isPrime(-2); // returns false
61269 * math.isPrime(0); // returns false
61270 * math.isPrime(-0); // returns false
61271 * math.isPrime(0.5); // returns false
61272 * math.isPrime('2'); // returns true
61273 * math.isPrime([2, 17, 100]'); // returns [true, true, false]
61274 *
61275 * See also:
61276 *
61277 * isNumeric, isZero, isNegative, isInteger
61278 *
61279 * @param {number | BigNumber | Array | Matrix} x Value to be tested
61280 * @return {boolean} Returns true when `x` is larger than zero.
61281 * Throws an error in case of an unknown data type.
61282 */
61283 var isPrime = typed('isPrime', {
61284 'number': function (x) {
61285 if (x < 2){
61286 return false;
61287 }
61288 if (x == 2){
61289 return true;
61290 }
61291 if (x % 2 == 0){
61292 return false;
61293 }
61294 for (var i = 3; i * i <= x; i += 2){
61295 if (x % i == 0){
61296 return false;
61297 }
61298 }
61299 return true;
61300 },
61301
61302 'BigNumber': function (x) {
61303 if (x.lt(2)){
61304 return false;
61305 }
61306 if (x.equals(2)){
61307 return true;
61308 }
61309 if (x.mod(2).isZero()){
61310 return false;
61311 }
61312 for(var i = type.BigNumber(3); i.times(i).lte(x); i = i.plus(1)){
61313 if (x.mod(i).isZero()){
61314 return false;
61315 }
61316 }
61317 return true;
61318 },
61319
61320 'Array | Matrix': function (x) {
61321 return deepMap(x, isPrime);
61322 }
61323 });
61324
61325 return isPrime;
61326}
61327
61328exports.name = 'isPrime';
61329exports.factory = factory;
61330
61331
61332/***/ }),
61333/* 548 */
61334/***/ (function(module, exports, __webpack_require__) {
61335
61336"use strict";
61337
61338
61339var deepMap = __webpack_require__(1);
61340var number = __webpack_require__(3);
61341
61342function factory (type, config, load, typed) {
61343 /**
61344 * Test whether a value is NaN (not a number).
61345 * The function supports types `number`, `BigNumber`, `Fraction`, `Unit` and `Complex`.
61346 *
61347 * The function is evaluated element-wise in case of Array or Matrix input.
61348 *
61349 * Syntax:
61350 *
61351 * math.isNaN(x)
61352 *
61353 * Examples:
61354 *
61355 * math.isNaN(3); // returns false
61356 * math.isNaN(NaN); // returns true
61357 * math.isNaN(0); // returns false
61358 * math.isNaN(math.bignumber(NaN)); // returns true
61359 * math.isNaN(math.bignumber(0)); // returns false
61360 * math.isNaN(math.fraction(-2, 5)); // returns false
61361 * math.isNaN('-2'); // returns false
61362 * math.isNaN([2, 0, -3, NaN]'); // returns [false, false, false, true]
61363 *
61364 * See also:
61365 *
61366 * isNumeric, isNegative, isPositive, isZero, isInteger
61367 *
61368 * @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested
61369 * @return {boolean} Returns true when `x` is NaN.
61370 * Throws an error in case of an unknown data type.
61371 */
61372 var isNaN = typed('isNaN', {
61373 'number': function (x) {
61374 return Number.isNaN(x);
61375 },
61376
61377 'BigNumber': function (x) {
61378 return x.isNaN();
61379 },
61380
61381 'Fraction': function (x) {
61382 return false;
61383 },
61384
61385 'Complex': function (x) {
61386 return x.isNaN();
61387 },
61388
61389 'Unit': function (x) {
61390 return Number.isNaN(x.value);
61391 },
61392
61393 'Array | Matrix': function (x) {
61394 return deepMap(x, Number.isNaN);
61395 }
61396 });
61397
61398 return isNaN;
61399}
61400
61401exports.name = 'isNaN';
61402exports.factory = factory;
61403
61404
61405/***/ }),
61406/* 549 */
61407/***/ (function(module, exports, __webpack_require__) {
61408
61409module.exports = [
61410 __webpack_require__(550)
61411];
61412
61413
61414/***/ }),
61415/* 550 */
61416/***/ (function(module, exports, __webpack_require__) {
61417
61418"use strict";
61419
61420
61421function factory (type, config, load, typed) {
61422 /**
61423 * Instantiate mathjs data types from their JSON representation
61424 * @param {string} key
61425 * @param {*} value
61426 * @returns {*} Returns the revived object
61427 */
61428 return function reviver(key, value) {
61429 var constructor = type[value && value.mathjs];
61430 if (constructor && typeof constructor.fromJSON === 'function') {
61431 return constructor.fromJSON(value);
61432 }
61433
61434 return value;
61435 }
61436}
61437
61438exports.name = 'reviver';
61439exports.path = 'json';
61440exports.factory = factory;
61441
61442
61443/***/ }),
61444/* 551 */
61445/***/ (function(module, exports, __webpack_require__) {
61446
61447"use strict";
61448
61449
61450var ArgumentsError = __webpack_require__(44);
61451var DimensionError = __webpack_require__(11);
61452var IndexError = __webpack_require__(53);
61453
61454module.exports = [
61455 {
61456 name: 'ArgumentsError', path: 'error',
61457 factory: function () {
61458 return ArgumentsError;
61459 }
61460 },
61461 {
61462 name: 'DimensionError',
61463 path: 'error',
61464 factory: function () {
61465 return DimensionError;
61466 }
61467 },
61468 {
61469 name: 'IndexError',
61470 path: 'error',
61471 factory: function () {
61472 return IndexError;
61473 }
61474 }
61475];
61476
61477// TODO: implement an InvalidValueError?
61478
61479
61480/***/ })
61481/******/ ]);
61482});
\No newline at end of file