'use strict';

var require$$0 = require('crypto');
var obsidian = require('obsidian');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

function _interopNamespace(e) {
    if (e && e.__esModule) return e;
    var n = Object.create(null);
    if (e) {
        Object.keys(e).forEach(function (k) {
            if (k !== 'default') {
                var d = Object.getOwnPropertyDescriptor(e, k);
                Object.defineProperty(n, k, d.get ? d : {
                    enumerable: true,
                    get: function () { return e[k]; }
                });
            }
        });
    }
    n["default"] = e;
    return Object.freeze(n);
}

var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

function getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

var _extends$2 = {exports: {}};

(function (module) {
function _extends() {
  return (module.exports = _extends = Object.assign ? Object.assign.bind() : function (n) {
    for (var e = 1; e < arguments.length; e++) {
      var t = arguments[e];
      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
    }
    return n;
  }, module.exports.__esModule = true, module.exports["default"] = module.exports), _extends.apply(null, arguments);
}
module.exports = _extends, module.exports.__esModule = true, module.exports["default"] = module.exports;
}(_extends$2));

var _extends$1 = /*@__PURE__*/getDefaultExportFromCjs(_extends$2.exports);

var DEFAULT_CONFIG = {
  // minimum relative difference between two compared values,
  // used by all comparison functions
  relTol: 1e-12,
  // minimum absolute difference between two compared values,
  // used by all comparison functions
  absTol: 1e-15,
  // type of default matrix output. Choose 'matrix' (default) or 'array'
  matrix: 'Matrix',
  // type of default number output. Choose 'number' (default) 'BigNumber', 'bigint', or 'Fraction'
  number: 'number',
  // type of fallback used for config { number: 'bigint' } when a value cannot be represented
  // in the configured numeric type. Choose 'number' (default) or 'BigNumber'.
  numberFallback: 'number',
  // number of significant digits in BigNumbers
  precision: 64,
  // predictable output type of functions. When true, output type depends only
  // on the input types. When false (default), output type can vary depending
  // on input values. For example `math.sqrt(-4)` returns `complex('2i')` when
  // predictable is false, and returns `NaN` when true.
  predictable: false,
  // random seed for seeded pseudo random number generation
  // null = randomly seed
  randomSeed: null
};

// type checks for all known types
//
// note that:
//
// - check by duck-typing on a property like `isUnit`, instead of checking instanceof.
//   instanceof cannot be used because that would not allow to pass data from
//   one instance of math.js to another since each has it's own instance of Unit.
// - check the `isUnit` property via the constructor, so there will be no
//   matches for "fake" instances like plain objects with a property `isUnit`.
//   That is important for security reasons.
// - It must not be possible to override the type checks used internally,
//   for security reasons, so these functions are not exposed in the expression
//   parser.

function isNumber(x) {
  return typeof x === 'number';
}
function isBigNumber(x) {
  if (!x || typeof x !== 'object' || typeof x.constructor !== 'function') {
    return false;
  }
  if (x.isBigNumber === true && typeof x.constructor.prototype === 'object' && x.constructor.prototype.isBigNumber === true) {
    return true;
  }
  if (typeof x.constructor.isDecimal === 'function' && x.constructor.isDecimal(x) === true) {
    return true;
  }
  return false;
}
function isBigInt(x) {
  return typeof x === 'bigint';
}
function isComplex(x) {
  return x && typeof x === 'object' && Object.getPrototypeOf(x).isComplex === true || false;
}
function isFraction(x) {
  return x && typeof x === 'object' && Object.getPrototypeOf(x).isFraction === true || false;
}
function isUnit(x) {
  return x && x.constructor.prototype.isUnit === true || false;
}
function isString(x) {
  return typeof x === 'string';
}
var isArray = Array.isArray;
function isMatrix(x) {
  return x && x.constructor.prototype.isMatrix === true || false;
}

/**
 * Test whether a value is a collection: an Array or Matrix
 * @param {*} x
 * @returns {boolean} isCollection
 */
function isCollection(x) {
  return Array.isArray(x) || isMatrix(x);
}
function isDenseMatrix(x) {
  return x && x.isDenseMatrix && x.constructor.prototype.isMatrix === true || false;
}
function isSparseMatrix(x) {
  return x && x.isSparseMatrix && x.constructor.prototype.isMatrix === true || false;
}
function isRange(x) {
  return x && x.constructor.prototype.isRange === true || false;
}
function isIndex(x) {
  return x && x.constructor.prototype.isIndex === true || false;
}
function isBoolean(x) {
  return typeof x === 'boolean';
}
function isResultSet(x) {
  return x && x.constructor.prototype.isResultSet === true || false;
}
function isHelp(x) {
  return x && x.constructor.prototype.isHelp === true || false;
}
function isFunction(x) {
  return typeof x === 'function';
}
function isDate(x) {
  return x instanceof Date;
}
function isRegExp(x) {
  return x instanceof RegExp;
}
function isObject(x) {
  return !!(x && typeof x === 'object' && x.constructor === Object && !isComplex(x) && !isFraction(x));
}
function isNull(x) {
  return x === null;
}
function isUndefined(x) {
  return x === undefined;
}
function isAccessorNode(x) {
  return x && x.isAccessorNode === true && x.constructor.prototype.isNode === true || false;
}
function isArrayNode(x) {
  return x && x.isArrayNode === true && x.constructor.prototype.isNode === true || false;
}
function isAssignmentNode(x) {
  return x && x.isAssignmentNode === true && x.constructor.prototype.isNode === true || false;
}
function isBlockNode(x) {
  return x && x.isBlockNode === true && x.constructor.prototype.isNode === true || false;
}
function isConditionalNode(x) {
  return x && x.isConditionalNode === true && x.constructor.prototype.isNode === true || false;
}
function isConstantNode(x) {
  return x && x.isConstantNode === true && x.constructor.prototype.isNode === true || false;
}

/* Very specialized: returns true for those nodes which in the numerator of
   a fraction means that the division in that fraction has precedence over implicit
   multiplication, e.g. -2/3 x parses as (-2/3) x and 3/4 x parses as (3/4) x but
   6!/8 x parses as 6! / (8x). It is located here because it is shared between
   parse.js and OperatorNode.js (for parsing and printing, respectively).

   This should *not* be exported from mathjs, unlike most of the tests here.
   Its name does not start with 'is' to prevent utils/snapshot.js from thinking
   it should be exported.
*/
function rule2Node(node) {
  return isConstantNode(node) || isOperatorNode(node) && node.args.length === 1 && isConstantNode(node.args[0]) && '-+~'.includes(node.op);
}
function isFunctionAssignmentNode(x) {
  return x && x.isFunctionAssignmentNode === true && x.constructor.prototype.isNode === true || false;
}
function isFunctionNode(x) {
  return x && x.isFunctionNode === true && x.constructor.prototype.isNode === true || false;
}
function isIndexNode(x) {
  return x && x.isIndexNode === true && x.constructor.prototype.isNode === true || false;
}
function isNode(x) {
  return x && x.isNode === true && x.constructor.prototype.isNode === true || false;
}
function isObjectNode(x) {
  return x && x.isObjectNode === true && x.constructor.prototype.isNode === true || false;
}
function isOperatorNode(x) {
  return x && x.isOperatorNode === true && x.constructor.prototype.isNode === true || false;
}
function isParenthesisNode(x) {
  return x && x.isParenthesisNode === true && x.constructor.prototype.isNode === true || false;
}
function isRangeNode(x) {
  return x && x.isRangeNode === true && x.constructor.prototype.isNode === true || false;
}
function isRelationalNode(x) {
  return x && x.isRelationalNode === true && x.constructor.prototype.isNode === true || false;
}
function isSymbolNode(x) {
  return x && x.isSymbolNode === true && x.constructor.prototype.isNode === true || false;
}
function isChain(x) {
  return x && x.constructor.prototype.isChain === true || false;
}
function typeOf(x) {
  var t = typeof x;
  if (t === 'object') {
    if (x === null) return 'null';
    if (isBigNumber(x)) return 'BigNumber'; // Special: weird mashup with Decimal
    if (x.constructor && x.constructor.name) return x.constructor.name;
    return 'Object'; // just in case
  }
  return t; // can be 'string', 'number', 'boolean', 'function', 'bigint', ...
}

/**
 * Clone an object
 *
 *     clone(x)
 *
 * Can clone any primitive type, array, and object.
 * If x has a function clone, this function will be invoked to clone the object.
 *
 * @param {*} x
 * @return {*} clone
 */
function clone$2(x) {
  var type = typeof x;

  // immutable primitive types
  if (type === 'number' || type === 'bigint' || type === 'string' || type === 'boolean' || x === null || x === undefined) {
    return x;
  }

  // use clone function of the object when available
  if (typeof x.clone === 'function') {
    return x.clone();
  }

  // array
  if (Array.isArray(x)) {
    return x.map(function (value) {
      return clone$2(value);
    });
  }
  if (x instanceof Date) return new Date(x.valueOf());
  if (isBigNumber(x)) return x; // bignumbers are immutable

  // object
  if (isObject(x)) {
    return mapObject(x, clone$2);
  }
  throw new TypeError("Cannot clone: unknown type of value (value: ".concat(x, ")"));
}

/**
 * Apply map to all properties of an object
 * @param {Object} object
 * @param {function} callback
 * @return {Object} Returns a copy of the object with mapped properties
 */
function mapObject(object, callback) {
  var clone = {};
  for (var key in object) {
    if (hasOwnProperty(object, key)) {
      clone[key] = callback(object[key]);
    }
  }
  return clone;
}

/**
 * Extend object a with the properties of object b
 * @param {Object} a
 * @param {Object} b
 * @return {Object} a
 */
function extend(a, b) {
  for (var prop in b) {
    if (hasOwnProperty(b, prop)) {
      a[prop] = b[prop];
    }
  }
  return a;
}

/**
 * Deep extend an object a with the properties of object b
 * @param {Object} a
 * @param {Object} b
 * @returns {Object}
 */
function deepExtend(a, b) {
  // TODO: add support for Arrays to deepExtend
  if (Array.isArray(b)) {
    throw new TypeError('Arrays are not supported by deepExtend');
  }
  for (var prop in b) {
    // We check against prop not being in Object.prototype or Function.prototype
    // to prevent polluting for example Object.__proto__.
    if (hasOwnProperty(b, prop) && !(prop in Object.prototype) && !(prop in Function.prototype)) {
      if (b[prop] && b[prop].constructor === Object) {
        if (a[prop] === undefined) {
          a[prop] = {};
        }
        if (a[prop] && a[prop].constructor === Object) {
          deepExtend(a[prop], b[prop]);
        } else {
          a[prop] = b[prop];
        }
      } else if (Array.isArray(b[prop])) {
        throw new TypeError('Arrays are not supported by deepExtend');
      } else {
        a[prop] = b[prop];
      }
    }
  }
  return a;
}

/**
 * Deep test equality of all fields in two pairs of arrays or objects.
 * Compares values and functions strictly (ie. 2 is not the same as '2').
 * @param {Array | Object} a
 * @param {Array | Object} b
 * @returns {boolean}
 */
function deepStrictEqual(a, b) {
  var prop, i, len;
  if (Array.isArray(a)) {
    if (!Array.isArray(b)) {
      return false;
    }
    if (a.length !== b.length) {
      return false;
    }
    for (i = 0, len = a.length; i < len; i++) {
      if (!deepStrictEqual(a[i], b[i])) {
        return false;
      }
    }
    return true;
  } else if (typeof a === 'function') {
    return a === b;
  } else if (a instanceof Object) {
    if (Array.isArray(b) || !(b instanceof Object)) {
      return false;
    }
    for (prop in a) {
      // noinspection JSUnfilteredForInLoop
      if (!(prop in b) || !deepStrictEqual(a[prop], b[prop])) {
        return false;
      }
    }
    for (prop in b) {
      // noinspection JSUnfilteredForInLoop
      if (!(prop in a)) {
        return false;
      }
    }
    return true;
  } else {
    return a === b;
  }
}

/**
 * Recursively flatten a nested object.
 * @param {Object} nestedObject
 * @return {Object} Returns the flattened object
 */
function deepFlatten(nestedObject) {
  var flattenedObject = {};
  _deepFlatten(nestedObject, flattenedObject);
  return flattenedObject;
}

// helper function used by deepFlatten
function _deepFlatten(nestedObject, flattenedObject) {
  for (var prop in nestedObject) {
    if (hasOwnProperty(nestedObject, prop)) {
      var value = nestedObject[prop];
      if (typeof value === 'object' && value !== null) {
        _deepFlatten(value, flattenedObject);
      } else {
        flattenedObject[prop] = value;
      }
    }
  }
}

/**
 * Attach a lazy loading property to a constant.
 * The given function `fn` is called once when the property is first requested.
 *
 * @param {Object} object         Object where to add the property
 * @param {string} prop           Property name
 * @param {Function} valueResolver Function returning the property value. Called
 *                                without arguments.
 */
function lazy(object, prop, valueResolver) {
  var _uninitialized = true;
  var _value;
  Object.defineProperty(object, prop, {
    get: function get() {
      if (_uninitialized) {
        _value = valueResolver();
        _uninitialized = false;
      }
      return _value;
    },
    set: function set(value) {
      _value = value;
      _uninitialized = false;
    },
    configurable: true,
    enumerable: true
  });
}

/**
 * A safe hasOwnProperty
 * @param {Object} object
 * @param {string} property
 */
function hasOwnProperty(object, property) {
  return object && Object.hasOwnProperty.call(object, property);
}

/**
 * Test whether an object is a factory. a factory has fields:
 *
 * - factory: function (type: Object, config: Object, load: function, typed: function [, math: Object])   (required)
 * - name: string (optional)
 * - path: string    A dot separated path (optional)
 * - math: boolean   If true (false by default), the math namespace is passed
 *                   as fifth argument of the factory function
 *
 * @param {*} object
 * @returns {boolean}
 */
function isLegacyFactory(object) {
  return object && typeof object.factory === 'function';
}

/**
 * Shallow version of pick, creating an object composed of the picked object properties
 * but not for nested properties
 * @param {Object} object
 * @param {string[]} properties
 * @return {Object}
 */
function pickShallow(object, properties) {
  var copy = {};
  for (var i = 0; i < properties.length; i++) {
    var key = properties[i];
    var value = object[key];
    if (value !== undefined) {
      copy[key] = value;
    }
  }
  return copy;
}

var MATRIX_OPTIONS = ['Matrix', 'Array']; // valid values for option matrix
var NUMBER_OPTIONS = ['number', 'BigNumber', 'Fraction']; // valid values for option number

function configFactory(config, emit) {
  /**
   * Set configuration options for math.js, and get current options.
   * Will emit a 'config' event, with arguments (curr, prev, changes).
   *
   * This function is only available on a mathjs instance created using `create`.
   *
   * Syntax:
   *
   *     math.config(config: Object): Object
   *
   * Examples:
   *
   *
   *     import { create, all } from 'mathjs'
   *
   *     // create a mathjs instance
   *     const math = create(all)
   *
   *     math.config().number                // outputs 'number'
   *     math.evaluate('0.4')                // outputs number 0.4
   *     math.config({number: 'Fraction'})
   *     math.evaluate('0.4')                // outputs Fraction 2/5
   *
   * @param {Object} [options] Available options:
   *                            {number} relTol
   *                              Minimum relative difference between two
   *                              compared values, used by all comparison functions.
   *                            {number} absTol
   *                              Minimum absolute difference between two
   *                              compared values, used by all comparison functions.
   *                            {string} matrix
   *                              A string 'Matrix' (default) or 'Array'.
   *                            {string} number
   *                              A string 'number' (default), 'BigNumber', 'bigint', or 'Fraction'
   *                            {number} precision
   *                              The number of significant digits for BigNumbers.
   *                              Not applicable for Numbers.
   *                            {string} parenthesis
   *                              How to display parentheses in LaTeX and string
   *                              output.
   *                            {string} randomSeed
   *                              Random seed for seeded pseudo random number generator.
   *                              Set to null to randomly seed.
   * @return {Object} Returns the current configuration
   */
  function _config(options) {
    if (options) {
      if (options.epsilon !== undefined) {
        // this if is only for backwards compatibility, it can be removed in the future.
        console.warn('Warning: The configuration option "epsilon" is deprecated. Use "relTol" and "absTol" instead.');
        var optionsFix = clone$2(options);
        optionsFix.relTol = options.epsilon;
        optionsFix.absTol = options.epsilon * 1e-3;
        delete optionsFix.epsilon;
        return _config(optionsFix);
      }
      var prev = clone$2(config);

      // validate some of the options
      validateOption(options, 'matrix', MATRIX_OPTIONS);
      validateOption(options, 'number', NUMBER_OPTIONS);

      // merge options
      deepExtend(config, options);
      var curr = clone$2(config);
      var changes = clone$2(options);

      // emit 'config' event
      emit('config', curr, prev, changes);
      return curr;
    } else {
      return clone$2(config);
    }
  }

  // attach the valid options to the function so they can be extended
  _config.MATRIX_OPTIONS = MATRIX_OPTIONS;
  _config.NUMBER_OPTIONS = NUMBER_OPTIONS;

  // attach the config properties as readonly properties to the config function
  Object.keys(DEFAULT_CONFIG).forEach(key => {
    Object.defineProperty(_config, key, {
      get: () => config[key],
      enumerable: true,
      configurable: true
    });
  });
  return _config;
}

/**
 * Validate an option
 * @param {Object} options         Object with options
 * @param {string} name            Name of the option to validate
 * @param {Array.<string>} values  Array with valid values for this option
 */
function validateOption(options, name, values) {
  if (options[name] !== undefined && !values.includes(options[name])) {
    // unknown value
    console.warn('Warning: Unknown value "' + options[name] + '" for configuration option "' + name + '". ' + 'Available options: ' + values.map(value => JSON.stringify(value)).join(', ') + '.');
  }
}

var typedFunction$1 = {exports: {}};

(function (module, exports) {
(function (global, factory) {
  module.exports = factory() ;
})(commonjsGlobal, (function () {
  function ok() {
    return true;
  }
  function notOk() {
    return false;
  }
  function undef() {
    return undefined;
  }
  const NOT_TYPED_FUNCTION = 'Argument is not a typed-function.';

  /**
   * @typedef {{
   *   params: Param[],
   *   fn: function,
   *   test: function,
   *   implementation: function
   * }} Signature
   *
   * @typedef {{
   *   types: Type[],
   *   hasAny: boolean,
   *   hasConversion: boolean,
   *   restParam: boolean
   * }} Param
   *
   * @typedef {{
   *   name: string,
   *   typeIndex: number,
   *   test: function,
   *   isAny: boolean,
   *   conversion?: ConversionDef,
   *   conversionIndex: number,
   * }} Type
   *
   * @typedef {{
   *   from: string,
   *   to: string,
   *   convert: function (*) : *
   * }} ConversionDef
   *
   * @typedef {{
   *   name: string,
   *   test: function(*) : boolean,
   *   isAny?: boolean
   * }} TypeDef
   */

  /**
   * @returns {() => function}
   */
  function create() {
    // data type tests

    /**
     * Returns true if the argument is a non-null "plain" object
     */
    function isPlainObject(x) {
      return typeof x === 'object' && x !== null && x.constructor === Object;
    }
    const _types = [{
      name: 'number',
      test: function (x) {
        return typeof x === 'number';
      }
    }, {
      name: 'string',
      test: function (x) {
        return typeof x === 'string';
      }
    }, {
      name: 'boolean',
      test: function (x) {
        return typeof x === 'boolean';
      }
    }, {
      name: 'Function',
      test: function (x) {
        return typeof x === 'function';
      }
    }, {
      name: 'Array',
      test: Array.isArray
    }, {
      name: 'Date',
      test: function (x) {
        return x instanceof Date;
      }
    }, {
      name: 'RegExp',
      test: function (x) {
        return x instanceof RegExp;
      }
    }, {
      name: 'Object',
      test: isPlainObject
    }, {
      name: 'null',
      test: function (x) {
        return x === null;
      }
    }, {
      name: 'undefined',
      test: function (x) {
        return x === undefined;
      }
    }];
    const anyType = {
      name: 'any',
      test: ok,
      isAny: true
    };

    // Data structures to track the types. As these are local variables in
    // create(), each typed universe will get its own copy, but the variables
    // will only be accessible through the (closures of the) functions supplied
    // as properties of the typed object, not directly.
    // These will be initialized in clear() below
    let typeMap; // primary store of all types
    let typeList; // Array of just type names, for the sake of ordering

    // And similar data structures for the type conversions:
    let nConversions = 0;
    // the actual conversions are stored on a property of the destination types

    // This is a temporary object, will be replaced with a function at the end
    let typed = {
      createCount: 0
    };

    /**
     * Takes a type name and returns the corresponding official type object
     * for that type.
     *
     * @param {string} typeName
     * @returns {TypeDef} type
     */
    function findType(typeName) {
      const type = typeMap.get(typeName);
      if (type) {
        return type;
      }
      // Remainder is error handling
      let message = 'Unknown type "' + typeName + '"';
      const name = typeName.toLowerCase();
      let otherName;
      for (otherName of typeList) {
        if (otherName.toLowerCase() === name) {
          message += '. Did you mean "' + otherName + '" ?';
          break;
        }
      }
      throw new TypeError(message);
    }

    /**
     * Adds an array `types` of type definitions to this typed instance.
     * Each type definition should be an object with properties:
     * 'name' - a string giving the name of the type; 'test' - function
     * returning a boolean that tests membership in the type; and optionally
     * 'isAny' - true only for the 'any' type.
     *
     * The second optional argument, `before`, gives the name of a type that
     * these types should be added before. The new types are added in the
     * order specified.
     * @param {TypeDef[]} types
     * @param {string | boolean} [beforeSpec='any'] before
     */
    function addTypes(types) {
      let beforeSpec = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'any';
      const beforeIndex = beforeSpec ? findType(beforeSpec).index : typeList.length;
      const newTypes = [];
      for (let i = 0; i < types.length; ++i) {
        if (!types[i] || typeof types[i].name !== 'string' || typeof types[i].test !== 'function') {
          throw new TypeError('Object with properties {name: string, test: function} expected');
        }
        const typeName = types[i].name;
        if (typeMap.has(typeName)) {
          throw new TypeError('Duplicate type name "' + typeName + '"');
        }
        newTypes.push(typeName);
        typeMap.set(typeName, {
          name: typeName,
          test: types[i].test,
          isAny: types[i].isAny,
          index: beforeIndex + i,
          conversionsTo: [] // Newly added type can't have any conversions to it
        });
      }
      // update the typeList
      const affectedTypes = typeList.slice(beforeIndex);
      typeList = typeList.slice(0, beforeIndex).concat(newTypes).concat(affectedTypes);
      // Fix the indices
      for (let i = beforeIndex + newTypes.length; i < typeList.length; ++i) {
        typeMap.get(typeList[i]).index = i;
      }
    }

    /**
     * Removes all types and conversions from this typed instance.
     * May cause previously constructed typed-functions to throw
     * strange errors when they are called with types that do not
     * match any of their signatures.
     */
    function clear() {
      typeMap = new Map();
      typeList = [];
      nConversions = 0;
      addTypes([anyType], false);
    }

    // initialize the types to the default list
    clear();
    addTypes(_types);

    /**
     * Removes all conversions, leaving the types alone.
     */
    function clearConversions() {
      let typeName;
      for (typeName of typeList) {
        typeMap.get(typeName).conversionsTo = [];
      }
      nConversions = 0;
    }

    /**
     * Find the type names that match a value.
     * @param {*} value
     * @return {string[]} Array of names of types for which
     *                  the type test matches the value.
     */
    function findTypeNames(value) {
      const matches = typeList.filter(name => {
        const type = typeMap.get(name);
        return !type.isAny && type.test(value);
      });
      if (matches.length) {
        return matches;
      }
      return ['any'];
    }

    /**
     * Check if an entity is a typed function created by any instance
     * @param {any} entity
     * @returns {boolean}
     */
    function isTypedFunction(entity) {
      return entity && typeof entity === 'function' && '_typedFunctionData' in entity;
    }

    /**
     * Find a specific signature from a (composed) typed function, for example:
     *
     *   typed.findSignature(fn, ['number', 'string'])
     *   typed.findSignature(fn, 'number, string')
     *   typed.findSignature(fn, 'number,string', {exact: true})
     *
     * This function findSignature will by default return the best match to
     * the given signature, possibly employing type conversions.
     *
     * The (optional) third argument is a plain object giving options
     * controlling the signature search. Currently the only implemented
     * option is `exact`: if specified as true (default is false), only
     * exact matches will be returned (i.e. signatures for which `fn` was
     * directly defined). Note that a (possibly different) type matching
     * `any`, or one or more instances of TYPE matching `...TYPE` are
     * considered exact matches in this regard, as no conversions are used.
     *
     * This function returns a "signature" object, as does `typed.resolve()`,
     * which is a plain object with four keys: `params` (the array of parameters
     * for this signature), `fn` (the originally supplied function for this
     * signature), `test` (a generated function that determines if an argument
     * list matches this signature, and `implementation` (the function to call
     * on a matching argument list, that performs conversions if necessary and
     * then calls the originally supplied function).
     *
     * @param {Function} fn                   A typed-function
     * @param {string | string[]} signature
     *     Signature to be found, can be an array or a comma separated string.
     * @param {object} options  Controls the signature search as documented
     * @return {{ params: Param[], fn: function, test: function, implementation: function }}
     *     Returns the matching signature, or throws an error when no signature
     *     is found.
     */
    function findSignature(fn, signature, options) {
      if (!isTypedFunction(fn)) {
        throw new TypeError(NOT_TYPED_FUNCTION);
      }

      // Canonicalize input
      const exact = options && options.exact;
      const stringSignature = Array.isArray(signature) ? signature.join(',') : signature;
      const params = parseSignature(stringSignature);
      const canonicalSignature = stringifyParams(params);

      // First hope we get lucky and exactly match a signature
      if (!exact || canonicalSignature in fn.signatures) {
        // OK, we can check the internal signatures
        const match = fn._typedFunctionData.signatureMap.get(canonicalSignature);
        if (match) {
          return match;
        }
      }

      // Oh well, we did not; so we have to go back and check the parameters
      // one by one, in order to catch things like `any` and rest params.
      // Note here we can assume there is at least one parameter, because
      // the empty signature would have matched successfully above.
      const nParams = params.length;
      let remainingSignatures;
      if (exact) {
        remainingSignatures = [];
        let name;
        for (name in fn.signatures) {
          remainingSignatures.push(fn._typedFunctionData.signatureMap.get(name));
        }
      } else {
        remainingSignatures = fn._typedFunctionData.signatures;
      }
      for (let i = 0; i < nParams; ++i) {
        const want = params[i];
        const filteredSignatures = [];
        let possibility;
        for (possibility of remainingSignatures) {
          const have = getParamAtIndex(possibility.params, i);
          if (!have || want.restParam && !have.restParam) {
            continue;
          }
          if (!have.hasAny) {
            // have to check all of the wanted types are available
            const haveTypes = paramTypeSet(have);
            if (want.types.some(wtype => !haveTypes.has(wtype.name))) {
              continue;
            }
          }
          // OK, this looks good
          filteredSignatures.push(possibility);
        }
        remainingSignatures = filteredSignatures;
        if (remainingSignatures.length === 0) break;
      }
      // Return the first remaining signature that was totally matched:
      let candidate;
      for (candidate of remainingSignatures) {
        if (candidate.params.length <= nParams) {
          return candidate;
        }
      }
      throw new TypeError('Signature not found (signature: ' + (fn.name || 'unnamed') + '(' + stringifyParams(params, ', ') + '))');
    }

    /**
     * Find the proper function to call for a specific signature from
     * a (composed) typed function, for example:
     *
     *   typed.find(fn, ['number', 'string'])
     *   typed.find(fn, 'number, string')
     *   typed.find(fn, 'number,string', {exact: true})
     *
     * This function find will by default return the best match to
     * the given signature, possibly employing type conversions (and returning
     * a function that will perform those conversions as needed). The
     * (optional) third argument is a plain object giving options contolling
     * the signature search. Currently only the option `exact` is implemented,
     * which defaults to "false". If `exact` is specified as true, then only
     * exact matches will be returned (i.e. signatures for which `fn` was
     * directly defined). Uses of `any` and `...TYPE` are considered exact if
     * no conversions are necessary to apply the corresponding function.
     *
     * @param {Function} fn                   A typed-function
     * @param {string | string[]} signature
     *     Signature to be found, can be an array or a comma separated string.
     * @param {object} options  Controls the signature match as documented
     * @return {function}
     *     Returns the function to call for the given signature, or throws an
     *     error if no match is found.
     */
    function find(fn, signature, options) {
      return findSignature(fn, signature, options).implementation;
    }

    /**
     * Convert a given value to another data type, specified by type name.
     *
     * @param {*} value
     * @param {string} typeName
     */
    function convert(value, typeName) {
      // check conversion is needed
      const type = findType(typeName);
      if (type.test(value)) {
        return value;
      }
      const conversions = type.conversionsTo;
      if (conversions.length === 0) {
        throw new Error('There are no conversions to ' + typeName + ' defined.');
      }
      for (let i = 0; i < conversions.length; i++) {
        const fromType = findType(conversions[i].from);
        if (fromType.test(value)) {
          return conversions[i].convert(value);
        }
      }
      throw new Error('Cannot convert ' + value + ' to ' + typeName);
    }

    /**
     * Stringify parameters in a normalized way
     * @param {Param[]} params
     * @param {string} [','] separator
     * @return {string}
     */
    function stringifyParams(params) {
      let separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';
      return params.map(p => p.name).join(separator);
    }

    /**
     * Parse a parameter, like "...number | boolean"
     * @param {string} param
     * @return {Param} param
     */
    function parseParam(param) {
      const restParam = param.indexOf('...') === 0;
      const types = !restParam ? param : param.length > 3 ? param.slice(3) : 'any';
      const typeDefs = types.split('|').map(s => findType(s.trim()));
      let hasAny = false;
      let paramName = restParam ? '...' : '';
      const exactTypes = typeDefs.map(function (type) {
        hasAny = type.isAny || hasAny;
        paramName += type.name + '|';
        return {
          name: type.name,
          typeIndex: type.index,
          test: type.test,
          isAny: type.isAny,
          conversion: null,
          conversionIndex: -1
        };
      });
      return {
        types: exactTypes,
        name: paramName.slice(0, -1),
        // remove trailing '|' from above
        hasAny,
        hasConversion: false,
        restParam
      };
    }

    /**
     * Expands a parsed parameter with the types available from currently
     * defined conversions.
     * @param {Param} param
     * @return {Param} param
     */
    function expandParam(param) {
      const typeNames = param.types.map(t => t.name);
      const matchingConversions = availableConversions(typeNames);
      let hasAny = param.hasAny;
      let newName = param.name;
      const convertibleTypes = matchingConversions.map(function (conversion) {
        const type = findType(conversion.from);
        hasAny = type.isAny || hasAny;
        newName += '|' + conversion.from;
        return {
          name: conversion.from,
          typeIndex: type.index,
          test: type.test,
          isAny: type.isAny,
          conversion,
          conversionIndex: conversion.index
        };
      });
      return {
        types: param.types.concat(convertibleTypes),
        name: newName,
        hasAny,
        hasConversion: convertibleTypes.length > 0,
        restParam: param.restParam
      };
    }

    /**
     * Return the set of type names in a parameter.
     * Caches the result for efficiency
     *
     * @param {Param} param
     * @return {Set<string>} typenames
     */
    function paramTypeSet(param) {
      if (!param.typeSet) {
        param.typeSet = new Set();
        param.types.forEach(type => param.typeSet.add(type.name));
      }
      return param.typeSet;
    }

    /**
     * Parse a signature with comma separated parameters,
     * like "number | boolean, ...string"
     *
     * @param {string} signature
     * @return {Param[]} params
     */
    function parseSignature(rawSignature) {
      const params = [];
      if (typeof rawSignature !== 'string') {
        throw new TypeError('Signatures must be strings');
      }
      const signature = rawSignature.trim();
      if (signature === '') {
        return params;
      }
      const rawParams = signature.split(',');
      for (let i = 0; i < rawParams.length; ++i) {
        const parsedParam = parseParam(rawParams[i].trim());
        if (parsedParam.restParam && i !== rawParams.length - 1) {
          throw new SyntaxError('Unexpected rest parameter "' + rawParams[i] + '": ' + 'only allowed for the last parameter');
        }
        // if invalid, short-circuit (all the types may have been filtered)
        if (parsedParam.types.length === 0) {
          return null;
        }
        params.push(parsedParam);
      }
      return params;
    }

    /**
     * Test whether a set of params contains a restParam
     * @param {Param[]} params
     * @return {boolean} Returns true when the last parameter is a restParam
     */
    function hasRestParam(params) {
      const param = last(params);
      return param ? param.restParam : false;
    }

    /**
     * Create a type test for a single parameter, which can have one or multiple
     * types.
     * @param {Param} param
     * @return {function(x: *) : boolean} Returns a test function
     */
    function compileTest(param) {
      if (!param || param.types.length === 0) {
        // nothing to do
        return ok;
      } else if (param.types.length === 1) {
        return findType(param.types[0].name).test;
      } else if (param.types.length === 2) {
        const test0 = findType(param.types[0].name).test;
        const test1 = findType(param.types[1].name).test;
        return function or(x) {
          return test0(x) || test1(x);
        };
      } else {
        // param.types.length > 2
        const tests = param.types.map(function (type) {
          return findType(type.name).test;
        });
        return function or(x) {
          for (let i = 0; i < tests.length; i++) {
            if (tests[i](x)) {
              return true;
            }
          }
          return false;
        };
      }
    }

    /**
     * Create a test for all parameters of a signature
     * @param {Param[]} params
     * @return {function(args: Array<*>) : boolean}
     */
    function compileTests(params) {
      let tests, test0, test1;
      if (hasRestParam(params)) {
        // variable arguments like '...number'
        tests = initial(params).map(compileTest);
        const varIndex = tests.length;
        const lastTest = compileTest(last(params));
        const testRestParam = function (args) {
          for (let i = varIndex; i < args.length; i++) {
            if (!lastTest(args[i])) {
              return false;
            }
          }
          return true;
        };
        return function testArgs(args) {
          for (let i = 0; i < tests.length; i++) {
            if (!tests[i](args[i])) {
              return false;
            }
          }
          return testRestParam(args) && args.length >= varIndex + 1;
        };
      } else {
        // no variable arguments
        if (params.length === 0) {
          return function testArgs(args) {
            return args.length === 0;
          };
        } else if (params.length === 1) {
          test0 = compileTest(params[0]);
          return function testArgs(args) {
            return test0(args[0]) && args.length === 1;
          };
        } else if (params.length === 2) {
          test0 = compileTest(params[0]);
          test1 = compileTest(params[1]);
          return function testArgs(args) {
            return test0(args[0]) && test1(args[1]) && args.length === 2;
          };
        } else {
          // arguments.length > 2
          tests = params.map(compileTest);
          return function testArgs(args) {
            for (let i = 0; i < tests.length; i++) {
              if (!tests[i](args[i])) {
                return false;
              }
            }
            return args.length === tests.length;
          };
        }
      }
    }

    /**
     * Find the parameter at a specific index of a Params list.
     * Handles rest parameters.
     * @param {Param[]} params
     * @param {number} index
     * @return {Param | null} Returns the matching parameter when found,
     *                        null otherwise.
     */
    function getParamAtIndex(params, index) {
      return index < params.length ? params[index] : hasRestParam(params) ? last(params) : null;
    }

    /**
     * Get all type names of a parameter
     * @param {Params[]} params
     * @param {number} index
     * @return {string[]} Returns an array with type names
     */
    function getTypeSetAtIndex(params, index) {
      const param = getParamAtIndex(params, index);
      if (!param) {
        return new Set();
      }
      return paramTypeSet(param);
    }

    /**
     * Test whether a type is an exact type or conversion
     * @param {Type} type
     * @return {boolean} Returns true when
     */
    function isExactType(type) {
      return type.conversion === null || type.conversion === undefined;
    }

    /**
     * Helper function for creating error messages: create an array with
     * all available types on a specific argument index.
     * @param {Signature[]} signatures
     * @param {number} index
     * @return {string[]} Returns an array with available types
     */
    function mergeExpectedParams(signatures, index) {
      const typeSet = new Set();
      signatures.forEach(signature => {
        const paramSet = getTypeSetAtIndex(signature.params, index);
        let name;
        for (name of paramSet) {
          typeSet.add(name);
        }
      });
      return typeSet.has('any') ? ['any'] : Array.from(typeSet);
    }

    /**
     * Create
     * @param {string} name             The name of the function
     * @param {array.<*>} args          The actual arguments passed to the function
     * @param {Signature[]} signatures  A list with available signatures
     * @return {TypeError} Returns a type error with additional data
     *                     attached to it in the property `data`
     */
    function createError(name, args, signatures) {
      let err, expected;
      const _name = name || 'unnamed';

      // test for wrong type at some index
      let matchingSignatures = signatures;
      let index;
      for (index = 0; index < args.length; index++) {
        const nextMatchingDefs = [];
        matchingSignatures.forEach(signature => {
          const param = getParamAtIndex(signature.params, index);
          const test = compileTest(param);
          if ((index < signature.params.length || hasRestParam(signature.params)) && test(args[index])) {
            nextMatchingDefs.push(signature);
          }
        });
        if (nextMatchingDefs.length === 0) {
          // no matching signatures anymore, throw error "wrong type"
          expected = mergeExpectedParams(matchingSignatures, index);
          if (expected.length > 0) {
            const actualTypes = findTypeNames(args[index]);
            err = new TypeError('Unexpected type of argument in function ' + _name + ' (expected: ' + expected.join(' or ') + ', actual: ' + actualTypes.join(' | ') + ', index: ' + index + ')');
            err.data = {
              category: 'wrongType',
              fn: _name,
              index,
              actual: actualTypes,
              expected
            };
            return err;
          }
        } else {
          matchingSignatures = nextMatchingDefs;
        }
      }

      // test for too few arguments
      const lengths = matchingSignatures.map(function (signature) {
        return hasRestParam(signature.params) ? Infinity : signature.params.length;
      });
      if (args.length < Math.min.apply(null, lengths)) {
        expected = mergeExpectedParams(matchingSignatures, index);
        err = new TypeError('Too few arguments in function ' + _name + ' (expected: ' + expected.join(' or ') + ', index: ' + args.length + ')');
        err.data = {
          category: 'tooFewArgs',
          fn: _name,
          index: args.length,
          expected
        };
        return err;
      }

      // test for too many arguments
      const maxLength = Math.max.apply(null, lengths);
      if (args.length > maxLength) {
        err = new TypeError('Too many arguments in function ' + _name + ' (expected: ' + maxLength + ', actual: ' + args.length + ')');
        err.data = {
          category: 'tooManyArgs',
          fn: _name,
          index: args.length,
          expectedLength: maxLength
        };
        return err;
      }

      // Generic error
      const argTypes = [];
      for (let i = 0; i < args.length; ++i) {
        argTypes.push(findTypeNames(args[i]).join('|'));
      }
      err = new TypeError('Arguments of type "' + argTypes.join(', ') + '" do not match any of the defined signatures of function ' + _name + '.');
      err.data = {
        category: 'mismatch',
        actual: argTypes
      };
      return err;
    }

    /**
     * Find the lowest index of all exact types of a parameter (no conversions)
     * @param {Param} param
     * @return {number} Returns the index of the lowest type in typed.types
     */
    function getLowestTypeIndex(param) {
      let min = typeList.length + 1;
      for (let i = 0; i < param.types.length; i++) {
        if (isExactType(param.types[i])) {
          min = Math.min(min, param.types[i].typeIndex);
        }
      }
      return min;
    }

    /**
     * Find the lowest index of the conversion of all types of the parameter
     * having a conversion
     * @param {Param} param
     * @return {number} Returns the lowest index of the conversions of this type
     */
    function getLowestConversionIndex(param) {
      let min = nConversions + 1;
      for (let i = 0; i < param.types.length; i++) {
        if (!isExactType(param.types[i])) {
          min = Math.min(min, param.types[i].conversionIndex);
        }
      }
      return min;
    }

    /**
     * Compare two params
     * @param {Param} param1
     * @param {Param} param2
     * @return {number} returns -1 when param1 must get a lower
     *                  index than param2, 1 when the opposite,
     *                  or zero when both are equal
     */
    function compareParams(param1, param2) {
      // We compare a number of metrics on a param in turn:
      // 1) 'any' parameters are the least preferred
      if (param1.hasAny) {
        if (!param2.hasAny) {
          return 1;
        }
      } else if (param2.hasAny) {
        return -1;
      }

      // 2) Prefer non-rest to rest parameters
      if (param1.restParam) {
        if (!param2.restParam) {
          return 1;
        }
      } else if (param2.restParam) {
        return -1;
      }

      // 3) Prefer exact type match to conversions
      if (param1.hasConversion) {
        if (!param2.hasConversion) {
          return 1;
        }
      } else if (param2.hasConversion) {
        return -1;
      }

      // 4) Prefer lower type index:
      const typeDiff = getLowestTypeIndex(param1) - getLowestTypeIndex(param2);
      if (typeDiff < 0) {
        return -1;
      }
      if (typeDiff > 0) {
        return 1;
      }

      // 5) Prefer lower conversion index
      const convDiff = getLowestConversionIndex(param1) - getLowestConversionIndex(param2);
      if (convDiff < 0) {
        return -1;
      }
      if (convDiff > 0) {
        return 1;
      }

      // Don't have a basis for preference
      return 0;
    }

    /**
     * Compare two signatures
     * @param {Signature} signature1
     * @param {Signature} signature2
     * @return {number} returns a negative number when param1 must get a lower
     *                  index than param2, a positive number when the opposite,
     *                  or zero when both are equal
     */
    function compareSignatures(signature1, signature2) {
      const pars1 = signature1.params;
      const pars2 = signature2.params;
      const last1 = last(pars1);
      const last2 = last(pars2);
      const hasRest1 = hasRestParam(pars1);
      const hasRest2 = hasRestParam(pars2);
      // We compare a number of metrics on signatures in turn:
      // 1) An "any rest param" is least preferred
      if (hasRest1 && last1.hasAny) {
        if (!hasRest2 || !last2.hasAny) {
          return 1;
        }
      } else if (hasRest2 && last2.hasAny) {
        return -1;
      }

      // 2) Minimize the number of 'any' parameters
      let any1 = 0;
      let conv1 = 0;
      let par;
      for (par of pars1) {
        if (par.hasAny) ++any1;
        if (par.hasConversion) ++conv1;
      }
      let any2 = 0;
      let conv2 = 0;
      for (par of pars2) {
        if (par.hasAny) ++any2;
        if (par.hasConversion) ++conv2;
      }
      if (any1 !== any2) {
        return any1 - any2;
      }

      // 3) A conversion rest param is less preferred
      if (hasRest1 && last1.hasConversion) {
        if (!hasRest2 || !last2.hasConversion) {
          return 1;
        }
      } else if (hasRest2 && last2.hasConversion) {
        return -1;
      }

      // 4) Minimize the number of conversions
      if (conv1 !== conv2) {
        return conv1 - conv2;
      }

      // 5) Prefer no rest param
      if (hasRest1) {
        if (!hasRest2) {
          return 1;
        }
      } else if (hasRest2) {
        return -1;
      }

      // 6) Prefer shorter with rest param, longer without
      const lengthCriterion = (pars1.length - pars2.length) * (hasRest1 ? -1 : 1);
      if (lengthCriterion !== 0) {
        return lengthCriterion;
      }

      // Signatures are identical in each of the above metrics.
      // In particular, they are the same length.
      // We can therefore compare the parameters one by one.
      // First we count which signature has more preferred parameters.
      const comparisons = [];
      let tc = 0;
      for (let i = 0; i < pars1.length; ++i) {
        const thisComparison = compareParams(pars1[i], pars2[i]);
        comparisons.push(thisComparison);
        tc += thisComparison;
      }
      if (tc !== 0) {
        return tc;
      }

      // They have the same number of preferred parameters, so go by the
      // earliest parameter in which we have a preference.
      // In other words, dispatch is driven somewhat more by earlier
      // parameters than later ones.
      let c;
      for (c of comparisons) {
        if (c !== 0) {
          return c;
        }
      }

      // It's a tossup:
      return 0;
    }

    /**
     * Produce a list of all conversions from distinct types to one of
     * the given types.
     *
     * @param {string[]} typeNames
     * @return {ConversionDef[]} Returns the conversions that are available
     *                        resulting in any given type (if any)
     */
    function availableConversions(typeNames) {
      if (typeNames.length === 0) {
        return [];
      }
      const types = typeNames.map(findType);
      if (typeNames.length > 1) {
        types.sort((t1, t2) => t1.index - t2.index);
      }
      let matches = types[0].conversionsTo;
      if (typeNames.length === 1) {
        return matches;
      }
      matches = matches.concat([]); // shallow copy the matches
      // Since the types are now in index order, we just want the first
      // occurrence of any from type:
      const knownTypes = new Set(typeNames);
      for (let i = 1; i < types.length; ++i) {
        let newMatch;
        for (newMatch of types[i].conversionsTo) {
          if (!knownTypes.has(newMatch.from)) {
            matches.push(newMatch);
            knownTypes.add(newMatch.from);
          }
        }
      }
      return matches;
    }

    /**
     * Preprocess arguments before calling the original function:
     * - if needed convert the parameters
     * - in case of rest parameters, move the rest parameters into an Array
     * @param {Param[]} params
     * @param {function} fn
     * @return {function} Returns a wrapped function
     */
    function compileArgsPreprocessing(params, fn) {
      let fnConvert = fn;

      // TODO: can we make this wrapper function smarter/simpler?

      if (params.some(p => p.hasConversion)) {
        const restParam = hasRestParam(params);
        const compiledConversions = params.map(compileArgConversion);
        fnConvert = function convertArgs() {
          const args = [];
          const last = restParam ? arguments.length - 1 : arguments.length;
          for (let i = 0; i < last; i++) {
            args[i] = compiledConversions[i](arguments[i]);
          }
          if (restParam) {
            args[last] = arguments[last].map(compiledConversions[last]);
          }
          return fn.apply(this, args);
        };
      }
      let fnPreprocess = fnConvert;
      if (hasRestParam(params)) {
        const offset = params.length - 1;
        fnPreprocess = function preprocessRestParams() {
          return fnConvert.apply(this, slice(arguments, 0, offset).concat([slice(arguments, offset)]));
        };
      }
      return fnPreprocess;
    }

    /**
     * Compile conversion for a parameter to the right type
     * @param {Param} param
     * @return {function} Returns the wrapped function that will convert arguments
     *
     */
    function compileArgConversion(param) {
      let test0, test1, conversion0, conversion1;
      const tests = [];
      const conversions = [];
      param.types.forEach(function (type) {
        if (type.conversion) {
          tests.push(findType(type.conversion.from).test);
          conversions.push(type.conversion.convert);
        }
      });

      // create optimized conversion functions depending on the number of conversions
      switch (conversions.length) {
        case 0:
          return function convertArg(arg) {
            return arg;
          };
        case 1:
          test0 = tests[0];
          conversion0 = conversions[0];
          return function convertArg(arg) {
            if (test0(arg)) {
              return conversion0(arg);
            }
            return arg;
          };
        case 2:
          test0 = tests[0];
          test1 = tests[1];
          conversion0 = conversions[0];
          conversion1 = conversions[1];
          return function convertArg(arg) {
            if (test0(arg)) {
              return conversion0(arg);
            }
            if (test1(arg)) {
              return conversion1(arg);
            }
            return arg;
          };
        default:
          return function convertArg(arg) {
            for (let i = 0; i < conversions.length; i++) {
              if (tests[i](arg)) {
                return conversions[i](arg);
              }
            }
            return arg;
          };
      }
    }

    /**
     * Split params with union types in to separate params.
     *
     * For example:
     *
     *     splitParams([['Array', 'Object'], ['string', 'RegExp'])
     *     // returns:
     *     // [
     *     //   ['Array', 'string'],
     *     //   ['Array', 'RegExp'],
     *     //   ['Object', 'string'],
     *     //   ['Object', 'RegExp']
     *     // ]
     *
     * @param {Param[]} params
     * @return {Param[]}
     */
    function splitParams(params) {
      function _splitParams(params, index, paramsSoFar) {
        if (index < params.length) {
          const param = params[index];
          let resultingParams = [];
          if (param.restParam) {
            // split the types of a rest parameter in two:
            // one with only exact types, and one with exact types and conversions
            const exactTypes = param.types.filter(isExactType);
            if (exactTypes.length < param.types.length) {
              resultingParams.push({
                types: exactTypes,
                name: '...' + exactTypes.map(t => t.name).join('|'),
                hasAny: exactTypes.some(t => t.isAny),
                hasConversion: false,
                restParam: true
              });
            }
            resultingParams.push(param);
          } else {
            // split all the types of a regular parameter into one type per param
            resultingParams = param.types.map(function (type) {
              return {
                types: [type],
                name: type.name,
                hasAny: type.isAny,
                hasConversion: type.conversion,
                restParam: false
              };
            });
          }

          // recurse over the groups with types
          return flatMap(resultingParams, function (nextParam) {
            return _splitParams(params, index + 1, paramsSoFar.concat([nextParam]));
          });
        } else {
          // we've reached the end of the parameters.
          return [paramsSoFar];
        }
      }
      return _splitParams(params, 0, []);
    }

    /**
     * Test whether two param lists represent conflicting signatures
     * @param {Param[]} params1
     * @param {Param[]} params2
     * @return {boolean} Returns true when the signatures conflict, false otherwise.
     */
    function conflicting(params1, params2) {
      const ii = Math.max(params1.length, params2.length);
      for (let i = 0; i < ii; i++) {
        const typeSet1 = getTypeSetAtIndex(params1, i);
        const typeSet2 = getTypeSetAtIndex(params2, i);
        let overlap = false;
        let name;
        for (name of typeSet2) {
          if (typeSet1.has(name)) {
            overlap = true;
            break;
          }
        }
        if (!overlap) {
          return false;
        }
      }
      const len1 = params1.length;
      const len2 = params2.length;
      const restParam1 = hasRestParam(params1);
      const restParam2 = hasRestParam(params2);
      return restParam1 ? restParam2 ? len1 === len2 : len2 >= len1 : restParam2 ? len1 >= len2 : len1 === len2;
    }

    /**
     * Helper function for `resolveReferences` that returns a copy of
     * functionList wihe any prior resolutions cleared out, in case we are
     * recycling signatures from a prior typed function construction.
     *
     * @param {Array.<function|typed-reference>} functionList
     * @return {Array.<function|typed-reference>}
     */
    function clearResolutions(functionList) {
      return functionList.map(fn => {
        if (isReferToSelf(fn)) {
          return referToSelf(fn.referToSelf.callback);
        }
        if (isReferTo(fn)) {
          return makeReferTo(fn.referTo.references, fn.referTo.callback);
        }
        return fn;
      });
    }

    /**
     * Take a list of references, a list of functions functionList, and a
     * signatureMap indexing signatures into functionList, and return
     * the list of resolutions, or a false-y value if they don't all
     * resolve in a valid way (yet).
     *
     * @param {string[]} references
     * @param {Array<function|typed-reference} functionList
     * @param {Object.<string, integer>} signatureMap
     * @return {function[] | false} resolutions
     */
    function collectResolutions(references, functionList, signatureMap) {
      const resolvedReferences = [];
      let reference;
      for (reference of references) {
        let resolution = signatureMap[reference];
        if (typeof resolution !== 'number') {
          throw new TypeError('No definition for referenced signature "' + reference + '"');
        }
        resolution = functionList[resolution];
        if (typeof resolution !== 'function') {
          return false;
        }
        resolvedReferences.push(resolution);
      }
      return resolvedReferences;
    }

    /**
     * Resolve any references in the functionList for the typed function
     * itself. The signatureMap tells which index in the functionList a
     * given signature should be mapped to (for use in resolving typed.referTo)
     * and self provides the destions of a typed.referToSelf.
     *
     * @param {Array<function | typed-reference-object>} functionList
     * @param {Object.<string, function>} signatureMap
     * @param {function} self  The typed-function itself
     * @return {Array<function>} The list of resolved functions
     */
    function resolveReferences(functionList, signatureMap, self) {
      const resolvedFunctions = clearResolutions(functionList);
      const isResolved = new Array(resolvedFunctions.length).fill(false);
      let leftUnresolved = true;
      while (leftUnresolved) {
        leftUnresolved = false;
        let nothingResolved = true;
        for (let i = 0; i < resolvedFunctions.length; ++i) {
          if (isResolved[i]) continue;
          const fn = resolvedFunctions[i];
          if (isReferToSelf(fn)) {
            resolvedFunctions[i] = fn.referToSelf.callback(self);
            // Preserve reference in case signature is reused someday:
            resolvedFunctions[i].referToSelf = fn.referToSelf;
            isResolved[i] = true;
            nothingResolved = false;
          } else if (isReferTo(fn)) {
            const resolvedReferences = collectResolutions(fn.referTo.references, resolvedFunctions, signatureMap);
            if (resolvedReferences) {
              resolvedFunctions[i] = fn.referTo.callback.apply(this, resolvedReferences);
              // Preserve reference in case signature is reused someday:
              resolvedFunctions[i].referTo = fn.referTo;
              isResolved[i] = true;
              nothingResolved = false;
            } else {
              leftUnresolved = true;
            }
          }
        }
        if (nothingResolved && leftUnresolved) {
          throw new SyntaxError('Circular reference detected in resolving typed.referTo');
        }
      }
      return resolvedFunctions;
    }

    /**
     * Validate whether any of the function bodies contains a self-reference
     * usage like `this(...)` or `this.signatures`. This self-referencing is
     * deprecated since typed-function v3. It has been replaced with
     * the functions typed.referTo and typed.referToSelf.
     * @param {Object.<string, function>} signaturesMap
     */
    function validateDeprecatedThis(signaturesMap) {
      // TODO: remove this deprecation warning logic some day (it's introduced in v3)

      // match occurrences like 'this(' and 'this.signatures'
      const deprecatedThisRegex = /\bthis(\(|\.signatures\b)/;
      Object.keys(signaturesMap).forEach(signature => {
        const fn = signaturesMap[signature];
        if (deprecatedThisRegex.test(fn.toString())) {
          throw new SyntaxError('Using `this` to self-reference a function ' + 'is deprecated since typed-function@3. ' + 'Use typed.referTo and typed.referToSelf instead.');
        }
      });
    }

    /**
     * Create a typed function
     * @param {String} name               The name for the typed function
     * @param {Object.<string, function>} rawSignaturesMap
     *                                    An object with one or
     *                                    multiple signatures as key, and the
     *                                    function corresponding to the
     *                                    signature as value.
     * @return {function}  Returns the created typed function.
     */
    function createTypedFunction(name, rawSignaturesMap) {
      typed.createCount++;
      if (Object.keys(rawSignaturesMap).length === 0) {
        throw new SyntaxError('No signatures provided');
      }
      if (typed.warnAgainstDeprecatedThis) {
        validateDeprecatedThis(rawSignaturesMap);
      }

      // Main processing loop for signatures
      const parsedParams = [];
      const originalFunctions = [];
      const signaturesMap = {};
      const preliminarySignatures = []; // may have duplicates from conversions
      let signature;
      for (signature in rawSignaturesMap) {
        // A) Protect against polluted Object prototype:
        if (!Object.prototype.hasOwnProperty.call(rawSignaturesMap, signature)) {
          continue;
        }
        // B) Parse the signature
        const params = parseSignature(signature);
        if (!params) continue;
        // C) Check for conflicts
        parsedParams.forEach(function (pp) {
          if (conflicting(pp, params)) {
            throw new TypeError('Conflicting signatures "' + stringifyParams(pp) + '" and "' + stringifyParams(params) + '".');
          }
        });
        parsedParams.push(params);
        // D) Store the provided function and add conversions
        const functionIndex = originalFunctions.length;
        originalFunctions.push(rawSignaturesMap[signature]);
        const conversionParams = params.map(expandParam);
        // E) Split the signatures and collect them up
        let sp;
        for (sp of splitParams(conversionParams)) {
          const spName = stringifyParams(sp);
          preliminarySignatures.push({
            params: sp,
            name: spName,
            fn: functionIndex
          });
          if (sp.every(p => !p.hasConversion)) {
            signaturesMap[spName] = functionIndex;
          }
        }
      }
      preliminarySignatures.sort(compareSignatures);

      // Note the forward reference to theTypedFn
      const resolvedFunctions = resolveReferences(originalFunctions, signaturesMap, theTypedFn);

      // Fill in the proper function for each signature
      let s;
      for (s in signaturesMap) {
        if (Object.prototype.hasOwnProperty.call(signaturesMap, s)) {
          signaturesMap[s] = resolvedFunctions[signaturesMap[s]];
        }
      }
      const signatures = [];
      const internalSignatureMap = new Map(); // benchmarks faster than object
      for (s of preliminarySignatures) {
        // Note it's only safe to eliminate duplicates like this
        // _after_ the signature sorting step above; otherwise we might
        // remove the wrong one.
        if (!internalSignatureMap.has(s.name)) {
          s.fn = resolvedFunctions[s.fn];
          signatures.push(s);
          internalSignatureMap.set(s.name, s);
        }
      }

      // we create a highly optimized checks for the first couple of signatures with max 2 arguments
      const ok0 = signatures[0] && signatures[0].params.length <= 2 && !hasRestParam(signatures[0].params);
      const ok1 = signatures[1] && signatures[1].params.length <= 2 && !hasRestParam(signatures[1].params);
      const ok2 = signatures[2] && signatures[2].params.length <= 2 && !hasRestParam(signatures[2].params);
      const ok3 = signatures[3] && signatures[3].params.length <= 2 && !hasRestParam(signatures[3].params);
      const ok4 = signatures[4] && signatures[4].params.length <= 2 && !hasRestParam(signatures[4].params);
      const ok5 = signatures[5] && signatures[5].params.length <= 2 && !hasRestParam(signatures[5].params);
      const allOk = ok0 && ok1 && ok2 && ok3 && ok4 && ok5;

      // compile the tests
      for (let i = 0; i < signatures.length; ++i) {
        signatures[i].test = compileTests(signatures[i].params);
      }
      const test00 = ok0 ? compileTest(signatures[0].params[0]) : notOk;
      const test10 = ok1 ? compileTest(signatures[1].params[0]) : notOk;
      const test20 = ok2 ? compileTest(signatures[2].params[0]) : notOk;
      const test30 = ok3 ? compileTest(signatures[3].params[0]) : notOk;
      const test40 = ok4 ? compileTest(signatures[4].params[0]) : notOk;
      const test50 = ok5 ? compileTest(signatures[5].params[0]) : notOk;
      const test01 = ok0 ? compileTest(signatures[0].params[1]) : notOk;
      const test11 = ok1 ? compileTest(signatures[1].params[1]) : notOk;
      const test21 = ok2 ? compileTest(signatures[2].params[1]) : notOk;
      const test31 = ok3 ? compileTest(signatures[3].params[1]) : notOk;
      const test41 = ok4 ? compileTest(signatures[4].params[1]) : notOk;
      const test51 = ok5 ? compileTest(signatures[5].params[1]) : notOk;

      // compile the functions
      for (let i = 0; i < signatures.length; ++i) {
        signatures[i].implementation = compileArgsPreprocessing(signatures[i].params, signatures[i].fn);
      }
      const fn0 = ok0 ? signatures[0].implementation : undef;
      const fn1 = ok1 ? signatures[1].implementation : undef;
      const fn2 = ok2 ? signatures[2].implementation : undef;
      const fn3 = ok3 ? signatures[3].implementation : undef;
      const fn4 = ok4 ? signatures[4].implementation : undef;
      const fn5 = ok5 ? signatures[5].implementation : undef;
      const len0 = ok0 ? signatures[0].params.length : -1;
      const len1 = ok1 ? signatures[1].params.length : -1;
      const len2 = ok2 ? signatures[2].params.length : -1;
      const len3 = ok3 ? signatures[3].params.length : -1;
      const len4 = ok4 ? signatures[4].params.length : -1;
      const len5 = ok5 ? signatures[5].params.length : -1;

      // simple and generic, but also slow
      const iStart = allOk ? 6 : 0;
      const iEnd = signatures.length;
      // de-reference ahead for execution speed:
      const tests = signatures.map(s => s.test);
      const fns = signatures.map(s => s.implementation);
      const generic = function generic() {

        for (let i = iStart; i < iEnd; i++) {
          if (tests[i](arguments)) {
            return fns[i].apply(this, arguments);
          }
        }
        return typed.onMismatch(name, arguments, signatures);
      };

      // create the typed function
      // fast, specialized version. Falls back to the slower, generic one if needed
      function theTypedFn(arg0, arg1) {

        if (arguments.length === len0 && test00(arg0) && test01(arg1)) {
          return fn0.apply(this, arguments);
        }
        if (arguments.length === len1 && test10(arg0) && test11(arg1)) {
          return fn1.apply(this, arguments);
        }
        if (arguments.length === len2 && test20(arg0) && test21(arg1)) {
          return fn2.apply(this, arguments);
        }
        if (arguments.length === len3 && test30(arg0) && test31(arg1)) {
          return fn3.apply(this, arguments);
        }
        if (arguments.length === len4 && test40(arg0) && test41(arg1)) {
          return fn4.apply(this, arguments);
        }
        if (arguments.length === len5 && test50(arg0) && test51(arg1)) {
          return fn5.apply(this, arguments);
        }
        return generic.apply(this, arguments);
      }

      // attach name the typed function
      try {
        Object.defineProperty(theTypedFn, 'name', {
          value: name
        });
      } catch (err) {
        // old browsers do not support Object.defineProperty and some don't support setting the name property
        // the function name is not essential for the functioning, it's mostly useful for debugging,
        // so it's fine to have unnamed functions.
      }

      // attach signatures to the function.
      // This property is close to the original collection of signatures
      // used to create the typed-function, just with unions split:
      theTypedFn.signatures = signaturesMap;

      // Store internal data for functions like resolve, find, etc.
      // Also serves as the flag that this is a typed-function
      theTypedFn._typedFunctionData = {
        signatures,
        signatureMap: internalSignatureMap
      };
      return theTypedFn;
    }

    /**
     * Action to take on mismatch
     * @param {string} name      Name of function that was attempted to be called
     * @param {Array} args       Actual arguments to the call
     * @param {Array} signatures Known signatures of the named typed-function
     */
    function _onMismatch(name, args, signatures) {
      throw createError(name, args, signatures);
    }

    /**
     * Return all but the last items of an array or function Arguments
     * @param {Array | Arguments} arr
     * @return {Array}
     */
    function initial(arr) {
      return slice(arr, 0, arr.length - 1);
    }

    /**
     * return the last item of an array or function Arguments
     * @param {Array | Arguments} arr
     * @return {*}
     */
    function last(arr) {
      return arr[arr.length - 1];
    }

    /**
     * Slice an array or function Arguments
     * @param {Array | Arguments | IArguments} arr
     * @param {number} start
     * @param {number} [end]
     * @return {Array}
     */
    function slice(arr, start, end) {
      return Array.prototype.slice.call(arr, start, end);
    }

    /**
     * Return the first item from an array for which test(arr[i]) returns true
     * @param {Array} arr
     * @param {function} test
     * @return {* | undefined} Returns the first matching item
     *                         or undefined when there is no match
     */
    function findInArray(arr, test) {
      for (let i = 0; i < arr.length; i++) {
        if (test(arr[i])) {
          return arr[i];
        }
      }
      return undefined;
    }

    /**
     * Flat map the result invoking a callback for every item in an array.
     * https://gist.github.com/samgiles/762ee337dff48623e729
     * @param {Array} arr
     * @param {function} callback
     * @return {Array}
     */
    function flatMap(arr, callback) {
      return Array.prototype.concat.apply([], arr.map(callback));
    }

    /**
     * Create a reference callback to one or multiple signatures
     *
     * Syntax:
     *
     *     typed.referTo(signature1, signature2, ..., function callback(fn1, fn2, ...) {
     *       // ...
     *     })
     *
     * @returns {{referTo: {references: string[], callback}}}
     */
    function referTo() {
      const references = initial(arguments).map(s => stringifyParams(parseSignature(s)));
      const callback = last(arguments);
      if (typeof callback !== 'function') {
        throw new TypeError('Callback function expected as last argument');
      }
      return makeReferTo(references, callback);
    }
    function makeReferTo(references, callback) {
      return {
        referTo: {
          references,
          callback
        }
      };
    }

    /**
     * Create a reference callback to the typed-function itself
     *
     * @param {(self: function) => function} callback
     * @returns {{referToSelf: { callback: function }}}
     */
    function referToSelf(callback) {
      if (typeof callback !== 'function') {
        throw new TypeError('Callback function expected as first argument');
      }
      return {
        referToSelf: {
          callback
        }
      };
    }

    /**
     * Test whether something is a referTo object, holding a list with reference
     * signatures and a callback.
     *
     * @param {Object | function} objectOrFn
     * @returns {boolean}
     */
    function isReferTo(objectOrFn) {
      return objectOrFn && typeof objectOrFn.referTo === 'object' && Array.isArray(objectOrFn.referTo.references) && typeof objectOrFn.referTo.callback === 'function';
    }

    /**
     * Test whether something is a referToSelf object, holding a callback where
     * to pass `self`.
     *
     * @param {Object | function} objectOrFn
     * @returns {boolean}
     */
    function isReferToSelf(objectOrFn) {
      return objectOrFn && typeof objectOrFn.referToSelf === 'object' && typeof objectOrFn.referToSelf.callback === 'function';
    }

    /**
     * Check if name is (A) new, (B) a match, or (C) a mismatch; and throw
     * an error in case (C).
     *
     * @param { string | undefined } nameSoFar
     * @param { string | undefined } newName
     * @returns { string } updated name
     */
    function checkName(nameSoFar, newName) {
      if (!nameSoFar) {
        return newName;
      }
      if (newName && newName !== nameSoFar) {
        const err = new Error('Function names do not match (expected: ' + nameSoFar + ', actual: ' + newName + ')');
        err.data = {
          actual: newName,
          expected: nameSoFar
        };
        throw err;
      }
      return nameSoFar;
    }

    /**
     * Retrieve the implied name from an object with signature keys
     * and function values, checking whether all value names match
     *
     * @param { {string: function} } obj
     */
    function getObjectName(obj) {
      let name;
      for (const key in obj) {
        // Only pay attention to own properties, and only if their values
        // are typed functions or functions with a signature property
        if (Object.prototype.hasOwnProperty.call(obj, key) && (isTypedFunction(obj[key]) || typeof obj[key].signature === 'string')) {
          name = checkName(name, obj[key].name);
        }
      }
      return name;
    }

    /**
     * Copy all of the signatures from the second argument into the first,
     * which is modified by side effect, checking for conflicts
     *
     * @param {Object.<string, function|typed-reference>} dest
     * @param {Object.<string, function|typed-reference>} source
     */
    function mergeSignatures(dest, source) {
      let key;
      for (key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          if (key in dest) {
            if (source[key] !== dest[key]) {
              const err = new Error('Signature "' + key + '" is defined twice');
              err.data = {
                signature: key,
                sourceFunction: source[key],
                destFunction: dest[key]
              };
              throw err;
            }
            // else: both signatures point to the same function, that's fine
          }
          dest[key] = source[key];
        }
      }
    }
    const saveTyped = typed;

    /**
     * Originally the main function was a typed function itself, but then
     * it might not be able to generate error messages if the client
     * replaced the type system with different names.
     *
     * Main entry: typed([name], functions/objects with signatures...)
     *
     * Assembles and returns a new typed-function from the given items
     * that provide signatures and implementations, each of which may be
     * * a plain object mapping (string) signatures to implementing functions,
     * * a previously constructed typed function, or
     * * any other single function with a string-valued property `signature`.
      * The name of the resulting typed-function will be given by the
     * string-valued name argument if present, or if not, by the name
     * of any of the arguments that have one, as long as any that do are
     * consistent with each other. If no name is specified, the name will be
     * an empty string.
     *
     * @param {string} maybeName [optional]
     * @param {(function|object)[]} signature providers
     * @returns {typed-function}
     */
    typed = function (maybeName) {
      const named = typeof maybeName === 'string';
      const start = named ? 1 : 0;
      let name = named ? maybeName : '';
      const allSignatures = {};
      for (let i = start; i < arguments.length; ++i) {
        const item = arguments[i];
        let theseSignatures = {};
        let thisName;
        if (typeof item === 'function') {
          thisName = item.name;
          if (typeof item.signature === 'string') {
            // Case 1: Ordinary function with a string 'signature' property
            theseSignatures[item.signature] = item;
          } else if (isTypedFunction(item)) {
            // Case 2: Existing typed function
            theseSignatures = item.signatures;
          }
        } else if (isPlainObject(item)) {
          // Case 3: Plain object, assume keys = signatures, values = functions
          theseSignatures = item;
          if (!named) {
            thisName = getObjectName(item);
          }
        }
        if (Object.keys(theseSignatures).length === 0) {
          const err = new TypeError('Argument to \'typed\' at index ' + i + ' is not a (typed) function, ' + 'nor an object with signatures as keys and functions as values.');
          err.data = {
            index: i,
            argument: item
          };
          throw err;
        }
        if (!named) {
          name = checkName(name, thisName);
        }
        mergeSignatures(allSignatures, theseSignatures);
      }
      return createTypedFunction(name || '', allSignatures);
    };
    typed.create = create;
    typed.createCount = saveTyped.createCount;
    typed.onMismatch = _onMismatch;
    typed.throwMismatchError = _onMismatch;
    typed.createError = createError;
    typed.clear = clear;
    typed.clearConversions = clearConversions;
    typed.addTypes = addTypes;
    typed._findType = findType; // For unit testing only
    typed.referTo = referTo;
    typed.referToSelf = referToSelf;
    typed.convert = convert;
    typed.findSignature = findSignature;
    typed.find = find;
    typed.isTypedFunction = isTypedFunction;
    typed.warnAgainstDeprecatedThis = true;

    /**
     * add a type (convenience wrapper for typed.addTypes)
     * @param {{name: string, test: function}} type
     * @param {boolean} [beforeObjectTest=true]
     *                          If true, the new test will be inserted before
     *                          the test with name 'Object' (if any), since
     *                          tests for Object match Array and classes too.
     */
    typed.addType = function (type, beforeObjectTest) {
      let before = 'any';
      if (beforeObjectTest !== false && typeMap.has('Object')) {
        before = 'Object';
      }
      typed.addTypes([type], before);
    };

    /**
     * Verify that the ConversionDef conversion has a valid format.
     *
     * @param {conversionDef} conversion
     * @return {void}
     * @throws {TypeError|SyntaxError}
     */
    function _validateConversion(conversion) {
      if (!conversion || typeof conversion.from !== 'string' || typeof conversion.to !== 'string' || typeof conversion.convert !== 'function') {
        throw new TypeError('Object with properties {from: string, to: string, convert: function} expected');
      }
      if (conversion.to === conversion.from) {
        throw new SyntaxError('Illegal to define conversion from "' + conversion.from + '" to itself.');
      }
    }

    /**
     * Add a conversion
     *
     * @param {ConversionDef} conversion
     * @param {{override: boolean}} [options]
     * @returns {void}
     * @throws {TypeError}
     */
    typed.addConversion = function (conversion) {
      let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
        override: false
      };
      _validateConversion(conversion);
      const to = findType(conversion.to);
      const existing = to.conversionsTo.find(other => other.from === conversion.from);
      if (existing) {
        if (options && options.override) {
          typed.removeConversion({
            from: existing.from,
            to: conversion.to,
            convert: existing.convert
          });
        } else {
          throw new Error('There is already a conversion from "' + conversion.from + '" to "' + to.name + '"');
        }
      }
      to.conversionsTo.push({
        from: conversion.from,
        convert: conversion.convert,
        index: nConversions++
      });
    };

    /**
     * Convenience wrapper to call addConversion on each conversion in a list.
     *
     * @param {ConversionDef[]} conversions
     * @param {{override: boolean}} [options]
     * @returns {void}
     * @throws {TypeError}
     */
    typed.addConversions = function (conversions, options) {
      conversions.forEach(conversion => typed.addConversion(conversion, options));
    };

    /**
     * Remove the specified conversion. The format is the same as for
     * addConversion, and the convert function must match or an error
     * is thrown.
     *
     * @param {{from: string, to: string, convert: function}} conversion
     * @returns {void}
     * @throws {TypeError|SyntaxError|Error}
     */
    typed.removeConversion = function (conversion) {
      _validateConversion(conversion);
      const to = findType(conversion.to);
      const existingConversion = findInArray(to.conversionsTo, c => c.from === conversion.from);
      if (!existingConversion) {
        throw new Error('Attempt to remove nonexistent conversion from ' + conversion.from + ' to ' + conversion.to);
      }
      if (existingConversion.convert !== conversion.convert) {
        throw new Error('Conversion to remove does not match existing conversion');
      }
      const index = to.conversionsTo.indexOf(existingConversion);
      to.conversionsTo.splice(index, 1);
    };

    /**
     * Produce the specific signature that a typed function
     * will execute on the given arguments. Here, a "signature" is an
     * object with properties 'params', 'test', 'fn', and 'implementation'.
     * This last property is a function that converts params as necessary
     * and then calls 'fn'. Returns null if there is no matching signature.
     * @param {typed-function} tf
     * @param {any[]} argList
     * @returns {{params: string, test: function, fn: function, implementation: function}}
     */
    typed.resolve = function (tf, argList) {
      if (!isTypedFunction(tf)) {
        throw new TypeError(NOT_TYPED_FUNCTION);
      }
      const sigs = tf._typedFunctionData.signatures;
      for (let i = 0; i < sigs.length; ++i) {
        if (sigs[i].test(argList)) {
          return sigs[i];
        }
      }
      return null;
    };
    return typed;
  }
  var typedFunction = create();

  return typedFunction;

}));

}(typedFunction$1));

var typedFunction = typedFunction$1.exports;

/**
 * @typedef {{sign: '+' | '-' | '', coefficients: number[], exponent: number}} SplitValue
 */

/**
 * Check if a number is integer
 * @param {number | boolean} value
 * @return {boolean} isInteger
 */
function isInteger(value) {
  if (typeof value === 'boolean') {
    return true;
  }
  return isFinite(value) ? value === Math.round(value) : false;
}

/**
 * Check if a string contains an integer
 * @param {string} str
 * @return {boolean} isInteger
 */
function isIntegerStr(str) {
  // regex matching strings like "123" and "-123"
  return /^-?\d+$/.test(str);
}

/**
 * Ensure the number type is compatible with the provided value.
 * If not, return 'number' instead.
 *
 * For example:
 *
 *     safeNumberType('2.3', { number: 'bigint', numberFallback: 'number' })
 *
 * will return 'number' and not 'bigint' because trying to create a bigint with
 * value 2.3 would throw an exception.
 *
 * @param {string} numberStr
 * @param {{
 *   number: 'number' | 'BigNumber' | 'bigint' | 'Fraction'
 *   numberFallback: 'number' | 'BigNumber'
 * }} config
 * @returns {'number' | 'BigNumber' | 'bigint' | 'Fraction'}
 */
function safeNumberType(numberStr, config) {
  if (config.number === 'bigint' && !isIntegerStr(numberStr)) {
    return config.numberFallback;
  }
  return config.number;
}

/**
 * Calculate the sign of a number
 * @param {number} x
 * @returns {number}
 */
var sign$1 = Math.sign || function (x) {
  if (x > 0) {
    return 1;
  } else if (x < 0) {
    return -1;
  } else {
    return 0;
  }
};

/**
 * Calculate the base-2 logarithm of a number
 * @param {number} x
 * @returns {number}
 */
var log2$1 = Math.log2 || function log2(x) {
  return Math.log(x) / Math.LN2;
};

/**
 * Calculate the base-10 logarithm of a number
 * @param {number} x
 * @returns {number}
 */
var log10$1 = Math.log10 || function log10(x) {
  return Math.log(x) / Math.LN10;
};

/**
 * Calculate the natural logarithm of a number + 1
 * @param {number} x
 * @returns {number}
 */
var log1p = Math.log1p || function (x) {
  return Math.log(x + 1);
};

/**
 * Calculate cubic root for a number
 *
 * Code from es6-shim.js:
 *   https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1564-L1577
 *
 * @param {number} x
 * @returns {number} Returns the cubic root of x
 */
var cbrt$1 = Math.cbrt || function cbrt(x) {
  if (x === 0) {
    return x;
  }
  var negate = x < 0;
  var result;
  if (negate) {
    x = -x;
  }
  if (isFinite(x)) {
    result = Math.exp(Math.log(x) / 3);
    // from https://en.wikipedia.org/wiki/Cube_root#Numerical_methods
    result = (x / (result * result) + 2 * result) / 3;
  } else {
    result = x;
  }
  return negate ? -result : result;
};

/**
 * Calculates exponentiation minus 1
 * @param {number} x
 * @return {number} res
 */
var expm1 = Math.expm1 || function expm1(x) {
  return x >= 2e-4 || x <= -2e-4 ? Math.exp(x) - 1 : x + x * x / 2 + x * x * x / 6;
};

/**
 * Formats a number in a given base
 * @param {number} n
 * @param {number} base
 * @param {number} size
 * @returns {string}
 */
function formatNumberToBase(n, base, size) {
  var prefixes = {
    2: '0b',
    8: '0o',
    16: '0x'
  };
  var prefix = prefixes[base];
  var suffix = '';
  if (size) {
    if (size < 1) {
      throw new Error('size must be in greater than 0');
    }
    if (!isInteger(size)) {
      throw new Error('size must be an integer');
    }
    if (n > 2 ** (size - 1) - 1 || n < -(2 ** (size - 1))) {
      throw new Error("Value must be in range [-2^".concat(size - 1, ", 2^").concat(size - 1, "-1]"));
    }
    if (!isInteger(n)) {
      throw new Error('Value must be an integer');
    }
    if (n < 0) {
      n = n + 2 ** size;
    }
    suffix = "i".concat(size);
  }
  var sign = '';
  if (n < 0) {
    n = -n;
    sign = '-';
  }
  return "".concat(sign).concat(prefix).concat(n.toString(base)).concat(suffix);
}

/**
 * Convert a number to a formatted string representation.
 *
 * Syntax:
 *
 *    format(value)
 *    format(value, options)
 *    format(value, precision)
 *    format(value, fn)
 *
 * Where:
 *
 *    {number} value   The value to be formatted
 *    {Object} options An object with formatting options. Available options:
 *                     {string} notation
 *                         Number notation. Choose from:
 *                         'fixed'          Always use regular number notation.
 *                                          For example '123.40' and '14000000'
 *                         'exponential'    Always use exponential notation.
 *                                          For example '1.234e+2' and '1.4e+7'
 *                         'engineering'    Always use engineering notation.
 *                                          For example '123.4e+0' and '14.0e+6'
 *                         'auto' (default) Regular number notation for numbers
 *                                          having an absolute value between
 *                                          `lowerExp` and `upperExp` bounds, and
 *                                          uses exponential notation elsewhere.
 *                                          Lower bound is included, upper bound
 *                                          is excluded.
 *                                          For example '123.4' and '1.4e7'.
 *                         'bin', 'oct, or
 *                         'hex'            Format the number using binary, octal,
 *                                          or hexadecimal notation.
 *                                          For example '0b1101' and '0x10fe'.
 *                     {number} wordSize    The word size in bits to use for formatting
 *                                          in binary, octal, or hexadecimal notation.
 *                                          To be used only with 'bin', 'oct', or 'hex'
 *                                          values for 'notation' option. When this option
 *                                          is defined the value is formatted as a signed
 *                                          twos complement integer of the given word size
 *                                          and the size suffix is appended to the output.
 *                                          For example
 *                                          format(-1, {notation: 'hex', wordSize: 8}) === '0xffi8'.
 *                                          Default value is undefined.
 *                     {number} precision   A number between 0 and 16 to round
 *                                          the digits of the number.
 *                                          In case of notations 'exponential',
 *                                          'engineering', and 'auto',
 *                                          `precision` defines the total
 *                                          number of significant digits returned.
 *                                          In case of notation 'fixed',
 *                                          `precision` defines the number of
 *                                          significant digits after the decimal
 *                                          point.
 *                                          `precision` is undefined by default,
 *                                          not rounding any digits.
 *                     {number} lowerExp    Exponent determining the lower boundary
 *                                          for formatting a value with an exponent
 *                                          when `notation='auto`.
 *                                          Default value is `-3`.
 *                     {number} upperExp    Exponent determining the upper boundary
 *                                          for formatting a value with an exponent
 *                                          when `notation='auto`.
 *                                          Default value is `5`.
 *    {Function} fn    A custom formatting function. Can be used to override the
 *                     built-in notations. Function `fn` is called with `value` as
 *                     parameter and must return a string. Is useful for example to
 *                     format all values inside a matrix in a particular way.
 *
 * Examples:
 *
 *    format(6.4)                                        // '6.4'
 *    format(1240000)                                    // '1.24e6'
 *    format(1/3)                                        // '0.3333333333333333'
 *    format(1/3, 3)                                     // '0.333'
 *    format(21385, 2)                                   // '21000'
 *    format(12.071, {notation: 'fixed'})                // '12'
 *    format(2.3,    {notation: 'fixed', precision: 2})  // '2.30'
 *    format(52.8,   {notation: 'exponential'})          // '5.28e+1'
 *    format(12345678, {notation: 'engineering'})        // '12.345678e+6'
 *
 * @param {number} value
 * @param {Object | Function | number} [options]
 * @return {string} str The formatted value
 */
function format$2(value, options) {
  if (typeof options === 'function') {
    // handle format(value, fn)
    return options(value);
  }

  // handle special cases
  if (value === Infinity) {
    return 'Infinity';
  } else if (value === -Infinity) {
    return '-Infinity';
  } else if (isNaN(value)) {
    return 'NaN';
  }
  var {
    notation,
    precision,
    wordSize
  } = normalizeFormatOptions(options);

  // handle the various notations
  switch (notation) {
    case 'fixed':
      return toFixed$1(value, precision);
    case 'exponential':
      return toExponential$1(value, precision);
    case 'engineering':
      return toEngineering$1(value, precision);
    case 'bin':
      return formatNumberToBase(value, 2, wordSize);
    case 'oct':
      return formatNumberToBase(value, 8, wordSize);
    case 'hex':
      return formatNumberToBase(value, 16, wordSize);
    case 'auto':
      // remove trailing zeros after the decimal point
      return toPrecision(value, precision, options).replace(/((\.\d*?)(0+))($|e)/, function () {
        var digits = arguments[2];
        var e = arguments[4];
        return digits !== '.' ? digits + e : e;
      });
    default:
      throw new Error('Unknown notation "' + notation + '". ' + 'Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.');
  }
}

/**
 * Normalize format options into an object:
 *   {
 *     notation: string,
 *     precision: number | undefined,
 *     wordSize: number | undefined
 *   }
 */
function normalizeFormatOptions(options) {
  // default values for options
  var notation = 'auto';
  var precision;
  var wordSize;
  if (options !== undefined) {
    if (isNumber(options)) {
      precision = options;
    } else if (isBigNumber(options)) {
      precision = options.toNumber();
    } else if (isObject(options)) {
      if (options.precision !== undefined) {
        precision = _toNumberOrThrow(options.precision, () => {
          throw new Error('Option "precision" must be a number or BigNumber');
        });
      }
      if (options.wordSize !== undefined) {
        wordSize = _toNumberOrThrow(options.wordSize, () => {
          throw new Error('Option "wordSize" must be a number or BigNumber');
        });
      }
      if (options.notation) {
        notation = options.notation;
      }
    } else {
      throw new Error('Unsupported type of options, number, BigNumber, or object expected');
    }
  }
  return {
    notation,
    precision,
    wordSize
  };
}

/**
 * Split a number into sign, coefficients, and exponent
 * @param {number | string} value
 * @return {SplitValue}
 *              Returns an object containing sign, coefficients, and exponent
 */
function splitNumber(value) {
  // parse the input value
  var match = String(value).toLowerCase().match(/^(-?)(\d+\.?\d*)(e([+-]?\d+))?$/);
  if (!match) {
    throw new SyntaxError('Invalid number ' + value);
  }
  var sign = match[1];
  var digits = match[2];
  var exponent = parseFloat(match[4] || '0');
  var dot = digits.indexOf('.');
  exponent += dot !== -1 ? dot - 1 : digits.length - 1;
  var coefficients = digits.replace('.', '') // remove the dot (must be removed before removing leading zeros)
  .replace(/^0*/, function (zeros) {
    // remove leading zeros, add their count to the exponent
    exponent -= zeros.length;
    return '';
  }).replace(/0*$/, '') // remove trailing zeros
  .split('').map(function (d) {
    return parseInt(d);
  });
  if (coefficients.length === 0) {
    coefficients.push(0);
    exponent++;
  }
  return {
    sign,
    coefficients,
    exponent
  };
}

/**
 * Format a number in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3'
 * @param {number | string} value
 * @param {number} [precision]        Optional number of significant figures to return.
 */
function toEngineering$1(value, precision) {
  if (isNaN(value) || !isFinite(value)) {
    return String(value);
  }
  var split = splitNumber(value);
  var rounded = roundDigits(split, precision);
  var e = rounded.exponent;
  var c = rounded.coefficients;

  // find nearest lower multiple of 3 for exponent
  var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3;
  if (isNumber(precision)) {
    // add zeroes to give correct sig figs
    while (precision > c.length || e - newExp + 1 > c.length) {
      c.push(0);
    }
  } else {
    // concatenate coefficients with necessary zeros
    // add zeros if necessary (for example: 1e+8 -> 100e+6)
    var missingZeros = Math.abs(e - newExp) - (c.length - 1);
    for (var i = 0; i < missingZeros; i++) {
      c.push(0);
    }
  }

  // find difference in exponents
  var expDiff = Math.abs(e - newExp);
  var decimalIdx = 1;

  // push decimal index over by expDiff times
  while (expDiff > 0) {
    decimalIdx++;
    expDiff--;
  }

  // if all coefficient values are zero after the decimal point and precision is unset, don't add a decimal value.
  // otherwise concat with the rest of the coefficients
  var decimals = c.slice(decimalIdx).join('');
  var decimalVal = isNumber(precision) && decimals.length || decimals.match(/[1-9]/) ? '.' + decimals : '';
  var str = c.slice(0, decimalIdx).join('') + decimalVal + 'e' + (e >= 0 ? '+' : '') + newExp.toString();
  return rounded.sign + str;
}

/**
 * Format a number with fixed notation.
 * @param {number | string} value
 * @param {number} [precision=undefined]  Optional number of decimals after the
 *                                        decimal point. null by default.
 */
function toFixed$1(value, precision) {
  if (isNaN(value) || !isFinite(value)) {
    return String(value);
  }
  var splitValue = splitNumber(value);
  var rounded = typeof precision === 'number' ? roundDigits(splitValue, splitValue.exponent + 1 + precision) : splitValue;
  var c = rounded.coefficients;
  var p = rounded.exponent + 1; // exponent may have changed

  // append zeros if needed
  var pp = p + (precision || 0);
  if (c.length < pp) {
    c = c.concat(zeros(pp - c.length));
  }

  // prepend zeros if needed
  if (p < 0) {
    c = zeros(-p + 1).concat(c);
    p = 1;
  }

  // insert a dot if needed
  if (p < c.length) {
    c.splice(p, 0, p === 0 ? '0.' : '.');
  }
  return rounded.sign + c.join('');
}

/**
 * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3'
 * @param {number | string} value
 * @param {number} [precision]  Number of digits in formatted output.
 *                              If not provided, the maximum available digits
 *                              is used.
 */
function toExponential$1(value, precision) {
  if (isNaN(value) || !isFinite(value)) {
    return String(value);
  }

  // round if needed, else create a clone
  var split = splitNumber(value);
  var rounded = precision ? roundDigits(split, precision) : split;
  var c = rounded.coefficients;
  var e = rounded.exponent;

  // append zeros if needed
  if (c.length < precision) {
    c = c.concat(zeros(precision - c.length));
  }

  // format as `C.CCCe+EEE` or `C.CCCe-EEE`
  var first = c.shift();
  return rounded.sign + first + (c.length > 0 ? '.' + c.join('') : '') + 'e' + (e >= 0 ? '+' : '') + e;
}

/**
 * Format a number with a certain precision
 * @param {number | string} value
 * @param {number} [precision=undefined] Optional number of digits.
 * @param {{lowerExp: number | undefined, upperExp: number | undefined}} [options]
 *                                       By default:
 *                                         lowerExp = -3 (incl)
 *                                         upper = +5 (excl)
 * @return {string}
 */
function toPrecision(value, precision, options) {
  if (isNaN(value) || !isFinite(value)) {
    return String(value);
  }

  // determine lower and upper bound for exponential notation.
  var lowerExp = _toNumberOrDefault$1(options === null || options === void 0 ? void 0 : options.lowerExp, -3);
  var upperExp = _toNumberOrDefault$1(options === null || options === void 0 ? void 0 : options.upperExp, 5);
  var split = splitNumber(value);
  var rounded = precision ? roundDigits(split, precision) : split;
  if (rounded.exponent < lowerExp || rounded.exponent >= upperExp) {
    // exponential notation
    return toExponential$1(value, precision);
  } else {
    var c = rounded.coefficients;
    var e = rounded.exponent;

    // append trailing zeros
    if (c.length < precision) {
      c = c.concat(zeros(precision - c.length));
    }

    // append trailing zeros
    // TODO: simplify the next statement
    c = c.concat(zeros(e - c.length + 1 + (c.length < precision ? precision - c.length : 0)));

    // prepend zeros
    c = zeros(-e).concat(c);
    var dot = e > 0 ? e : 0;
    if (dot < c.length - 1) {
      c.splice(dot + 1, 0, '.');
    }
    return rounded.sign + c.join('');
  }
}

/**
 * Round the number of digits of a number *
 * @param {SplitValue} split       A value split with .splitNumber(value)
 * @param {number} precision  A positive integer
 * @return {SplitValue}
 *              Returns an object containing sign, coefficients, and exponent
 *              with rounded digits
 */
function roundDigits(split, precision) {
  // create a clone
  var rounded = {
    sign: split.sign,
    coefficients: split.coefficients,
    exponent: split.exponent
  };
  var c = rounded.coefficients;

  // prepend zeros if needed
  while (precision <= 0) {
    c.unshift(0);
    rounded.exponent++;
    precision++;
  }
  if (c.length > precision) {
    var removed = c.splice(precision, c.length - precision);
    if (removed[0] >= 5) {
      var i = precision - 1;
      c[i]++;
      while (c[i] === 10) {
        c.pop();
        if (i === 0) {
          c.unshift(0);
          rounded.exponent++;
          i++;
        }
        i--;
        c[i]++;
      }
    }
  }
  return rounded;
}

/**
 * Create an array filled with zeros.
 * @param {number} length
 * @return {Array}
 */
function zeros(length) {
  var arr = [];
  for (var i = 0; i < length; i++) {
    arr.push(0);
  }
  return arr;
}

/**
 * Count the number of significant digits of a number.
 *
 * For example:
 *   2.34 returns 3
 *   0.0034 returns 2
 *   120.5e+30 returns 4
 *
 * @param {number} value
 * @return {number} digits   Number of significant digits
 */
function digits(value) {
  return value.toExponential().replace(/e.*$/, '') // remove exponential notation
  .replace(/^0\.?0*|\./, '') // remove decimal point and leading zeros
  .length;
}

/**
 * Compares two floating point numbers.
 * @param {number} a - First value to compare
 * @param {number} b - Second value to compare
 * @param {number} [relTol=1e-09] - The relative tolerance, indicating the maximum allowed difference relative to the larger absolute value. Must be greater than 0.
 * @param {number} [absTol=1e-12] - The minimum absolute tolerance, useful for comparisons near zero. Must be at least 0.
 * @return {boolean} whether the two numbers are nearly equal
 *
 * @throws {Error} If `relTol` is less than or equal to 0.
 * @throws {Error} If `absTol` is less than 0.
 *
 * @example
 * nearlyEqual(1.000000001, 1.0, 1e-8);            // true
 * nearlyEqual(1.000000002, 1.0, 0);            // false
 * nearlyEqual(1.0, 1.009, undefined, 0.01);       // true
 * nearlyEqual(0.000000001, 0.0, undefined, 1e-8); // true
 */
function nearlyEqual$1(a, b) {
  var relTol = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1e-8;
  var absTol = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  if (relTol <= 0) {
    throw new Error('Relative tolerance must be greater than 0');
  }
  if (absTol < 0) {
    throw new Error('Absolute tolerance must be at least 0');
  }

  // NaN
  if (isNaN(a) || isNaN(b)) {
    return false;
  }
  if (!isFinite(a) || !isFinite(b)) {
    return a === b;
  }
  if (a === b) {
    return true;
  }

  // abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
  return Math.abs(a - b) <= Math.max(relTol * Math.max(Math.abs(a), Math.abs(b)), absTol);
}

/**
 * Calculate the hyperbolic arccos of a number
 * @param {number} x
 * @return {number}
 */
var acosh$1 = Math.acosh || function (x) {
  return Math.log(Math.sqrt(x * x - 1) + x);
};
var asinh$1 = Math.asinh || function (x) {
  return Math.log(Math.sqrt(x * x + 1) + x);
};

/**
 * Calculate the hyperbolic arctangent of a number
 * @param {number} x
 * @return {number}
 */
var atanh$1 = Math.atanh || function (x) {
  return Math.log((1 + x) / (1 - x)) / 2;
};

/**
 * Calculate the hyperbolic cosine of a number
 * @param {number} x
 * @returns {number}
 */
var cosh$1 = Math.cosh || function (x) {
  return (Math.exp(x) + Math.exp(-x)) / 2;
};

/**
 * Calculate the hyperbolic sine of a number
 * @param {number} x
 * @returns {number}
 */
var sinh$1 = Math.sinh || function (x) {
  return (Math.exp(x) - Math.exp(-x)) / 2;
};

/**
 * Calculate the hyperbolic tangent of a number
 * @param {number} x
 * @returns {number}
 */
var tanh$1 = Math.tanh || function (x) {
  var e = Math.exp(2 * x);
  return (e - 1) / (e + 1);
};

/**
 * Returns a value with the magnitude of x and the sign of y.
 * @param {number} x
 * @param {number} y
 * @returns {number}
 */
function copysign(x, y) {
  var signx = x > 0 ? true : x < 0 ? false : 1 / x === Infinity;
  var signy = y > 0 ? true : y < 0 ? false : 1 / y === Infinity;
  return signx ^ signy ? -x : x;
}
function _toNumberOrThrow(value, onError) {
  if (isNumber(value)) {
    return value;
  } else if (isBigNumber(value)) {
    return value.toNumber();
  } else {
    onError();
  }
}
function _toNumberOrDefault$1(value, defaultValue) {
  if (isNumber(value)) {
    return value;
  } else if (isBigNumber(value)) {
    return value.toNumber();
  } else {
    return defaultValue;
  }
}

/**
 * Create a factory function, which can be used to inject dependencies.
 *
 * The created functions are memoized, a consecutive call of the factory
 * with the exact same inputs will return the same function instance.
 * The memoized cache is exposed on `factory.cache` and can be cleared
 * if needed.
 *
 * Example:
 *
 *     const name = 'log'
 *     const dependencies = ['config', 'typed', 'divideScalar', 'Complex']
 *
 *     export const createLog = factory(name, dependencies, ({ typed, config, divideScalar, Complex }) => {
 *       // ... create the function log here and return it
 *     }
 *
 * @param {string} name           Name of the function to be created
 * @param {string[]} dependencies The names of all required dependencies
 * @param {function} create       Callback function called with an object with all dependencies
 * @param {Object} [meta]         Optional object with meta information that will be attached
 *                                to the created factory function as property `meta`.
 * @returns {function}
 */
function factory(name, dependencies, create, meta) {
  function assertAndCreate(scope) {
    // we only pass the requested dependencies to the factory function
    // to prevent functions to rely on dependencies that are not explicitly
    // requested.
    var deps = pickShallow(scope, dependencies.map(stripOptionalNotation));
    assertDependencies(name, dependencies, scope);
    return create(deps);
  }
  assertAndCreate.isFactory = true;
  assertAndCreate.fn = name;
  assertAndCreate.dependencies = dependencies.slice().sort();
  if (meta) {
    assertAndCreate.meta = meta;
  }
  return assertAndCreate;
}

/**
 * Test whether an object is a factory. This is the case when it has
 * properties name, dependencies, and a function create.
 * @param {*} obj
 * @returns {boolean}
 */
function isFactory(obj) {
  return typeof obj === 'function' && typeof obj.fn === 'string' && Array.isArray(obj.dependencies);
}

/**
 * Assert that all dependencies of a list with dependencies are available in the provided scope.
 *
 * Will throw an exception when there are dependencies missing.
 *
 * @param {string} name   Name for the function to be created. Used to generate a useful error message
 * @param {string[]} dependencies
 * @param {Object} scope
 */
function assertDependencies(name, dependencies, scope) {
  var allDefined = dependencies.filter(dependency => !isOptionalDependency(dependency)) // filter optionals
  .every(dependency => scope[dependency] !== undefined);
  if (!allDefined) {
    var missingDependencies = dependencies.filter(dependency => scope[dependency] === undefined);

    // TODO: create a custom error class for this, a MathjsError or something like that
    throw new Error("Cannot create function \"".concat(name, "\", ") + "some dependencies are missing: ".concat(missingDependencies.map(d => "\"".concat(d, "\"")).join(', '), "."));
  }
}
function isOptionalDependency(dependency) {
  return dependency && dependency[0] === '?';
}
function stripOptionalNotation(dependency) {
  return dependency && dependency[0] === '?' ? dependency.slice(1) : dependency;
}

/**
 * Get a property of a plain object
 * Throws an error in case the object is not a plain object or the
 * property is not defined on the object itself
 * @param {Object} object
 * @param {string} prop
 * @return {*} Returns the property value when safe
 */
function getSafeProperty(object, prop) {
  // only allow getting safe properties of a plain object
  if (isPlainObject(object) && isSafeProperty(object, prop)) {
    return object[prop];
  }
  if (typeof object[prop] === 'function' && isSafeMethod(object, prop)) {
    throw new Error('Cannot access method "' + prop + '" as a property');
  }
  throw new Error('No access to property "' + prop + '"');
}

/**
 * Set a property on a plain object.
 * Throws an error in case the object is not a plain object or the
 * property would override an inherited property like .constructor or .toString
 * @param {Object} object
 * @param {string} prop
 * @param {*} value
 * @return {*} Returns the value
 */
// TODO: merge this function into access.js?
function setSafeProperty(object, prop, value) {
  // only allow setting safe properties of a plain object
  if (isPlainObject(object) && isSafeProperty(object, prop)) {
    object[prop] = value;
    return value;
  }
  throw new Error('No access to property "' + prop + '"');
}
function hasSafeProperty(object, prop) {
  return prop in object;
}

/**
 * Test whether a property is safe to use for an object.
 * For example .toString and .constructor are not safe
 * @param {string} prop
 * @return {boolean} Returns true when safe
 */
function isSafeProperty(object, prop) {
  if (!object || typeof object !== 'object') {
    return false;
  }
  // SAFE: whitelisted
  // e.g length
  if (hasOwnProperty(safeNativeProperties, prop)) {
    return true;
  }
  // UNSAFE: inherited from Object prototype
  // e.g constructor
  if (prop in Object.prototype) {
    // 'in' is used instead of hasOwnProperty for nodejs v0.10
    // which is inconsistent on root prototypes. It is safe
    // here because Object.prototype is a root object
    return false;
  }
  // UNSAFE: inherited from Function prototype
  // e.g call, apply
  if (prop in Function.prototype) {
    // 'in' is used instead of hasOwnProperty for nodejs v0.10
    // which is inconsistent on root prototypes. It is safe
    // here because Function.prototype is a root object
    return false;
  }
  return true;
}

/**
 * Validate whether a method is safe.
 * Throws an error when that's not the case.
 * @param {Object} object
 * @param {string} method
 * @return {function} Returns the method when valid
 */
function getSafeMethod(object, method) {
  if (!isSafeMethod(object, method)) {
    throw new Error('No access to method "' + method + '"');
  }
  return object[method];
}

/**
 * Check whether a method is safe.
 * Throws an error when that's not the case (for example for `constructor`).
 * @param {Object} object
 * @param {string} method
 * @return {boolean} Returns true when safe, false otherwise
 */
function isSafeMethod(object, method) {
  if (object === null || object === undefined || typeof object[method] !== 'function') {
    return false;
  }
  // UNSAFE: ghosted
  // e.g overridden toString
  // Note that IE10 doesn't support __proto__ and we can't do this check there.
  if (hasOwnProperty(object, method) && Object.getPrototypeOf && method in Object.getPrototypeOf(object)) {
    return false;
  }
  // SAFE: whitelisted
  // e.g toString
  if (hasOwnProperty(safeNativeMethods, method)) {
    return true;
  }
  // UNSAFE: inherited from Object prototype
  // e.g constructor
  if (method in Object.prototype) {
    // 'in' is used instead of hasOwnProperty for nodejs v0.10
    // which is inconsistent on root prototypes. It is safe
    // here because Object.prototype is a root object
    return false;
  }
  // UNSAFE: inherited from Function prototype
  // e.g call, apply
  if (method in Function.prototype) {
    // 'in' is used instead of hasOwnProperty for nodejs v0.10
    // which is inconsistent on root prototypes. It is safe
    // here because Function.prototype is a root object
    return false;
  }
  return true;
}
function isPlainObject(object) {
  return typeof object === 'object' && object && object.constructor === Object;
}
var safeNativeProperties = {
  length: true,
  name: true
};
var safeNativeMethods = {
  toString: true,
  valueOf: true,
  toLocaleString: true
};

/**
 * A map facade on a bare object.
 *
 * The small number of methods needed to implement a scope,
 * forwarding on to the SafeProperty functions. Over time, the codebase
 * will stop using this method, as all objects will be Maps, rather than
 * more security prone objects.
 */
class ObjectWrappingMap {
  constructor(object) {
    this.wrappedObject = object;
    this[Symbol.iterator] = this.entries;
  }
  keys() {
    return Object.keys(this.wrappedObject).values();
  }
  get(key) {
    return getSafeProperty(this.wrappedObject, key);
  }
  set(key, value) {
    setSafeProperty(this.wrappedObject, key, value);
    return this;
  }
  has(key) {
    return hasSafeProperty(this.wrappedObject, key);
  }
  entries() {
    return mapIterator(this.keys(), key => [key, this.get(key)]);
  }
  forEach(callback) {
    for (var key of this.keys()) {
      callback(this.get(key), key, this);
    }
  }
  delete(key) {
    delete this.wrappedObject[key];
  }
  clear() {
    for (var key of this.keys()) {
      this.delete(key);
    }
  }
  get size() {
    return Object.keys(this.wrappedObject).length;
  }
}

/**
 * Create a map with two partitions: a and b.
 * The set with bKeys determines which keys/values are read/written to map b,
 * all other values are read/written to map a
 *
 * For example:
 *
 *   const a = new Map()
 *   const b = new Map()
 *   const p = new PartitionedMap(a, b, new Set(['x', 'y']))
 *
 * In this case, values `x` and `y` are read/written to map `b`,
 * all other values are read/written to map `a`.
 */
class PartitionedMap {
  /**
   * @param {Map} a
   * @param {Map} b
   * @param {Set} bKeys
   */
  constructor(a, b, bKeys) {
    this.a = a;
    this.b = b;
    this.bKeys = bKeys;
    this[Symbol.iterator] = this.entries;
  }
  get(key) {
    return this.bKeys.has(key) ? this.b.get(key) : this.a.get(key);
  }
  set(key, value) {
    if (this.bKeys.has(key)) {
      this.b.set(key, value);
    } else {
      this.a.set(key, value);
    }
    return this;
  }
  has(key) {
    return this.b.has(key) || this.a.has(key);
  }
  keys() {
    return new Set([...this.a.keys(), ...this.b.keys()])[Symbol.iterator]();
  }
  entries() {
    return mapIterator(this.keys(), key => [key, this.get(key)]);
  }
  forEach(callback) {
    for (var key of this.keys()) {
      callback(this.get(key), key, this);
    }
  }
  delete(key) {
    return this.bKeys.has(key) ? this.b.delete(key) : this.a.delete(key);
  }
  clear() {
    this.a.clear();
    this.b.clear();
  }
  get size() {
    return [...this.keys()].length;
  }
}

/**
 * Create a new iterator that maps over the provided iterator, applying a mapping function to each item
 */
function mapIterator(it, callback) {
  return {
    next: () => {
      var n = it.next();
      return n.done ? n : {
        value: callback(n.value),
        done: false
      };
    }
  };
}

/**
 * Creates an empty map, or whatever your platform's polyfill is.
 *
 * @returns an empty Map or Map like object.
 */
function createEmptyMap() {
  return new Map();
}

/**
 * Creates a Map from the given object.
 *
 * @param { Map | { [key: string]: unknown } | undefined } mapOrObject
 * @returns
 */
function createMap$1(mapOrObject) {
  if (!mapOrObject) {
    return createEmptyMap();
  }
  if (isMap(mapOrObject)) {
    return mapOrObject;
  }
  if (isObject(mapOrObject)) {
    return new ObjectWrappingMap(mapOrObject);
  }
  throw new Error('createMap can create maps from objects or Maps');
}

/**
 * Unwraps a map into an object.
 *
 * @param {Map} map
 * @returns { [key: string]: unknown }
 */
function toObject(map) {
  if (map instanceof ObjectWrappingMap) {
    return map.wrappedObject;
  }
  var object = {};
  for (var key of map.keys()) {
    var value = map.get(key);
    setSafeProperty(object, key, value);
  }
  return object;
}

/**
 * Returns `true` if the passed object appears to be a Map (i.e. duck typing).
 *
 * Methods looked for are `get`, `set`, `keys` and `has`.
 *
 * @param {Map | object} object
 * @returns
 */
function isMap(object) {
  // We can use the fast instanceof, or a slower duck typing check.
  // The duck typing method needs to cover enough methods to not be confused with DenseMatrix.
  if (!object) {
    return false;
  }
  return object instanceof Map || object instanceof ObjectWrappingMap || typeof object.set === 'function' && typeof object.get === 'function' && typeof object.keys === 'function' && typeof object.has === 'function';
}

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

// returns a new instance of typed-function
var _createTyped2 = function _createTyped() {
  // initially, return the original instance of typed-function
  // consecutively, return a new instance from typed.create.
  _createTyped2 = typedFunction.create;
  return typedFunction;
};
var dependencies$4V = ['?BigNumber', '?Complex', '?DenseMatrix', '?Fraction'];

/**
 * Factory function for creating a new typed instance
 * @param {Object} dependencies   Object with data types like Complex and BigNumber
 * @returns {Function}
 */
var createTyped = /* #__PURE__ */factory('typed', dependencies$4V, function createTyped(_ref) {
  var {
    BigNumber,
    Complex,
    DenseMatrix,
    Fraction
  } = _ref;
  // TODO: typed-function must be able to silently ignore signatures with unknown data types

  // get a new instance of typed-function
  var typed = _createTyped2();

  // define all types. The order of the types determines in which order function
  // arguments are type-checked (so for performance it's important to put the
  // most used types first).
  typed.clear();
  typed.addTypes([{
    name: 'number',
    test: isNumber
  }, {
    name: 'Complex',
    test: isComplex
  }, {
    name: 'BigNumber',
    test: isBigNumber
  }, {
    name: 'bigint',
    test: isBigInt
  }, {
    name: 'Fraction',
    test: isFraction
  }, {
    name: 'Unit',
    test: isUnit
  },
  // The following type matches a valid variable name, i.e., an alphanumeric
  // string starting with an alphabetic character. It is used (at least)
  // in the definition of the derivative() function, as the argument telling
  // what to differentiate over must (currently) be a variable.
  {
    name: 'identifier',
    test: s => isString && /^(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE3F\uDE40\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2\uDF02\uDF04-\uDF10\uDF12-\uDF33\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD887][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2F\uDC41-\uDC46]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD32\uDD50-\uDD52\uDD55\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E\uDF25-\uDF2A]|\uD838[\uDC30-\uDC6D\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDCD0-\uDCEB\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF39\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD888[\uDC00-\uDFAF])(?:[0-9A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE3F\uDE40\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2\uDF02\uDF04-\uDF10\uDF12-\uDF33\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD887][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2F\uDC41-\uDC46]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD32\uDD50-\uDD52\uDD55\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E\uDF25-\uDF2A]|\uD838[\uDC30-\uDC6D\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDCD0-\uDCEB\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF39\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD888[\uDC00-\uDFAF])*$/.test(s)
  }, {
    name: 'string',
    test: isString
  }, {
    name: 'Chain',
    test: isChain
  }, {
    name: 'Array',
    test: isArray
  }, {
    name: 'Matrix',
    test: isMatrix
  }, {
    name: 'DenseMatrix',
    test: isDenseMatrix
  }, {
    name: 'SparseMatrix',
    test: isSparseMatrix
  }, {
    name: 'Range',
    test: isRange
  }, {
    name: 'Index',
    test: isIndex
  }, {
    name: 'boolean',
    test: isBoolean
  }, {
    name: 'ResultSet',
    test: isResultSet
  }, {
    name: 'Help',
    test: isHelp
  }, {
    name: 'function',
    test: isFunction
  }, {
    name: 'Date',
    test: isDate
  }, {
    name: 'RegExp',
    test: isRegExp
  }, {
    name: 'null',
    test: isNull
  }, {
    name: 'undefined',
    test: isUndefined
  }, {
    name: 'AccessorNode',
    test: isAccessorNode
  }, {
    name: 'ArrayNode',
    test: isArrayNode
  }, {
    name: 'AssignmentNode',
    test: isAssignmentNode
  }, {
    name: 'BlockNode',
    test: isBlockNode
  }, {
    name: 'ConditionalNode',
    test: isConditionalNode
  }, {
    name: 'ConstantNode',
    test: isConstantNode
  }, {
    name: 'FunctionNode',
    test: isFunctionNode
  }, {
    name: 'FunctionAssignmentNode',
    test: isFunctionAssignmentNode
  }, {
    name: 'IndexNode',
    test: isIndexNode
  }, {
    name: 'Node',
    test: isNode
  }, {
    name: 'ObjectNode',
    test: isObjectNode
  }, {
    name: 'OperatorNode',
    test: isOperatorNode
  }, {
    name: 'ParenthesisNode',
    test: isParenthesisNode
  }, {
    name: 'RangeNode',
    test: isRangeNode
  }, {
    name: 'RelationalNode',
    test: isRelationalNode
  }, {
    name: 'SymbolNode',
    test: isSymbolNode
  }, {
    name: 'Map',
    test: isMap
  }, {
    name: 'Object',
    test: isObject
  } // order 'Object' last, it matches on other classes too
  ]);
  typed.addConversions([{
    from: 'number',
    to: 'BigNumber',
    convert: function convert(x) {
      if (!BigNumber) {
        throwNoBignumber(x);
      }

      // note: conversion from number to BigNumber can fail if x has >15 digits
      if (digits(x) > 15) {
        throw new TypeError('Cannot implicitly convert a number with >15 significant digits to BigNumber ' + '(value: ' + x + '). ' + 'Use function bignumber(x) to convert to BigNumber.');
      }
      return new BigNumber(x);
    }
  }, {
    from: 'number',
    to: 'Complex',
    convert: function convert(x) {
      if (!Complex) {
        throwNoComplex(x);
      }
      return new Complex(x, 0);
    }
  }, {
    from: 'BigNumber',
    to: 'Complex',
    convert: function convert(x) {
      if (!Complex) {
        throwNoComplex(x);
      }
      return new Complex(x.toNumber(), 0);
    }
  }, {
    from: 'bigint',
    to: 'number',
    convert: function convert(x) {
      if (x > Number.MAX_SAFE_INTEGER) {
        throw new TypeError('Cannot implicitly convert bigint to number: ' + 'value exceeds the max safe integer value (value: ' + x + ')');
      }
      return Number(x);
    }
  }, {
    from: 'bigint',
    to: 'BigNumber',
    convert: function convert(x) {
      if (!BigNumber) {
        throwNoBignumber(x);
      }
      return new BigNumber(x.toString());
    }
  }, {
    from: 'bigint',
    to: 'Fraction',
    convert: function convert(x) {
      if (!Fraction) {
        throwNoFraction(x);
      }
      return new Fraction(x.toString());
    }
  }, {
    from: 'Fraction',
    to: 'BigNumber',
    convert: function convert(x) {
      throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' + 'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
    }
  }, {
    from: 'Fraction',
    to: 'Complex',
    convert: function convert(x) {
      if (!Complex) {
        throwNoComplex(x);
      }
      return new Complex(x.valueOf(), 0);
    }
  }, {
    from: 'number',
    to: 'Fraction',
    convert: function convert(x) {
      if (!Fraction) {
        throwNoFraction(x);
      }
      var f = new Fraction(x);
      if (f.valueOf() !== x) {
        throw new TypeError('Cannot implicitly convert a number to a Fraction when there will be a loss of precision ' + '(value: ' + x + '). ' + 'Use function fraction(x) to convert to Fraction.');
      }
      return f;
    }
  }, {
    // FIXME: add conversion from Fraction to number, for example for `sqrt(fraction(1,3))`
    //  from: 'Fraction',
    //  to: 'number',
    //  convert: function (x) {
    //    return x.valueOf()
    //  }
    // }, {
    from: 'string',
    to: 'number',
    convert: function convert(x) {
      var n = Number(x);
      if (isNaN(n)) {
        throw new Error('Cannot convert "' + x + '" to a number');
      }
      return n;
    }
  }, {
    from: 'string',
    to: 'BigNumber',
    convert: function convert(x) {
      if (!BigNumber) {
        throwNoBignumber(x);
      }
      try {
        return new BigNumber(x);
      } catch (err) {
        throw new Error('Cannot convert "' + x + '" to BigNumber');
      }
    }
  }, {
    from: 'string',
    to: 'bigint',
    convert: function convert(x) {
      try {
        return BigInt(x);
      } catch (err) {
        throw new Error('Cannot convert "' + x + '" to BigInt');
      }
    }
  }, {
    from: 'string',
    to: 'Fraction',
    convert: function convert(x) {
      if (!Fraction) {
        throwNoFraction(x);
      }
      try {
        return new Fraction(x);
      } catch (err) {
        throw new Error('Cannot convert "' + x + '" to Fraction');
      }
    }
  }, {
    from: 'string',
    to: 'Complex',
    convert: function convert(x) {
      if (!Complex) {
        throwNoComplex(x);
      }
      try {
        return new Complex(x);
      } catch (err) {
        throw new Error('Cannot convert "' + x + '" to Complex');
      }
    }
  }, {
    from: 'boolean',
    to: 'number',
    convert: function convert(x) {
      return +x;
    }
  }, {
    from: 'boolean',
    to: 'BigNumber',
    convert: function convert(x) {
      if (!BigNumber) {
        throwNoBignumber(x);
      }
      return new BigNumber(+x);
    }
  }, {
    from: 'boolean',
    to: 'bigint',
    convert: function convert(x) {
      return BigInt(+x);
    }
  }, {
    from: 'boolean',
    to: 'Fraction',
    convert: function convert(x) {
      if (!Fraction) {
        throwNoFraction(x);
      }
      return new Fraction(+x);
    }
  }, {
    from: 'boolean',
    to: 'string',
    convert: function convert(x) {
      return String(x);
    }
  }, {
    from: 'Array',
    to: 'Matrix',
    convert: function convert(array) {
      if (!DenseMatrix) {
        throwNoMatrix();
      }
      return new DenseMatrix(array);
    }
  }, {
    from: 'Matrix',
    to: 'Array',
    convert: function convert(matrix) {
      return matrix.valueOf();
    }
  }]);

  // Provide a suggestion on how to call a function elementwise
  // This was added primarily as guidance for the v10 -> v11 transition,
  // and could potentially be removed in the future if it no longer seems
  // to be helpful.
  typed.onMismatch = (name, args, signatures) => {
    var usualError = typed.createError(name, args, signatures);
    if (['wrongType', 'mismatch'].includes(usualError.data.category) && args.length === 1 && isCollection(args[0]) &&
    // check if the function can be unary:
    signatures.some(sig => !sig.params.includes(','))) {
      var err = new TypeError("Function '".concat(name, "' doesn't apply to matrices. To call it ") + "elementwise on a matrix 'M', try 'map(M, ".concat(name, ")'."));
      err.data = usualError.data;
      throw err;
    }
    throw usualError;
  };

  // Provide a suggestion on how to call a function elementwise
  // This was added primarily as guidance for the v10 -> v11 transition,
  // and could potentially be removed in the future if it no longer seems
  // to be helpful.
  typed.onMismatch = (name, args, signatures) => {
    var usualError = typed.createError(name, args, signatures);
    if (['wrongType', 'mismatch'].includes(usualError.data.category) && args.length === 1 && isCollection(args[0]) &&
    // check if the function can be unary:
    signatures.some(sig => !sig.params.includes(','))) {
      var err = new TypeError("Function '".concat(name, "' doesn't apply to matrices. To call it ") + "elementwise on a matrix 'M', try 'map(M, ".concat(name, ")'."));
      err.data = usualError.data;
      throw err;
    }
    throw usualError;
  };
  return typed;
});
function throwNoBignumber(x) {
  throw new Error("Cannot convert value ".concat(x, " into a BigNumber: no class 'BigNumber' provided"));
}
function throwNoComplex(x) {
  throw new Error("Cannot convert value ".concat(x, " into a Complex number: no class 'Complex' provided"));
}
function throwNoMatrix() {
  throw new Error('Cannot convert array into a Matrix: no class \'DenseMatrix\' provided');
}
function throwNoFraction(x) {
  throw new Error("Cannot convert value ".concat(x, " into a Fraction, no class 'Fraction' provided."));
}

var name$4V = 'ResultSet';
var dependencies$4U = [];
var createResultSet = /* #__PURE__ */factory(name$4V, dependencies$4U, () => {
  /**
   * A ResultSet contains a list or results
   * @class ResultSet
   * @param {Array} entries
   * @constructor ResultSet
   */
  function ResultSet(entries) {
    if (!(this instanceof ResultSet)) {
      throw new SyntaxError('Constructor must be called with the new operator');
    }
    this.entries = entries || [];
  }

  /**
   * Attach type information
   */
  ResultSet.prototype.type = 'ResultSet';
  ResultSet.prototype.isResultSet = true;

  /**
   * Returns the array with results hold by this ResultSet
   * @memberof ResultSet
   * @returns {Array} entries
   */
  ResultSet.prototype.valueOf = function () {
    return this.entries;
  };

  /**
   * Returns the stringified results of the ResultSet
   * @memberof ResultSet
   * @returns {string} string
   */
  ResultSet.prototype.toString = function () {
    return '[' + this.entries.join(', ') + ']';
  };

  /**
   * Get a JSON representation of the ResultSet
   * @memberof ResultSet
   * @returns {Object} Returns a JSON object structured as:
   *                   `{"mathjs": "ResultSet", "entries": [...]}`
   */
  ResultSet.prototype.toJSON = function () {
    return {
      mathjs: 'ResultSet',
      entries: this.entries
    };
  };

  /**
   * Instantiate a ResultSet from a JSON object
   * @memberof ResultSet
   * @param {Object} json  A JSON object structured as:
   *                       `{"mathjs": "ResultSet", "entries": [...]}`
   * @return {ResultSet}
   */
  ResultSet.fromJSON = function (json) {
    return new ResultSet(json.entries);
  };
  return ResultSet;
}, {
  isClass: true
});

/*!
 *  decimal.js v10.4.3
 *  An arbitrary-precision Decimal type for JavaScript.
 *  https://github.com/MikeMcl/decimal.js
 *  Copyright (c) 2022 Michael Mclaughlin <M8ch88l@gmail.com>
 *  MIT Licence
 */


// -----------------------------------  EDITABLE DEFAULTS  ------------------------------------ //


  // The maximum exponent magnitude.
  // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.
var EXP_LIMIT = 9e15,                      // 0 to 9e15

  // The limit on the value of `precision`, and on the value of the first argument to
  // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
  MAX_DIGITS = 1e9,                        // 0 to 1e9

  // Base conversion alphabet.
  NUMERALS = '0123456789abcdef',

  // The natural logarithm of 10 (1025 digits).
  LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',

  // Pi (1025 digits).
  PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',


  // The initial configuration properties of the Decimal constructor.
  DEFAULTS = {

    // These values must be integers within the stated ranges (inclusive).
    // Most of these values can be changed at run-time using the `Decimal.config` method.

    // The maximum number of significant digits of the result of a calculation or base conversion.
    // E.g. `Decimal.config({ precision: 20 });`
    precision: 20,                         // 1 to MAX_DIGITS

    // The rounding mode used when rounding to `precision`.
    //
    // ROUND_UP         0 Away from zero.
    // ROUND_DOWN       1 Towards zero.
    // ROUND_CEIL       2 Towards +Infinity.
    // ROUND_FLOOR      3 Towards -Infinity.
    // ROUND_HALF_UP    4 Towards nearest neighbour. If equidistant, up.
    // ROUND_HALF_DOWN  5 Towards nearest neighbour. If equidistant, down.
    // ROUND_HALF_EVEN  6 Towards nearest neighbour. If equidistant, towards even neighbour.
    // ROUND_HALF_CEIL  7 Towards nearest neighbour. If equidistant, towards +Infinity.
    // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
    //
    // E.g.
    // `Decimal.rounding = 4;`
    // `Decimal.rounding = Decimal.ROUND_HALF_UP;`
    rounding: 4,                           // 0 to 8

    // The modulo mode used when calculating the modulus: a mod n.
    // The quotient (q = a / n) is calculated according to the corresponding rounding mode.
    // The remainder (r) is calculated as: r = a - n * q.
    //
    // UP         0 The remainder is positive if the dividend is negative, else is negative.
    // DOWN       1 The remainder has the same sign as the dividend (JavaScript %).
    // FLOOR      3 The remainder has the same sign as the divisor (Python %).
    // HALF_EVEN  6 The IEEE 754 remainder function.
    // EUCLID     9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.
    //
    // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian
    // division (9) are commonly used for the modulus operation. The other rounding modes can also
    // be used, but they may not give useful results.
    modulo: 1,                             // 0 to 9

    // The exponent value at and beneath which `toString` returns exponential notation.
    // JavaScript numbers: -7
    toExpNeg: -7,                          // 0 to -EXP_LIMIT

    // The exponent value at and above which `toString` returns exponential notation.
    // JavaScript numbers: 21
    toExpPos:  21,                         // 0 to EXP_LIMIT

    // The minimum exponent value, beneath which underflow to zero occurs.
    // JavaScript numbers: -324  (5e-324)
    minE: -EXP_LIMIT,                      // -1 to -EXP_LIMIT

    // The maximum exponent value, above which overflow to Infinity occurs.
    // JavaScript numbers: 308  (1.7976931348623157e+308)
    maxE: EXP_LIMIT,                       // 1 to EXP_LIMIT

    // Whether to use cryptographically-secure random number generation, if available.
    crypto: false                          // true/false
  },


// ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //


  inexact, quadrant,
  external = true,

  decimalError = '[DecimalError] ',
  invalidArgument = decimalError + 'Invalid argument: ',
  precisionLimitExceeded = decimalError + 'Precision limit exceeded',
  cryptoUnavailable = decimalError + 'crypto unavailable',
  tag = '[object Decimal]',

  mathfloor = Math.floor,
  mathpow = Math.pow,

  isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,
  isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,
  isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,
  isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,

  BASE = 1e7,
  LOG_BASE = 7,
  MAX_SAFE_INTEGER = 9007199254740991,

  LN10_PRECISION = LN10.length - 1,
  PI_PRECISION = PI.length - 1,

  // Decimal.prototype object
  P$2 = { toStringTag: tag };


// Decimal prototype methods


/*
 *  absoluteValue             abs
 *  ceil
 *  clampedTo                 clamp
 *  comparedTo                cmp
 *  cosine                    cos
 *  cubeRoot                  cbrt
 *  decimalPlaces             dp
 *  dividedBy                 div
 *  dividedToIntegerBy        divToInt
 *  equals                    eq
 *  floor
 *  greaterThan               gt
 *  greaterThanOrEqualTo      gte
 *  hyperbolicCosine          cosh
 *  hyperbolicSine            sinh
 *  hyperbolicTangent         tanh
 *  inverseCosine             acos
 *  inverseHyperbolicCosine   acosh
 *  inverseHyperbolicSine     asinh
 *  inverseHyperbolicTangent  atanh
 *  inverseSine               asin
 *  inverseTangent            atan
 *  isFinite
 *  isInteger                 isInt
 *  isNaN
 *  isNegative                isNeg
 *  isPositive                isPos
 *  isZero
 *  lessThan                  lt
 *  lessThanOrEqualTo         lte
 *  logarithm                 log
 *  [maximum]                 [max]
 *  [minimum]                 [min]
 *  minus                     sub
 *  modulo                    mod
 *  naturalExponential        exp
 *  naturalLogarithm          ln
 *  negated                   neg
 *  plus                      add
 *  precision                 sd
 *  round
 *  sine                      sin
 *  squareRoot                sqrt
 *  tangent                   tan
 *  times                     mul
 *  toBinary
 *  toDecimalPlaces           toDP
 *  toExponential
 *  toFixed
 *  toFraction
 *  toHexadecimal             toHex
 *  toNearest
 *  toNumber
 *  toOctal
 *  toPower                   pow
 *  toPrecision
 *  toSignificantDigits       toSD
 *  toString
 *  truncated                 trunc
 *  valueOf                   toJSON
 */


/*
 * Return a new Decimal whose value is the absolute value of this Decimal.
 *
 */
P$2.absoluteValue = P$2.abs = function () {
  var x = new this.constructor(this);
  if (x.s < 0) x.s = 1;
  return finalise(x);
};


/*
 * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
 * direction of positive Infinity.
 *
 */
P$2.ceil = function () {
  return finalise(new this.constructor(this), this.e + 1, 2);
};


/*
 * Return a new Decimal whose value is the value of this Decimal clamped to the range
 * delineated by `min` and `max`.
 *
 * min {number|string|Decimal}
 * max {number|string|Decimal}
 *
 */
P$2.clampedTo = P$2.clamp = function (min, max) {
  var k,
    x = this,
    Ctor = x.constructor;
  min = new Ctor(min);
  max = new Ctor(max);
  if (!min.s || !max.s) return new Ctor(NaN);
  if (min.gt(max)) throw Error(invalidArgument + max);
  k = x.cmp(min);
  return k < 0 ? min : x.cmp(max) > 0 ? max : new Ctor(x);
};


/*
 * Return
 *   1    if the value of this Decimal is greater than the value of `y`,
 *  -1    if the value of this Decimal is less than the value of `y`,
 *   0    if they have the same value,
 *   NaN  if the value of either Decimal is NaN.
 *
 */
P$2.comparedTo = P$2.cmp = function (y) {
  var i, j, xdL, ydL,
    x = this,
    xd = x.d,
    yd = (y = new x.constructor(y)).d,
    xs = x.s,
    ys = y.s;

  // Either NaN or ±Infinity?
  if (!xd || !yd) {
    return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;
  }

  // Either zero?
  if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;

  // Signs differ?
  if (xs !== ys) return xs;

  // Compare exponents.
  if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;

  xdL = xd.length;
  ydL = yd.length;

  // Compare digit by digit.
  for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
    if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;
  }

  // Compare lengths.
  return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;
};


/*
 * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.
 *
 * Domain: [-Infinity, Infinity]
 * Range: [-1, 1]
 *
 * cos(0)         = 1
 * cos(-0)        = 1
 * cos(Infinity)  = NaN
 * cos(-Infinity) = NaN
 * cos(NaN)       = NaN
 *
 */
P$2.cosine = P$2.cos = function () {
  var pr, rm,
    x = this,
    Ctor = x.constructor;

  if (!x.d) return new Ctor(NaN);

  // cos(0) = cos(-0) = 1
  if (!x.d[0]) return new Ctor(1);

  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
  Ctor.rounding = 1;

  x = cosine(Ctor, toLessThanHalfPi(Ctor, x));

  Ctor.precision = pr;
  Ctor.rounding = rm;

  return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);
};


/*
 *
 * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to
 * `precision` significant digits using rounding mode `rounding`.
 *
 *  cbrt(0)  =  0
 *  cbrt(-0) = -0
 *  cbrt(1)  =  1
 *  cbrt(-1) = -1
 *  cbrt(N)  =  N
 *  cbrt(-I) = -I
 *  cbrt(I)  =  I
 *
 * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))
 *
 */
P$2.cubeRoot = P$2.cbrt = function () {
  var e, m, n, r, rep, s, sd, t, t3, t3plusx,
    x = this,
    Ctor = x.constructor;

  if (!x.isFinite() || x.isZero()) return new Ctor(x);
  external = false;

  // Initial estimate.
  s = x.s * mathpow(x.s * x, 1 / 3);

   // Math.cbrt underflow/overflow?
   // Pass x to Math.pow as integer, then adjust the exponent of the result.
  if (!s || Math.abs(s) == 1 / 0) {
    n = digitsToString(x.d);
    e = x.e;

    // Adjust n exponent so it is a multiple of 3 away from x exponent.
    if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');
    s = mathpow(n, 1 / 3);

    // Rarely, e may be one less than the result exponent value.
    e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));

    if (s == 1 / 0) {
      n = '5e' + e;
    } else {
      n = s.toExponential();
      n = n.slice(0, n.indexOf('e') + 1) + e;
    }

    r = new Ctor(n);
    r.s = x.s;
  } else {
    r = new Ctor(s.toString());
  }

  sd = (e = Ctor.precision) + 3;

  // Halley's method.
  // TODO? Compare Newton's method.
  for (;;) {
    t = r;
    t3 = t.times(t).times(t);
    t3plusx = t3.plus(x);
    r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);

    // TODO? Replace with for-loop and checkRoundingDigits.
    if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
      n = n.slice(sd - 3, sd + 1);

      // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999
      // , i.e. approaching a rounding boundary, continue the iteration.
      if (n == '9999' || !rep && n == '4999') {

        // On the first iteration only, check to see if rounding up gives the exact result as the
        // nines may infinitely repeat.
        if (!rep) {
          finalise(t, e + 1, 0);

          if (t.times(t).times(t).eq(x)) {
            r = t;
            break;
          }
        }

        sd += 4;
        rep = 1;
      } else {

        // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
        // If not, then there are further digits and m will be truthy.
        if (!+n || !+n.slice(1) && n.charAt(0) == '5') {

          // Truncate to the first rounding digit.
          finalise(r, e + 1, 1);
          m = !r.times(r).times(r).eq(x);
        }

        break;
      }
    }
  }

  external = true;

  return finalise(r, e, Ctor.rounding, m);
};


/*
 * Return the number of decimal places of the value of this Decimal.
 *
 */
P$2.decimalPlaces = P$2.dp = function () {
  var w,
    d = this.d,
    n = NaN;

  if (d) {
    w = d.length - 1;
    n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;

    // Subtract the number of trailing zeros of the last word.
    w = d[w];
    if (w) for (; w % 10 == 0; w /= 10) n--;
    if (n < 0) n = 0;
  }

  return n;
};


/*
 *  n / 0 = I
 *  n / N = N
 *  n / I = 0
 *  0 / n = 0
 *  0 / 0 = N
 *  0 / N = N
 *  0 / I = 0
 *  N / n = N
 *  N / 0 = N
 *  N / N = N
 *  N / I = N
 *  I / n = I
 *  I / 0 = I
 *  I / N = N
 *  I / I = N
 *
 * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to
 * `precision` significant digits using rounding mode `rounding`.
 *
 */
P$2.dividedBy = P$2.div = function (y) {
  return divide(this, new this.constructor(y));
};


/*
 * Return a new Decimal whose value is the integer part of dividing the value of this Decimal
 * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.
 *
 */
P$2.dividedToIntegerBy = P$2.divToInt = function (y) {
  var x = this,
    Ctor = x.constructor;
  return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);
};


/*
 * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
 *
 */
P$2.equals = P$2.eq = function (y) {
  return this.cmp(y) === 0;
};


/*
 * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
 * direction of negative Infinity.
 *
 */
P$2.floor = function () {
  return finalise(new this.constructor(this), this.e + 1, 3);
};


/*
 * Return true if the value of this Decimal is greater than the value of `y`, otherwise return
 * false.
 *
 */
P$2.greaterThan = P$2.gt = function (y) {
  return this.cmp(y) > 0;
};


/*
 * Return true if the value of this Decimal is greater than or equal to the value of `y`,
 * otherwise return false.
 *
 */
P$2.greaterThanOrEqualTo = P$2.gte = function (y) {
  var k = this.cmp(y);
  return k == 1 || k === 0;
};


/*
 * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this
 * Decimal.
 *
 * Domain: [-Infinity, Infinity]
 * Range: [1, Infinity]
 *
 * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...
 *
 * cosh(0)         = 1
 * cosh(-0)        = 1
 * cosh(Infinity)  = Infinity
 * cosh(-Infinity) = Infinity
 * cosh(NaN)       = NaN
 *
 *  x        time taken (ms)   result
 * 1000      9                 9.8503555700852349694e+433
 * 10000     25                4.4034091128314607936e+4342
 * 100000    171               1.4033316802130615897e+43429
 * 1000000   3817              1.5166076984010437725e+434294
 * 10000000  abandoned after 2 minute wait
 *
 * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))
 *
 */
P$2.hyperbolicCosine = P$2.cosh = function () {
  var k, n, pr, rm, len,
    x = this,
    Ctor = x.constructor,
    one = new Ctor(1);

  if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);
  if (x.isZero()) return one;

  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
  Ctor.rounding = 1;
  len = x.d.length;

  // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1
  // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))

  // Estimate the optimum number of times to use the argument reduction.
  // TODO? Estimation reused from cosine() and may not be optimal here.
  if (len < 32) {
    k = Math.ceil(len / 3);
    n = (1 / tinyPow(4, k)).toString();
  } else {
    k = 16;
    n = '2.3283064365386962890625e-10';
  }

  x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);

  // Reverse argument reduction
  var cosh2_x,
    i = k,
    d8 = new Ctor(8);
  for (; i--;) {
    cosh2_x = x.times(x);
    x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));
  }

  return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);
};


/*
 * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this
 * Decimal.
 *
 * Domain: [-Infinity, Infinity]
 * Range: [-Infinity, Infinity]
 *
 * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...
 *
 * sinh(0)         = 0
 * sinh(-0)        = -0
 * sinh(Infinity)  = Infinity
 * sinh(-Infinity) = -Infinity
 * sinh(NaN)       = NaN
 *
 * x        time taken (ms)
 * 10       2 ms
 * 100      5 ms
 * 1000     14 ms
 * 10000    82 ms
 * 100000   886 ms            1.4033316802130615897e+43429
 * 200000   2613 ms
 * 300000   5407 ms
 * 400000   8824 ms
 * 500000   13026 ms          8.7080643612718084129e+217146
 * 1000000  48543 ms
 *
 * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))
 *
 */
P$2.hyperbolicSine = P$2.sinh = function () {
  var k, pr, rm, len,
    x = this,
    Ctor = x.constructor;

  if (!x.isFinite() || x.isZero()) return new Ctor(x);

  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
  Ctor.rounding = 1;
  len = x.d.length;

  if (len < 3) {
    x = taylorSeries(Ctor, 2, x, x, true);
  } else {

    // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))
    // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))
    // 3 multiplications and 1 addition

    // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))
    // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))
    // 4 multiplications and 2 additions

    // Estimate the optimum number of times to use the argument reduction.
    k = 1.4 * Math.sqrt(len);
    k = k > 16 ? 16 : k | 0;

    x = x.times(1 / tinyPow(5, k));
    x = taylorSeries(Ctor, 2, x, x, true);

    // Reverse argument reduction
    var sinh2_x,
      d5 = new Ctor(5),
      d16 = new Ctor(16),
      d20 = new Ctor(20);
    for (; k--;) {
      sinh2_x = x.times(x);
      x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));
    }
  }

  Ctor.precision = pr;
  Ctor.rounding = rm;

  return finalise(x, pr, rm, true);
};


/*
 * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this
 * Decimal.
 *
 * Domain: [-Infinity, Infinity]
 * Range: [-1, 1]
 *
 * tanh(x) = sinh(x) / cosh(x)
 *
 * tanh(0)         = 0
 * tanh(-0)        = -0
 * tanh(Infinity)  = 1
 * tanh(-Infinity) = -1
 * tanh(NaN)       = NaN
 *
 */
P$2.hyperbolicTangent = P$2.tanh = function () {
  var pr, rm,
    x = this,
    Ctor = x.constructor;

  if (!x.isFinite()) return new Ctor(x.s);
  if (x.isZero()) return new Ctor(x);

  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + 7;
  Ctor.rounding = 1;

  return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);
};


/*
 * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of
 * this Decimal.
 *
 * Domain: [-1, 1]
 * Range: [0, pi]
 *
 * acos(x) = pi/2 - asin(x)
 *
 * acos(0)       = pi/2
 * acos(-0)      = pi/2
 * acos(1)       = 0
 * acos(-1)      = pi
 * acos(1/2)     = pi/3
 * acos(-1/2)    = 2*pi/3
 * acos(|x| > 1) = NaN
 * acos(NaN)     = NaN
 *
 */
P$2.inverseCosine = P$2.acos = function () {
  var halfPi,
    x = this,
    Ctor = x.constructor,
    k = x.abs().cmp(1),
    pr = Ctor.precision,
    rm = Ctor.rounding;

  if (k !== -1) {
    return k === 0
      // |x| is 1
      ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)
      // |x| > 1 or x is NaN
      : new Ctor(NaN);
  }

  if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);

  // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3

  Ctor.precision = pr + 6;
  Ctor.rounding = 1;

  x = x.asin();
  halfPi = getPi(Ctor, pr + 4, rm).times(0.5);

  Ctor.precision = pr;
  Ctor.rounding = rm;

  return halfPi.minus(x);
};


/*
 * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the
 * value of this Decimal.
 *
 * Domain: [1, Infinity]
 * Range: [0, Infinity]
 *
 * acosh(x) = ln(x + sqrt(x^2 - 1))
 *
 * acosh(x < 1)     = NaN
 * acosh(NaN)       = NaN
 * acosh(Infinity)  = Infinity
 * acosh(-Infinity) = NaN
 * acosh(0)         = NaN
 * acosh(-0)        = NaN
 * acosh(1)         = 0
 * acosh(-1)        = NaN
 *
 */
P$2.inverseHyperbolicCosine = P$2.acosh = function () {
  var pr, rm,
    x = this,
    Ctor = x.constructor;

  if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);
  if (!x.isFinite()) return new Ctor(x);

  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;
  Ctor.rounding = 1;
  external = false;

  x = x.times(x).minus(1).sqrt().plus(x);

  external = true;
  Ctor.precision = pr;
  Ctor.rounding = rm;

  return x.ln();
};


/*
 * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value
 * of this Decimal.
 *
 * Domain: [-Infinity, Infinity]
 * Range: [-Infinity, Infinity]
 *
 * asinh(x) = ln(x + sqrt(x^2 + 1))
 *
 * asinh(NaN)       = NaN
 * asinh(Infinity)  = Infinity
 * asinh(-Infinity) = -Infinity
 * asinh(0)         = 0
 * asinh(-0)        = -0
 *
 */
P$2.inverseHyperbolicSine = P$2.asinh = function () {
  var pr, rm,
    x = this,
    Ctor = x.constructor;

  if (!x.isFinite() || x.isZero()) return new Ctor(x);

  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;
  Ctor.rounding = 1;
  external = false;

  x = x.times(x).plus(1).sqrt().plus(x);

  external = true;
  Ctor.precision = pr;
  Ctor.rounding = rm;

  return x.ln();
};


/*
 * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the
 * value of this Decimal.
 *
 * Domain: [-1, 1]
 * Range: [-Infinity, Infinity]
 *
 * atanh(x) = 0.5 * ln((1 + x) / (1 - x))
 *
 * atanh(|x| > 1)   = NaN
 * atanh(NaN)       = NaN
 * atanh(Infinity)  = NaN
 * atanh(-Infinity) = NaN
 * atanh(0)         = 0
 * atanh(-0)        = -0
 * atanh(1)         = Infinity
 * atanh(-1)        = -Infinity
 *
 */
P$2.inverseHyperbolicTangent = P$2.atanh = function () {
  var pr, rm, wpr, xsd,
    x = this,
    Ctor = x.constructor;

  if (!x.isFinite()) return new Ctor(NaN);
  if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);

  pr = Ctor.precision;
  rm = Ctor.rounding;
  xsd = x.sd();

  if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);

  Ctor.precision = wpr = xsd - x.e;

  x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);

  Ctor.precision = pr + 4;
  Ctor.rounding = 1;

  x = x.ln();

  Ctor.precision = pr;
  Ctor.rounding = rm;

  return x.times(0.5);
};


/*
 * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this
 * Decimal.
 *
 * Domain: [-Infinity, Infinity]
 * Range: [-pi/2, pi/2]
 *
 * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))
 *
 * asin(0)       = 0
 * asin(-0)      = -0
 * asin(1/2)     = pi/6
 * asin(-1/2)    = -pi/6
 * asin(1)       = pi/2
 * asin(-1)      = -pi/2
 * asin(|x| > 1) = NaN
 * asin(NaN)     = NaN
 *
 * TODO? Compare performance of Taylor series.
 *
 */
P$2.inverseSine = P$2.asin = function () {
  var halfPi, k,
    pr, rm,
    x = this,
    Ctor = x.constructor;

  if (x.isZero()) return new Ctor(x);

  k = x.abs().cmp(1);
  pr = Ctor.precision;
  rm = Ctor.rounding;

  if (k !== -1) {

    // |x| is 1
    if (k === 0) {
      halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
      halfPi.s = x.s;
      return halfPi;
    }

    // |x| > 1 or x is NaN
    return new Ctor(NaN);
  }

  // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6

  Ctor.precision = pr + 6;
  Ctor.rounding = 1;

  x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();

  Ctor.precision = pr;
  Ctor.rounding = rm;

  return x.times(2);
};


/*
 * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value
 * of this Decimal.
 *
 * Domain: [-Infinity, Infinity]
 * Range: [-pi/2, pi/2]
 *
 * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
 *
 * atan(0)         = 0
 * atan(-0)        = -0
 * atan(1)         = pi/4
 * atan(-1)        = -pi/4
 * atan(Infinity)  = pi/2
 * atan(-Infinity) = -pi/2
 * atan(NaN)       = NaN
 *
 */
P$2.inverseTangent = P$2.atan = function () {
  var i, j, k, n, px, t, r, wpr, x2,
    x = this,
    Ctor = x.constructor,
    pr = Ctor.precision,
    rm = Ctor.rounding;

  if (!x.isFinite()) {
    if (!x.s) return new Ctor(NaN);
    if (pr + 4 <= PI_PRECISION) {
      r = getPi(Ctor, pr + 4, rm).times(0.5);
      r.s = x.s;
      return r;
    }
  } else if (x.isZero()) {
    return new Ctor(x);
  } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {
    r = getPi(Ctor, pr + 4, rm).times(0.25);
    r.s = x.s;
    return r;
  }

  Ctor.precision = wpr = pr + 10;
  Ctor.rounding = 1;

  // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);

  // Argument reduction
  // Ensure |x| < 0.42
  // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))

  k = Math.min(28, wpr / LOG_BASE + 2 | 0);

  for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));

  external = false;

  j = Math.ceil(wpr / LOG_BASE);
  n = 1;
  x2 = x.times(x);
  r = new Ctor(x);
  px = x;

  // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
  for (; i !== -1;) {
    px = px.times(x2);
    t = r.minus(px.div(n += 2));

    px = px.times(x2);
    r = t.plus(px.div(n += 2));

    if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);
  }

  if (k) r = r.times(2 << (k - 1));

  external = true;

  return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);
};


/*
 * Return true if the value of this Decimal is a finite number, otherwise return false.
 *
 */
P$2.isFinite = function () {
  return !!this.d;
};


/*
 * Return true if the value of this Decimal is an integer, otherwise return false.
 *
 */
P$2.isInteger = P$2.isInt = function () {
  return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;
};


/*
 * Return true if the value of this Decimal is NaN, otherwise return false.
 *
 */
P$2.isNaN = function () {
  return !this.s;
};


/*
 * Return true if the value of this Decimal is negative, otherwise return false.
 *
 */
P$2.isNegative = P$2.isNeg = function () {
  return this.s < 0;
};


/*
 * Return true if the value of this Decimal is positive, otherwise return false.
 *
 */
P$2.isPositive = P$2.isPos = function () {
  return this.s > 0;
};


/*
 * Return true if the value of this Decimal is 0 or -0, otherwise return false.
 *
 */
P$2.isZero = function () {
  return !!this.d && this.d[0] === 0;
};


/*
 * Return true if the value of this Decimal is less than `y`, otherwise return false.
 *
 */
P$2.lessThan = P$2.lt = function (y) {
  return this.cmp(y) < 0;
};


/*
 * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
 *
 */
P$2.lessThanOrEqualTo = P$2.lte = function (y) {
  return this.cmp(y) < 1;
};


/*
 * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`
 * significant digits using rounding mode `rounding`.
 *
 * If no base is specified, return log[10](arg).
 *
 * log[base](arg) = ln(arg) / ln(base)
 *
 * The result will always be correctly rounded if the base of the log is 10, and 'almost always'
 * otherwise:
 *
 * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen
 * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error
 * between the result and the correctly rounded result will be one ulp (unit in the last place).
 *
 * log[-b](a)       = NaN
 * log[0](a)        = NaN
 * log[1](a)        = NaN
 * log[NaN](a)      = NaN
 * log[Infinity](a) = NaN
 * log[b](0)        = -Infinity
 * log[b](-0)       = -Infinity
 * log[b](-a)       = NaN
 * log[b](1)        = 0
 * log[b](Infinity) = Infinity
 * log[b](NaN)      = NaN
 *
 * [base] {number|string|Decimal} The base of the logarithm.
 *
 */
P$2.logarithm = P$2.log = function (base) {
  var isBase10, d, denominator, k, inf, num, sd, r,
    arg = this,
    Ctor = arg.constructor,
    pr = Ctor.precision,
    rm = Ctor.rounding,
    guard = 5;

  // Default base is 10.
  if (base == null) {
    base = new Ctor(10);
    isBase10 = true;
  } else {
    base = new Ctor(base);
    d = base.d;

    // Return NaN if base is negative, or non-finite, or is 0 or 1.
    if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);

    isBase10 = base.eq(10);
  }

  d = arg.d;

  // Is arg negative, non-finite, 0 or 1?
  if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {
    return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);
  }

  // The result will have a non-terminating decimal expansion if base is 10 and arg is not an
  // integer power of 10.
  if (isBase10) {
    if (d.length > 1) {
      inf = true;
    } else {
      for (k = d[0]; k % 10 === 0;) k /= 10;
      inf = k !== 1;
    }
  }

  external = false;
  sd = pr + guard;
  num = naturalLogarithm(arg, sd);
  denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);

  // The result will have 5 rounding digits.
  r = divide(num, denominator, sd, 1);

  // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,
  // calculate 10 further digits.
  //
  // If the result is known to have an infinite decimal expansion, repeat this until it is clear
  // that the result is above or below the boundary. Otherwise, if after calculating the 10
  // further digits, the last 14 are nines, round up and assume the result is exact.
  // Also assume the result is exact if the last 14 are zero.
  //
  // Example of a result that will be incorrectly rounded:
  // log[1048576](4503599627370502) = 2.60000000000000009610279511444746...
  // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it
  // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so
  // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal
  // place is still 2.6.
  if (checkRoundingDigits(r.d, k = pr, rm)) {

    do {
      sd += 10;
      num = naturalLogarithm(arg, sd);
      denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
      r = divide(num, denominator, sd, 1);

      if (!inf) {

        // Check for 14 nines from the 2nd rounding digit, as the first may be 4.
        if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {
          r = finalise(r, pr + 1, 0);
        }

        break;
      }
    } while (checkRoundingDigits(r.d, k += 10, rm));
  }

  external = true;

  return finalise(r, pr, rm);
};


/*
 * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.
 *
 * arguments {number|string|Decimal}
 *
P.max = function () {
  Array.prototype.push.call(arguments, this);
  return maxOrMin(this.constructor, arguments, 'lt');
};
 */


/*
 * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.
 *
 * arguments {number|string|Decimal}
 *
P.min = function () {
  Array.prototype.push.call(arguments, this);
  return maxOrMin(this.constructor, arguments, 'gt');
};
 */


/*
 *  n - 0 = n
 *  n - N = N
 *  n - I = -I
 *  0 - n = -n
 *  0 - 0 = 0
 *  0 - N = N
 *  0 - I = -I
 *  N - n = N
 *  N - 0 = N
 *  N - N = N
 *  N - I = N
 *  I - n = I
 *  I - 0 = I
 *  I - N = N
 *  I - I = N
 *
 * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`
 * significant digits using rounding mode `rounding`.
 *
 */
P$2.minus = P$2.sub = function (y) {
  var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,
    x = this,
    Ctor = x.constructor;

  y = new Ctor(y);

  // If either is not finite...
  if (!x.d || !y.d) {

    // Return NaN if either is NaN.
    if (!x.s || !y.s) y = new Ctor(NaN);

    // Return y negated if x is finite and y is ±Infinity.
    else if (x.d) y.s = -y.s;

    // Return x if y is finite and x is ±Infinity.
    // Return x if both are ±Infinity with different signs.
    // Return NaN if both are ±Infinity with the same sign.
    else y = new Ctor(y.d || x.s !== y.s ? x : NaN);

    return y;
  }

  // If signs differ...
  if (x.s != y.s) {
    y.s = -y.s;
    return x.plus(y);
  }

  xd = x.d;
  yd = y.d;
  pr = Ctor.precision;
  rm = Ctor.rounding;

  // If either is zero...
  if (!xd[0] || !yd[0]) {

    // Return y negated if x is zero and y is non-zero.
    if (yd[0]) y.s = -y.s;

    // Return x if y is zero and x is non-zero.
    else if (xd[0]) y = new Ctor(x);

    // Return zero if both are zero.
    // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.
    else return new Ctor(rm === 3 ? -0 : 0);

    return external ? finalise(y, pr, rm) : y;
  }

  // x and y are finite, non-zero numbers with the same sign.

  // Calculate base 1e7 exponents.
  e = mathfloor(y.e / LOG_BASE);
  xe = mathfloor(x.e / LOG_BASE);

  xd = xd.slice();
  k = xe - e;

  // If base 1e7 exponents differ...
  if (k) {
    xLTy = k < 0;

    if (xLTy) {
      d = xd;
      k = -k;
      len = yd.length;
    } else {
      d = yd;
      e = xe;
      len = xd.length;
    }

    // Numbers with massively different exponents would result in a very high number of
    // zeros needing to be prepended, but this can be avoided while still ensuring correct
    // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.
    i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;

    if (k > i) {
      k = i;
      d.length = 1;
    }

    // Prepend zeros to equalise exponents.
    d.reverse();
    for (i = k; i--;) d.push(0);
    d.reverse();

  // Base 1e7 exponents equal.
  } else {

    // Check digits to determine which is the bigger number.

    i = xd.length;
    len = yd.length;
    xLTy = i < len;
    if (xLTy) len = i;

    for (i = 0; i < len; i++) {
      if (xd[i] != yd[i]) {
        xLTy = xd[i] < yd[i];
        break;
      }
    }

    k = 0;
  }

  if (xLTy) {
    d = xd;
    xd = yd;
    yd = d;
    y.s = -y.s;
  }

  len = xd.length;

  // Append zeros to `xd` if shorter.
  // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.
  for (i = yd.length - len; i > 0; --i) xd[len++] = 0;

  // Subtract yd from xd.
  for (i = yd.length; i > k;) {

    if (xd[--i] < yd[i]) {
      for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;
      --xd[j];
      xd[i] += BASE;
    }

    xd[i] -= yd[i];
  }

  // Remove trailing zeros.
  for (; xd[--len] === 0;) xd.pop();

  // Remove leading zeros and adjust exponent accordingly.
  for (; xd[0] === 0; xd.shift()) --e;

  // Zero?
  if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);

  y.d = xd;
  y.e = getBase10Exponent(xd, e);

  return external ? finalise(y, pr, rm) : y;
};


/*
 *   n % 0 =  N
 *   n % N =  N
 *   n % I =  n
 *   0 % n =  0
 *  -0 % n = -0
 *   0 % 0 =  N
 *   0 % N =  N
 *   0 % I =  0
 *   N % n =  N
 *   N % 0 =  N
 *   N % N =  N
 *   N % I =  N
 *   I % n =  N
 *   I % 0 =  N
 *   I % N =  N
 *   I % I =  N
 *
 * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to
 * `precision` significant digits using rounding mode `rounding`.
 *
 * The result depends on the modulo mode.
 *
 */
P$2.modulo = P$2.mod = function (y) {
  var q,
    x = this,
    Ctor = x.constructor;

  y = new Ctor(y);

  // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.
  if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);

  // Return x if y is ±Infinity or x is ±0.
  if (!y.d || x.d && !x.d[0]) {
    return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);
  }

  // Prevent rounding of intermediate calculations.
  external = false;

  if (Ctor.modulo == 9) {

    // Euclidian division: q = sign(y) * floor(x / abs(y))
    // result = x - q * y    where  0 <= result < abs(y)
    q = divide(x, y.abs(), 0, 3, 1);
    q.s *= y.s;
  } else {
    q = divide(x, y, 0, Ctor.modulo, 1);
  }

  q = q.times(y);

  external = true;

  return x.minus(q);
};


/*
 * Return a new Decimal whose value is the natural exponential of the value of this Decimal,
 * i.e. the base e raised to the power the value of this Decimal, rounded to `precision`
 * significant digits using rounding mode `rounding`.
 *
 */
P$2.naturalExponential = P$2.exp = function () {
  return naturalExponential(this);
};


/*
 * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
 * rounded to `precision` significant digits using rounding mode `rounding`.
 *
 */
P$2.naturalLogarithm = P$2.ln = function () {
  return naturalLogarithm(this);
};


/*
 * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
 * -1.
 *
 */
P$2.negated = P$2.neg = function () {
  var x = new this.constructor(this);
  x.s = -x.s;
  return finalise(x);
};


/*
 *  n + 0 = n
 *  n + N = N
 *  n + I = I
 *  0 + n = n
 *  0 + 0 = 0
 *  0 + N = N
 *  0 + I = I
 *  N + n = N
 *  N + 0 = N
 *  N + N = N
 *  N + I = N
 *  I + n = I
 *  I + 0 = I
 *  I + N = N
 *  I + I = I
 *
 * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`
 * significant digits using rounding mode `rounding`.
 *
 */
P$2.plus = P$2.add = function (y) {
  var carry, d, e, i, k, len, pr, rm, xd, yd,
    x = this,
    Ctor = x.constructor;

  y = new Ctor(y);

  // If either is not finite...
  if (!x.d || !y.d) {

    // Return NaN if either is NaN.
    if (!x.s || !y.s) y = new Ctor(NaN);

    // Return x if y is finite and x is ±Infinity.
    // Return x if both are ±Infinity with the same sign.
    // Return NaN if both are ±Infinity with different signs.
    // Return y if x is finite and y is ±Infinity.
    else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);

    return y;
  }

   // If signs differ...
  if (x.s != y.s) {
    y.s = -y.s;
    return x.minus(y);
  }

  xd = x.d;
  yd = y.d;
  pr = Ctor.precision;
  rm = Ctor.rounding;

  // If either is zero...
  if (!xd[0] || !yd[0]) {

    // Return x if y is zero.
    // Return y if y is non-zero.
    if (!yd[0]) y = new Ctor(x);

    return external ? finalise(y, pr, rm) : y;
  }

  // x and y are finite, non-zero numbers with the same sign.

  // Calculate base 1e7 exponents.
  k = mathfloor(x.e / LOG_BASE);
  e = mathfloor(y.e / LOG_BASE);

  xd = xd.slice();
  i = k - e;

  // If base 1e7 exponents differ...
  if (i) {

    if (i < 0) {
      d = xd;
      i = -i;
      len = yd.length;
    } else {
      d = yd;
      e = k;
      len = xd.length;
    }

    // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
    k = Math.ceil(pr / LOG_BASE);
    len = k > len ? k + 1 : len + 1;

    if (i > len) {
      i = len;
      d.length = 1;
    }

    // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
    d.reverse();
    for (; i--;) d.push(0);
    d.reverse();
  }

  len = xd.length;
  i = yd.length;

  // If yd is longer than xd, swap xd and yd so xd points to the longer array.
  if (len - i < 0) {
    i = len;
    d = yd;
    yd = xd;
    xd = d;
  }

  // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
  for (carry = 0; i;) {
    carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
    xd[i] %= BASE;
  }

  if (carry) {
    xd.unshift(carry);
    ++e;
  }

  // Remove trailing zeros.
  // No need to check for zero, as +x + +y != 0 && -x + -y != 0
  for (len = xd.length; xd[--len] == 0;) xd.pop();

  y.d = xd;
  y.e = getBase10Exponent(xd, e);

  return external ? finalise(y, pr, rm) : y;
};


/*
 * Return the number of significant digits of the value of this Decimal.
 *
 * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
 *
 */
P$2.precision = P$2.sd = function (z) {
  var k,
    x = this;

  if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);

  if (x.d) {
    k = getPrecision(x.d);
    if (z && x.e + 1 > k) k = x.e + 1;
  } else {
    k = NaN;
  }

  return k;
};


/*
 * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
 * rounding mode `rounding`.
 *
 */
P$2.round = function () {
  var x = this,
    Ctor = x.constructor;

  return finalise(new Ctor(x), x.e + 1, Ctor.rounding);
};


/*
 * Return a new Decimal whose value is the sine of the value in radians of this Decimal.
 *
 * Domain: [-Infinity, Infinity]
 * Range: [-1, 1]
 *
 * sin(x) = x - x^3/3! + x^5/5! - ...
 *
 * sin(0)         = 0
 * sin(-0)        = -0
 * sin(Infinity)  = NaN
 * sin(-Infinity) = NaN
 * sin(NaN)       = NaN
 *
 */
P$2.sine = P$2.sin = function () {
  var pr, rm,
    x = this,
    Ctor = x.constructor;

  if (!x.isFinite()) return new Ctor(NaN);
  if (x.isZero()) return new Ctor(x);

  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
  Ctor.rounding = 1;

  x = sine(Ctor, toLessThanHalfPi(Ctor, x));

  Ctor.precision = pr;
  Ctor.rounding = rm;

  return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);
};


/*
 * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`
 * significant digits using rounding mode `rounding`.
 *
 *  sqrt(-n) =  N
 *  sqrt(N)  =  N
 *  sqrt(-I) =  N
 *  sqrt(I)  =  I
 *  sqrt(0)  =  0
 *  sqrt(-0) = -0
 *
 */
P$2.squareRoot = P$2.sqrt = function () {
  var m, n, sd, r, rep, t,
    x = this,
    d = x.d,
    e = x.e,
    s = x.s,
    Ctor = x.constructor;

  // Negative/NaN/Infinity/zero?
  if (s !== 1 || !d || !d[0]) {
    return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);
  }

  external = false;

  // Initial estimate.
  s = Math.sqrt(+x);

  // Math.sqrt underflow/overflow?
  // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
  if (s == 0 || s == 1 / 0) {
    n = digitsToString(d);

    if ((n.length + e) % 2 == 0) n += '0';
    s = Math.sqrt(n);
    e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);

    if (s == 1 / 0) {
      n = '5e' + e;
    } else {
      n = s.toExponential();
      n = n.slice(0, n.indexOf('e') + 1) + e;
    }

    r = new Ctor(n);
  } else {
    r = new Ctor(s.toString());
  }

  sd = (e = Ctor.precision) + 3;

  // Newton-Raphson iteration.
  for (;;) {
    t = r;
    r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);

    // TODO? Replace with for-loop and checkRoundingDigits.
    if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
      n = n.slice(sd - 3, sd + 1);

      // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
      // 4999, i.e. approaching a rounding boundary, continue the iteration.
      if (n == '9999' || !rep && n == '4999') {

        // On the first iteration only, check to see if rounding up gives the exact result as the
        // nines may infinitely repeat.
        if (!rep) {
          finalise(t, e + 1, 0);

          if (t.times(t).eq(x)) {
            r = t;
            break;
          }
        }

        sd += 4;
        rep = 1;
      } else {

        // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
        // If not, then there are further digits and m will be truthy.
        if (!+n || !+n.slice(1) && n.charAt(0) == '5') {

          // Truncate to the first rounding digit.
          finalise(r, e + 1, 1);
          m = !r.times(r).eq(x);
        }

        break;
      }
    }
  }

  external = true;

  return finalise(r, e, Ctor.rounding, m);
};


/*
 * Return a new Decimal whose value is the tangent of the value in radians of this Decimal.
 *
 * Domain: [-Infinity, Infinity]
 * Range: [-Infinity, Infinity]
 *
 * tan(0)         = 0
 * tan(-0)        = -0
 * tan(Infinity)  = NaN
 * tan(-Infinity) = NaN
 * tan(NaN)       = NaN
 *
 */
P$2.tangent = P$2.tan = function () {
  var pr, rm,
    x = this,
    Ctor = x.constructor;

  if (!x.isFinite()) return new Ctor(NaN);
  if (x.isZero()) return new Ctor(x);

  pr = Ctor.precision;
  rm = Ctor.rounding;
  Ctor.precision = pr + 10;
  Ctor.rounding = 1;

  x = x.sin();
  x.s = 1;
  x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);

  Ctor.precision = pr;
  Ctor.rounding = rm;

  return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);
};


/*
 *  n * 0 = 0
 *  n * N = N
 *  n * I = I
 *  0 * n = 0
 *  0 * 0 = 0
 *  0 * N = N
 *  0 * I = N
 *  N * n = N
 *  N * 0 = N
 *  N * N = N
 *  N * I = N
 *  I * n = I
 *  I * 0 = N
 *  I * N = N
 *  I * I = I
 *
 * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant
 * digits using rounding mode `rounding`.
 *
 */
P$2.times = P$2.mul = function (y) {
  var carry, e, i, k, r, rL, t, xdL, ydL,
    x = this,
    Ctor = x.constructor,
    xd = x.d,
    yd = (y = new Ctor(y)).d;

  y.s *= x.s;

   // If either is NaN, ±Infinity or ±0...
  if (!xd || !xd[0] || !yd || !yd[0]) {

    return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd

      // Return NaN if either is NaN.
      // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.
      ? NaN

      // Return ±Infinity if either is ±Infinity.
      // Return ±0 if either is ±0.
      : !xd || !yd ? y.s / 0 : y.s * 0);
  }

  e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);
  xdL = xd.length;
  ydL = yd.length;

  // Ensure xd points to the longer array.
  if (xdL < ydL) {
    r = xd;
    xd = yd;
    yd = r;
    rL = xdL;
    xdL = ydL;
    ydL = rL;
  }

  // Initialise the result array with zeros.
  r = [];
  rL = xdL + ydL;
  for (i = rL; i--;) r.push(0);

  // Multiply!
  for (i = ydL; --i >= 0;) {
    carry = 0;
    for (k = xdL + i; k > i;) {
      t = r[k] + yd[i] * xd[k - i - 1] + carry;
      r[k--] = t % BASE | 0;
      carry = t / BASE | 0;
    }

    r[k] = (r[k] + carry) % BASE | 0;
  }

  // Remove trailing zeros.
  for (; !r[--rL];) r.pop();

  if (carry) ++e;
  else r.shift();

  y.d = r;
  y.e = getBase10Exponent(r, e);

  return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;
};


/*
 * Return a string representing the value of this Decimal in base 2, round to `sd` significant
 * digits using rounding mode `rm`.
 *
 * If the optional `sd` argument is present then return binary exponential notation.
 *
 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
 *
 */
P$2.toBinary = function (sd, rm) {
  return toStringBinary(this, 2, sd, rm);
};


/*
 * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
 * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
 *
 * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
 *
 * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
 *
 */
P$2.toDecimalPlaces = P$2.toDP = function (dp, rm) {
  var x = this,
    Ctor = x.constructor;

  x = new Ctor(x);
  if (dp === void 0) return x;

  checkInt32(dp, 0, MAX_DIGITS);

  if (rm === void 0) rm = Ctor.rounding;
  else checkInt32(rm, 0, 8);

  return finalise(x, dp + x.e + 1, rm);
};


/*
 * Return a string representing the value of this Decimal in exponential notation rounded to
 * `dp` fixed decimal places using rounding mode `rounding`.
 *
 * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
 *
 */
P$2.toExponential = function (dp, rm) {
  var str,
    x = this,
    Ctor = x.constructor;

  if (dp === void 0) {
    str = finiteToString(x, true);
  } else {
    checkInt32(dp, 0, MAX_DIGITS);

    if (rm === void 0) rm = Ctor.rounding;
    else checkInt32(rm, 0, 8);

    x = finalise(new Ctor(x), dp + 1, rm);
    str = finiteToString(x, true, dp + 1);
  }

  return x.isNeg() && !x.isZero() ? '-' + str : str;
};


/*
 * Return a string representing the value of this Decimal in normal (fixed-point) notation to
 * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
 * omitted.
 *
 * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
 *
 * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
 *
 * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
 * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
 * (-0).toFixed(3) is '0.000'.
 * (-0.5).toFixed(0) is '-0'.
 *
 */
P$2.toFixed = function (dp, rm) {
  var str, y,
    x = this,
    Ctor = x.constructor;

  if (dp === void 0) {
    str = finiteToString(x);
  } else {
    checkInt32(dp, 0, MAX_DIGITS);

    if (rm === void 0) rm = Ctor.rounding;
    else checkInt32(rm, 0, 8);

    y = finalise(new Ctor(x), dp + x.e + 1, rm);
    str = finiteToString(y, false, dp + y.e + 1);
  }

  // To determine whether to add the minus sign look at the value before it was rounded,
  // i.e. look at `x` rather than `y`.
  return x.isNeg() && !x.isZero() ? '-' + str : str;
};


/*
 * Return an array representing the value of this Decimal as a simple fraction with an integer
 * numerator and an integer denominator.
 *
 * The denominator will be a positive non-zero value less than or equal to the specified maximum
 * denominator. If a maximum denominator is not specified, the denominator will be the lowest
 * value necessary to represent the number exactly.
 *
 * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.
 *
 */
P$2.toFraction = function (maxD) {
  var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,
    x = this,
    xd = x.d,
    Ctor = x.constructor;

  if (!xd) return new Ctor(x);

  n1 = d0 = new Ctor(1);
  d1 = n0 = new Ctor(0);

  d = new Ctor(d1);
  e = d.e = getPrecision(xd) - x.e - 1;
  k = e % LOG_BASE;
  d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);

  if (maxD == null) {

    // d is 10**e, the minimum max-denominator needed.
    maxD = e > 0 ? d : n1;
  } else {
    n = new Ctor(maxD);
    if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);
    maxD = n.gt(d) ? (e > 0 ? d : n1) : n;
  }

  external = false;
  n = new Ctor(digitsToString(xd));
  pr = Ctor.precision;
  Ctor.precision = e = xd.length * LOG_BASE * 2;

  for (;;)  {
    q = divide(n, d, 0, 1, 1);
    d2 = d0.plus(q.times(d1));
    if (d2.cmp(maxD) == 1) break;
    d0 = d1;
    d1 = d2;
    d2 = n1;
    n1 = n0.plus(q.times(d2));
    n0 = d2;
    d2 = d;
    d = n.minus(q.times(d2));
    n = d2;
  }

  d2 = divide(maxD.minus(d0), d1, 0, 1, 1);
  n0 = n0.plus(d2.times(n1));
  d0 = d0.plus(d2.times(d1));
  n0.s = n1.s = x.s;

  // Determine which fraction is closer to x, n0/d0 or n1/d1?
  r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1
      ? [n1, d1] : [n0, d0];

  Ctor.precision = pr;
  external = true;

  return r;
};


/*
 * Return a string representing the value of this Decimal in base 16, round to `sd` significant
 * digits using rounding mode `rm`.
 *
 * If the optional `sd` argument is present then return binary exponential notation.
 *
 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
 *
 */
P$2.toHexadecimal = P$2.toHex = function (sd, rm) {
  return toStringBinary(this, 16, sd, rm);
};


/*
 * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding
 * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal.
 *
 * The return value will always have the same sign as this Decimal, unless either this Decimal
 * or `y` is NaN, in which case the return value will be also be NaN.
 *
 * The return value is not affected by the value of `precision`.
 *
 * y {number|string|Decimal} The magnitude to round to a multiple of.
 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
 *
 * 'toNearest() rounding mode not an integer: {rm}'
 * 'toNearest() rounding mode out of range: {rm}'
 *
 */
P$2.toNearest = function (y, rm) {
  var x = this,
    Ctor = x.constructor;

  x = new Ctor(x);

  if (y == null) {

    // If x is not finite, return x.
    if (!x.d) return x;

    y = new Ctor(1);
    rm = Ctor.rounding;
  } else {
    y = new Ctor(y);
    if (rm === void 0) {
      rm = Ctor.rounding;
    } else {
      checkInt32(rm, 0, 8);
    }

    // If x is not finite, return x if y is not NaN, else NaN.
    if (!x.d) return y.s ? x : y;

    // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.
    if (!y.d) {
      if (y.s) y.s = x.s;
      return y;
    }
  }

  // If y is not zero, calculate the nearest multiple of y to x.
  if (y.d[0]) {
    external = false;
    x = divide(x, y, 0, rm, 1).times(y);
    external = true;
    finalise(x);

  // If y is zero, return zero with the sign of x.
  } else {
    y.s = x.s;
    x = y;
  }

  return x;
};


/*
 * Return the value of this Decimal converted to a number primitive.
 * Zero keeps its sign.
 *
 */
P$2.toNumber = function () {
  return +this;
};


/*
 * Return a string representing the value of this Decimal in base 8, round to `sd` significant
 * digits using rounding mode `rm`.
 *
 * If the optional `sd` argument is present then return binary exponential notation.
 *
 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
 *
 */
P$2.toOctal = function (sd, rm) {
  return toStringBinary(this, 8, sd, rm);
};


/*
 * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded
 * to `precision` significant digits using rounding mode `rounding`.
 *
 * ECMAScript compliant.
 *
 *   pow(x, NaN)                           = NaN
 *   pow(x, ±0)                            = 1

 *   pow(NaN, non-zero)                    = NaN
 *   pow(abs(x) > 1, +Infinity)            = +Infinity
 *   pow(abs(x) > 1, -Infinity)            = +0
 *   pow(abs(x) == 1, ±Infinity)           = NaN
 *   pow(abs(x) < 1, +Infinity)            = +0
 *   pow(abs(x) < 1, -Infinity)            = +Infinity
 *   pow(+Infinity, y > 0)                 = +Infinity
 *   pow(+Infinity, y < 0)                 = +0
 *   pow(-Infinity, odd integer > 0)       = -Infinity
 *   pow(-Infinity, even integer > 0)      = +Infinity
 *   pow(-Infinity, odd integer < 0)       = -0
 *   pow(-Infinity, even integer < 0)      = +0
 *   pow(+0, y > 0)                        = +0
 *   pow(+0, y < 0)                        = +Infinity
 *   pow(-0, odd integer > 0)              = -0
 *   pow(-0, even integer > 0)             = +0
 *   pow(-0, odd integer < 0)              = -Infinity
 *   pow(-0, even integer < 0)             = +Infinity
 *   pow(finite x < 0, finite non-integer) = NaN
 *
 * For non-integer or very large exponents pow(x, y) is calculated using
 *
 *   x^y = exp(y*ln(x))
 *
 * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the
 * probability of an incorrectly rounded result
 * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14
 * i.e. 1 in 250,000,000,000,000
 *
 * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).
 *
 * y {number|string|Decimal} The power to which to raise this Decimal.
 *
 */
P$2.toPower = P$2.pow = function (y) {
  var e, k, pr, r, rm, s,
    x = this,
    Ctor = x.constructor,
    yn = +(y = new Ctor(y));

  // Either ±Infinity, NaN or ±0?
  if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));

  x = new Ctor(x);

  if (x.eq(1)) return x;

  pr = Ctor.precision;
  rm = Ctor.rounding;

  if (y.eq(1)) return finalise(x, pr, rm);

  // y exponent
  e = mathfloor(y.e / LOG_BASE);

  // If y is a small integer use the 'exponentiation by squaring' algorithm.
  if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
    r = intPow(Ctor, x, k, pr);
    return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);
  }

  s = x.s;

  // if x is negative
  if (s < 0) {

    // if y is not an integer
    if (e < y.d.length - 1) return new Ctor(NaN);

    // Result is positive if x is negative and the last digit of integer y is even.
    if ((y.d[e] & 1) == 0) s = 1;

    // if x.eq(-1)
    if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {
      x.s = s;
      return x;
    }
  }

  // Estimate result exponent.
  // x^y = 10^e,  where e = y * log10(x)
  // log10(x) = log10(x_significand) + x_exponent
  // log10(x_significand) = ln(x_significand) / ln(10)
  k = mathpow(+x, yn);
  e = k == 0 || !isFinite(k)
    ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))
    : new Ctor(k + '').e;

  // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.

  // Overflow/underflow?
  if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);

  external = false;
  Ctor.rounding = x.s = 1;

  // Estimate the extra guard digits needed to ensure five correct rounding digits from
  // naturalLogarithm(x). Example of failure without these extra digits (precision: 10):
  // new Decimal(2.32456).pow('2087987436534566.46411')
  // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815
  k = Math.min(12, (e + '').length);

  // r = x^y = exp(y*ln(x))
  r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);

  // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)
  if (r.d) {

    // Truncate to the required precision plus five rounding digits.
    r = finalise(r, pr + 5, 1);

    // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate
    // the result.
    if (checkRoundingDigits(r.d, pr, rm)) {
      e = pr + 10;

      // Truncate to the increased precision plus five rounding digits.
      r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);

      // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).
      if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {
        r = finalise(r, pr + 1, 0);
      }
    }
  }

  r.s = s;
  external = true;
  Ctor.rounding = rm;

  return finalise(r, pr, rm);
};


/*
 * Return a string representing the value of this Decimal rounded to `sd` significant digits
 * using rounding mode `rounding`.
 *
 * Return exponential notation if `sd` is less than the number of digits necessary to represent
 * the integer part of the value in normal notation.
 *
 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
 *
 */
P$2.toPrecision = function (sd, rm) {
  var str,
    x = this,
    Ctor = x.constructor;

  if (sd === void 0) {
    str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  } else {
    checkInt32(sd, 1, MAX_DIGITS);

    if (rm === void 0) rm = Ctor.rounding;
    else checkInt32(rm, 0, 8);

    x = finalise(new Ctor(x), sd, rm);
    str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);
  }

  return x.isNeg() && !x.isZero() ? '-' + str : str;
};


/*
 * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
 * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
 * omitted.
 *
 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
 *
 * 'toSD() digits out of range: {sd}'
 * 'toSD() digits not an integer: {sd}'
 * 'toSD() rounding mode not an integer: {rm}'
 * 'toSD() rounding mode out of range: {rm}'
 *
 */
P$2.toSignificantDigits = P$2.toSD = function (sd, rm) {
  var x = this,
    Ctor = x.constructor;

  if (sd === void 0) {
    sd = Ctor.precision;
    rm = Ctor.rounding;
  } else {
    checkInt32(sd, 1, MAX_DIGITS);

    if (rm === void 0) rm = Ctor.rounding;
    else checkInt32(rm, 0, 8);
  }

  return finalise(new Ctor(x), sd, rm);
};


/*
 * Return a string representing the value of this Decimal.
 *
 * Return exponential notation if this Decimal has a positive exponent equal to or greater than
 * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
 *
 */
P$2.toString = function () {
  var x = this,
    Ctor = x.constructor,
    str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);

  return x.isNeg() && !x.isZero() ? '-' + str : str;
};


/*
 * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.
 *
 */
P$2.truncated = P$2.trunc = function () {
  return finalise(new this.constructor(this), this.e + 1, 1);
};


/*
 * Return a string representing the value of this Decimal.
 * Unlike `toString`, negative zero will include the minus sign.
 *
 */
P$2.valueOf = P$2.toJSON = function () {
  var x = this,
    Ctor = x.constructor,
    str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);

  return x.isNeg() ? '-' + str : str;
};


// Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.


/*
 *  digitsToString           P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,
 *                           finiteToString, naturalExponential, naturalLogarithm
 *  checkInt32               P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,
 *                           P.toPrecision, P.toSignificantDigits, toStringBinary, random
 *  checkRoundingDigits      P.logarithm, P.toPower, naturalExponential, naturalLogarithm
 *  convertBase              toStringBinary, parseOther
 *  cos                      P.cos
 *  divide                   P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,
 *                           P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,
 *                           P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,
 *                           taylorSeries, atan2, parseOther
 *  finalise                 P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,
 *                           P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,
 *                           P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,
 *                           P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,
 *                           P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,
 *                           P.truncated, divide, getLn10, getPi, naturalExponential,
 *                           naturalLogarithm, ceil, floor, round, trunc
 *  finiteToString           P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,
 *                           toStringBinary
 *  getBase10Exponent        P.minus, P.plus, P.times, parseOther
 *  getLn10                  P.logarithm, naturalLogarithm
 *  getPi                    P.acos, P.asin, P.atan, toLessThanHalfPi, atan2
 *  getPrecision             P.precision, P.toFraction
 *  getZeroString            digitsToString, finiteToString
 *  intPow                   P.toPower, parseOther
 *  isOdd                    toLessThanHalfPi
 *  maxOrMin                 max, min
 *  naturalExponential       P.naturalExponential, P.toPower
 *  naturalLogarithm         P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,
 *                           P.toPower, naturalExponential
 *  nonFiniteToString        finiteToString, toStringBinary
 *  parseDecimal             Decimal
 *  parseOther               Decimal
 *  sin                      P.sin
 *  taylorSeries             P.cosh, P.sinh, cos, sin
 *  toLessThanHalfPi         P.cos, P.sin
 *  toStringBinary           P.toBinary, P.toHexadecimal, P.toOctal
 *  truncate                 intPow
 *
 *  Throws:                  P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,
 *                           naturalLogarithm, config, parseOther, random, Decimal
 */


function digitsToString(d) {
  var i, k, ws,
    indexOfLastWord = d.length - 1,
    str = '',
    w = d[0];

  if (indexOfLastWord > 0) {
    str += w;
    for (i = 1; i < indexOfLastWord; i++) {
      ws = d[i] + '';
      k = LOG_BASE - ws.length;
      if (k) str += getZeroString(k);
      str += ws;
    }

    w = d[i];
    ws = w + '';
    k = LOG_BASE - ws.length;
    if (k) str += getZeroString(k);
  } else if (w === 0) {
    return '0';
  }

  // Remove trailing zeros of last w.
  for (; w % 10 === 0;) w /= 10;

  return str + w;
}


function checkInt32(i, min, max) {
  if (i !== ~~i || i < min || i > max) {
    throw Error(invalidArgument + i);
  }
}


/*
 * Check 5 rounding digits if `repeating` is null, 4 otherwise.
 * `repeating == null` if caller is `log` or `pow`,
 * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.
 */
function checkRoundingDigits(d, i, rm, repeating) {
  var di, k, r, rd;

  // Get the length of the first word of the array d.
  for (k = d[0]; k >= 10; k /= 10) --i;

  // Is the rounding digit in the first word of d?
  if (--i < 0) {
    i += LOG_BASE;
    di = 0;
  } else {
    di = Math.ceil((i + 1) / LOG_BASE);
    i %= LOG_BASE;
  }

  // i is the index (0 - 6) of the rounding digit.
  // E.g. if within the word 3487563 the first rounding digit is 5,
  // then i = 4, k = 1000, rd = 3487563 % 1000 = 563
  k = mathpow(10, LOG_BASE - i);
  rd = d[di] % k | 0;

  if (repeating == null) {
    if (i < 3) {
      if (i == 0) rd = rd / 100 | 0;
      else if (i == 1) rd = rd / 10 | 0;
      r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;
    } else {
      r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&
        (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||
          (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;
    }
  } else {
    if (i < 4) {
      if (i == 0) rd = rd / 1000 | 0;
      else if (i == 1) rd = rd / 100 | 0;
      else if (i == 2) rd = rd / 10 | 0;
      r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;
    } else {
      r = ((repeating || rm < 4) && rd + 1 == k ||
      (!repeating && rm > 3) && rd + 1 == k / 2) &&
        (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;
    }
  }

  return r;
}


// Convert string of `baseIn` to an array of numbers of `baseOut`.
// Eg. convertBase('255', 10, 16) returns [15, 15].
// Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
function convertBase(str, baseIn, baseOut) {
  var j,
    arr = [0],
    arrL,
    i = 0,
    strL = str.length;

  for (; i < strL;) {
    for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;
    arr[0] += NUMERALS.indexOf(str.charAt(i++));
    for (j = 0; j < arr.length; j++) {
      if (arr[j] > baseOut - 1) {
        if (arr[j + 1] === void 0) arr[j + 1] = 0;
        arr[j + 1] += arr[j] / baseOut | 0;
        arr[j] %= baseOut;
      }
    }
  }

  return arr.reverse();
}


/*
 * cos(x) = 1 - x^2/2! + x^4/4! - ...
 * |x| < pi/2
 *
 */
function cosine(Ctor, x) {
  var k, len, y;

  if (x.isZero()) return x;

  // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1
  // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1

  // Estimate the optimum number of times to use the argument reduction.
  len = x.d.length;
  if (len < 32) {
    k = Math.ceil(len / 3);
    y = (1 / tinyPow(4, k)).toString();
  } else {
    k = 16;
    y = '2.3283064365386962890625e-10';
  }

  Ctor.precision += k;

  x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));

  // Reverse argument reduction
  for (var i = k; i--;) {
    var cos2x = x.times(x);
    x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);
  }

  Ctor.precision -= k;

  return x;
}


/*
 * Perform division in the specified base.
 */
var divide = (function () {

  // Assumes non-zero x and k, and hence non-zero result.
  function multiplyInteger(x, k, base) {
    var temp,
      carry = 0,
      i = x.length;

    for (x = x.slice(); i--;) {
      temp = x[i] * k + carry;
      x[i] = temp % base | 0;
      carry = temp / base | 0;
    }

    if (carry) x.unshift(carry);

    return x;
  }

  function compare(a, b, aL, bL) {
    var i, r;

    if (aL != bL) {
      r = aL > bL ? 1 : -1;
    } else {
      for (i = r = 0; i < aL; i++) {
        if (a[i] != b[i]) {
          r = a[i] > b[i] ? 1 : -1;
          break;
        }
      }
    }

    return r;
  }

  function subtract(a, b, aL, base) {
    var i = 0;

    // Subtract b from a.
    for (; aL--;) {
      a[aL] -= i;
      i = a[aL] < b[aL] ? 1 : 0;
      a[aL] = i * base + a[aL] - b[aL];
    }

    // Remove leading zeros.
    for (; !a[0] && a.length > 1;) a.shift();
  }

  return function (x, y, pr, rm, dp, base) {
    var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,
      yL, yz,
      Ctor = x.constructor,
      sign = x.s == y.s ? 1 : -1,
      xd = x.d,
      yd = y.d;

    // Either NaN, Infinity or 0?
    if (!xd || !xd[0] || !yd || !yd[0]) {

      return new Ctor(// Return NaN if either NaN, or both Infinity or 0.
        !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :

        // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.
        xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);
    }

    if (base) {
      logBase = 1;
      e = x.e - y.e;
    } else {
      base = BASE;
      logBase = LOG_BASE;
      e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);
    }

    yL = yd.length;
    xL = xd.length;
    q = new Ctor(sign);
    qd = q.d = [];

    // Result exponent may be one less than e.
    // The digit array of a Decimal from toStringBinary may have trailing zeros.
    for (i = 0; yd[i] == (xd[i] || 0); i++);

    if (yd[i] > (xd[i] || 0)) e--;

    if (pr == null) {
      sd = pr = Ctor.precision;
      rm = Ctor.rounding;
    } else if (dp) {
      sd = pr + (x.e - y.e) + 1;
    } else {
      sd = pr;
    }

    if (sd < 0) {
      qd.push(1);
      more = true;
    } else {

      // Convert precision in number of base 10 digits to base 1e7 digits.
      sd = sd / logBase + 2 | 0;
      i = 0;

      // divisor < 1e7
      if (yL == 1) {
        k = 0;
        yd = yd[0];
        sd++;

        // k is the carry.
        for (; (i < xL || k) && sd--; i++) {
          t = k * base + (xd[i] || 0);
          qd[i] = t / yd | 0;
          k = t % yd | 0;
        }

        more = k || i < xL;

      // divisor >= 1e7
      } else {

        // Normalise xd and yd so highest order digit of yd is >= base/2
        k = base / (yd[0] + 1) | 0;

        if (k > 1) {
          yd = multiplyInteger(yd, k, base);
          xd = multiplyInteger(xd, k, base);
          yL = yd.length;
          xL = xd.length;
        }

        xi = yL;
        rem = xd.slice(0, yL);
        remL = rem.length;

        // Add zeros to make remainder as long as divisor.
        for (; remL < yL;) rem[remL++] = 0;

        yz = yd.slice();
        yz.unshift(0);
        yd0 = yd[0];

        if (yd[1] >= base / 2) ++yd0;

        do {
          k = 0;

          // Compare divisor and remainder.
          cmp = compare(yd, rem, yL, remL);

          // If divisor < remainder.
          if (cmp < 0) {

            // Calculate trial digit, k.
            rem0 = rem[0];
            if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);

            // k will be how many times the divisor goes into the current remainder.
            k = rem0 / yd0 | 0;

            //  Algorithm:
            //  1. product = divisor * trial digit (k)
            //  2. if product > remainder: product -= divisor, k--
            //  3. remainder -= product
            //  4. if product was < remainder at 2:
            //    5. compare new remainder and divisor
            //    6. If remainder > divisor: remainder -= divisor, k++

            if (k > 1) {
              if (k >= base) k = base - 1;

              // product = divisor * trial digit.
              prod = multiplyInteger(yd, k, base);
              prodL = prod.length;
              remL = rem.length;

              // Compare product and remainder.
              cmp = compare(prod, rem, prodL, remL);

              // product > remainder.
              if (cmp == 1) {
                k--;

                // Subtract divisor from product.
                subtract(prod, yL < prodL ? yz : yd, prodL, base);
              }
            } else {

              // cmp is -1.
              // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1
              // to avoid it. If k is 1 there is a need to compare yd and rem again below.
              if (k == 0) cmp = k = 1;
              prod = yd.slice();
            }

            prodL = prod.length;
            if (prodL < remL) prod.unshift(0);

            // Subtract product from remainder.
            subtract(rem, prod, remL, base);

            // If product was < previous remainder.
            if (cmp == -1) {
              remL = rem.length;

              // Compare divisor and new remainder.
              cmp = compare(yd, rem, yL, remL);

              // If divisor < new remainder, subtract divisor from remainder.
              if (cmp < 1) {
                k++;

                // Subtract divisor from remainder.
                subtract(rem, yL < remL ? yz : yd, remL, base);
              }
            }

            remL = rem.length;
          } else if (cmp === 0) {
            k++;
            rem = [0];
          }    // if cmp === 1, k will be 0

          // Add the next digit, k, to the result array.
          qd[i++] = k;

          // Update the remainder.
          if (cmp && rem[0]) {
            rem[remL++] = xd[xi] || 0;
          } else {
            rem = [xd[xi]];
            remL = 1;
          }

        } while ((xi++ < xL || rem[0] !== void 0) && sd--);

        more = rem[0] !== void 0;
      }

      // Leading zero?
      if (!qd[0]) qd.shift();
    }

    // logBase is 1 when divide is being used for base conversion.
    if (logBase == 1) {
      q.e = e;
      inexact = more;
    } else {

      // To calculate q.e, first get the number of digits of qd[0].
      for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;
      q.e = i + e * logBase - 1;

      finalise(q, dp ? pr + q.e + 1 : pr, rm, more);
    }

    return q;
  };
})();


/*
 * Round `x` to `sd` significant digits using rounding mode `rm`.
 * Check for over/under-flow.
 */
 function finalise(x, sd, rm, isTruncated) {
  var digits, i, j, k, rd, roundUp, w, xd, xdi,
    Ctor = x.constructor;

  // Don't round if sd is null or undefined.
  out: if (sd != null) {
    xd = x.d;

    // Infinity/NaN.
    if (!xd) return x;

    // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.
    // w: the word of xd containing rd, a base 1e7 number.
    // xdi: the index of w within xd.
    // digits: the number of digits of w.
    // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if
    // they had leading zeros)
    // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).

    // Get the length of the first word of the digits array xd.
    for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;
    i = sd - digits;

    // Is the rounding digit in the first word of xd?
    if (i < 0) {
      i += LOG_BASE;
      j = sd;
      w = xd[xdi = 0];

      // Get the rounding digit at index j of w.
      rd = w / mathpow(10, digits - j - 1) % 10 | 0;
    } else {
      xdi = Math.ceil((i + 1) / LOG_BASE);
      k = xd.length;
      if (xdi >= k) {
        if (isTruncated) {

          // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.
          for (; k++ <= xdi;) xd.push(0);
          w = rd = 0;
          digits = 1;
          i %= LOG_BASE;
          j = i - LOG_BASE + 1;
        } else {
          break out;
        }
      } else {
        w = k = xd[xdi];

        // Get the number of digits of w.
        for (digits = 1; k >= 10; k /= 10) digits++;

        // Get the index of rd within w.
        i %= LOG_BASE;

        // Get the index of rd within w, adjusted for leading zeros.
        // The number of leading zeros of w is given by LOG_BASE - digits.
        j = i - LOG_BASE + digits;

        // Get the rounding digit at index j of w.
        rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;
      }
    }

    // Are there any non-zero digits after the rounding digit?
    isTruncated = isTruncated || sd < 0 ||
      xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));

    // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right
    // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression
    // will give 714.

    roundUp = rm < 4
      ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
      : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&

        // Check whether the digit to the left of the rounding digit is odd.
        ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||
          rm == (x.s < 0 ? 8 : 7));

    if (sd < 1 || !xd[0]) {
      xd.length = 0;
      if (roundUp) {

        // Convert sd to decimal places.
        sd -= x.e + 1;

        // 1, 0.1, 0.01, 0.001, 0.0001 etc.
        xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
        x.e = -sd || 0;
      } else {

        // Zero.
        xd[0] = x.e = 0;
      }

      return x;
    }

    // Remove excess digits.
    if (i == 0) {
      xd.length = xdi;
      k = 1;
      xdi--;
    } else {
      xd.length = xdi + 1;
      k = mathpow(10, LOG_BASE - i);

      // E.g. 56700 becomes 56000 if 7 is the rounding digit.
      // j > 0 means i > number of leading zeros of w.
      xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;
    }

    if (roundUp) {
      for (;;) {

        // Is the digit to be rounded up in the first word of xd?
        if (xdi == 0) {

          // i will be the length of xd[0] before k is added.
          for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;
          j = xd[0] += k;
          for (k = 1; j >= 10; j /= 10) k++;

          // if i != k the length has increased.
          if (i != k) {
            x.e++;
            if (xd[0] == BASE) xd[0] = 1;
          }

          break;
        } else {
          xd[xdi] += k;
          if (xd[xdi] != BASE) break;
          xd[xdi--] = 0;
          k = 1;
        }
      }
    }

    // Remove trailing zeros.
    for (i = xd.length; xd[--i] === 0;) xd.pop();
  }

  if (external) {

    // Overflow?
    if (x.e > Ctor.maxE) {

      // Infinity.
      x.d = null;
      x.e = NaN;

    // Underflow?
    } else if (x.e < Ctor.minE) {

      // Zero.
      x.e = 0;
      x.d = [0];
      // Ctor.underflow = true;
    } // else Ctor.underflow = false;
  }

  return x;
}


function finiteToString(x, isExp, sd) {
  if (!x.isFinite()) return nonFiniteToString(x);
  var k,
    e = x.e,
    str = digitsToString(x.d),
    len = str.length;

  if (isExp) {
    if (sd && (k = sd - len) > 0) {
      str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);
    } else if (len > 1) {
      str = str.charAt(0) + '.' + str.slice(1);
    }

    str = str + (x.e < 0 ? 'e' : 'e+') + x.e;
  } else if (e < 0) {
    str = '0.' + getZeroString(-e - 1) + str;
    if (sd && (k = sd - len) > 0) str += getZeroString(k);
  } else if (e >= len) {
    str += getZeroString(e + 1 - len);
    if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);
  } else {
    if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);
    if (sd && (k = sd - len) > 0) {
      if (e + 1 === len) str += '.';
      str += getZeroString(k);
    }
  }

  return str;
}


// Calculate the base 10 exponent from the base 1e7 exponent.
function getBase10Exponent(digits, e) {
  var w = digits[0];

  // Add the number of digits of the first word of the digits array.
  for ( e *= LOG_BASE; w >= 10; w /= 10) e++;
  return e;
}


function getLn10(Ctor, sd, pr) {
  if (sd > LN10_PRECISION) {

    // Reset global state in case the exception is caught.
    external = true;
    if (pr) Ctor.precision = pr;
    throw Error(precisionLimitExceeded);
  }
  return finalise(new Ctor(LN10), sd, 1, true);
}


function getPi(Ctor, sd, rm) {
  if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);
  return finalise(new Ctor(PI), sd, rm, true);
}


function getPrecision(digits) {
  var w = digits.length - 1,
    len = w * LOG_BASE + 1;

  w = digits[w];

  // If non-zero...
  if (w) {

    // Subtract the number of trailing zeros of the last word.
    for (; w % 10 == 0; w /= 10) len--;

    // Add the number of digits of the first word.
    for (w = digits[0]; w >= 10; w /= 10) len++;
  }

  return len;
}


function getZeroString(k) {
  var zs = '';
  for (; k--;) zs += '0';
  return zs;
}


/*
 * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an
 * integer of type number.
 *
 * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.
 *
 */
function intPow(Ctor, x, n, pr) {
  var isTruncated,
    r = new Ctor(1),

    // Max n of 9007199254740991 takes 53 loop iterations.
    // Maximum digits array length; leaves [28, 34] guard digits.
    k = Math.ceil(pr / LOG_BASE + 4);

  external = false;

  for (;;) {
    if (n % 2) {
      r = r.times(x);
      if (truncate(r.d, k)) isTruncated = true;
    }

    n = mathfloor(n / 2);
    if (n === 0) {

      // To ensure correct rounding when r.d is truncated, increment the last word if it is zero.
      n = r.d.length - 1;
      if (isTruncated && r.d[n] === 0) ++r.d[n];
      break;
    }

    x = x.times(x);
    truncate(x.d, k);
  }

  external = true;

  return r;
}


function isOdd(n) {
  return n.d[n.d.length - 1] & 1;
}


/*
 * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.
 */
function maxOrMin(Ctor, args, ltgt) {
  var y,
    x = new Ctor(args[0]),
    i = 0;

  for (; ++i < args.length;) {
    y = new Ctor(args[i]);
    if (!y.s) {
      x = y;
      break;
    } else if (x[ltgt](y)) {
      x = y;
    }
  }

  return x;
}


/*
 * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant
 * digits.
 *
 * Taylor/Maclaurin series.
 *
 * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
 *
 * Argument reduction:
 *   Repeat x = x / 32, k += 5, until |x| < 0.1
 *   exp(x) = exp(x / 2^k)^(2^k)
 *
 * Previously, the argument was initially reduced by
 * exp(x) = exp(r) * 10^k  where r = x - k * ln10, k = floor(x / ln10)
 * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
 * found to be slower than just dividing repeatedly by 32 as above.
 *
 * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000
 * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000
 * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)
 *
 *  exp(Infinity)  = Infinity
 *  exp(-Infinity) = 0
 *  exp(NaN)       = NaN
 *  exp(±0)        = 1
 *
 *  exp(x) is non-terminating for any finite, non-zero x.
 *
 *  The result will always be correctly rounded.
 *
 */
function naturalExponential(x, sd) {
  var denominator, guard, j, pow, sum, t, wpr,
    rep = 0,
    i = 0,
    k = 0,
    Ctor = x.constructor,
    rm = Ctor.rounding,
    pr = Ctor.precision;

  // 0/NaN/Infinity?
  if (!x.d || !x.d[0] || x.e > 17) {

    return new Ctor(x.d
      ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0
      : x.s ? x.s < 0 ? 0 : x : 0 / 0);
  }

  if (sd == null) {
    external = false;
    wpr = pr;
  } else {
    wpr = sd;
  }

  t = new Ctor(0.03125);

  // while abs(x) >= 0.1
  while (x.e > -2) {

    // x = x / 2^5
    x = x.times(t);
    k += 5;
  }

  // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision
  // necessary to ensure the first 4 rounding digits are correct.
  guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
  wpr += guard;
  denominator = pow = sum = new Ctor(1);
  Ctor.precision = wpr;

  for (;;) {
    pow = finalise(pow.times(x), wpr, 1);
    denominator = denominator.times(++i);
    t = sum.plus(divide(pow, denominator, wpr, 1));

    if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
      j = k;
      while (j--) sum = finalise(sum.times(sum), wpr, 1);

      // Check to see if the first 4 rounding digits are [49]999.
      // If so, repeat the summation with a higher precision, otherwise
      // e.g. with precision: 18, rounding: 1
      // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)
      // `wpr - guard` is the index of first rounding digit.
      if (sd == null) {

        if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
          Ctor.precision = wpr += 10;
          denominator = pow = t = new Ctor(1);
          i = 0;
          rep++;
        } else {
          return finalise(sum, Ctor.precision = pr, rm, external = true);
        }
      } else {
        Ctor.precision = pr;
        return sum;
      }
    }

    sum = t;
  }
}


/*
 * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant
 * digits.
 *
 *  ln(-n)        = NaN
 *  ln(0)         = -Infinity
 *  ln(-0)        = -Infinity
 *  ln(1)         = 0
 *  ln(Infinity)  = Infinity
 *  ln(-Infinity) = NaN
 *  ln(NaN)       = NaN
 *
 *  ln(n) (n != 1) is non-terminating.
 *
 */
function naturalLogarithm(y, sd) {
  var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,
    n = 1,
    guard = 10,
    x = y,
    xd = x.d,
    Ctor = x.constructor,
    rm = Ctor.rounding,
    pr = Ctor.precision;

  // Is x negative or Infinity, NaN, 0 or 1?
  if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {
    return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);
  }

  if (sd == null) {
    external = false;
    wpr = pr;
  } else {
    wpr = sd;
  }

  Ctor.precision = wpr += guard;
  c = digitsToString(xd);
  c0 = c.charAt(0);

  if (Math.abs(e = x.e) < 1.5e15) {

    // Argument reduction.
    // The series converges faster the closer the argument is to 1, so using
    // ln(a^b) = b * ln(a),   ln(a) = ln(a^b) / b
    // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
    // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
    // later be divided by this number, then separate out the power of 10 using
    // ln(a*10^b) = ln(a) + b*ln(10).

    // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
    //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
    // max n is 6 (gives 0.7 - 1.3)
    while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
      x = x.times(y);
      c = digitsToString(x.d);
      c0 = c.charAt(0);
      n++;
    }

    e = x.e;

    if (c0 > 1) {
      x = new Ctor('0.' + c);
      e++;
    } else {
      x = new Ctor(c0 + '.' + c.slice(1));
    }
  } else {

    // The argument reduction method above may result in overflow if the argument y is a massive
    // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
    // function using ln(x*10^e) = ln(x) + e*ln(10).
    t = getLn10(Ctor, wpr + 2, pr).times(e + '');
    x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);
    Ctor.precision = pr;

    return sd == null ? finalise(x, pr, rm, external = true) : x;
  }

  // x1 is x reduced to a value near 1.
  x1 = x;

  // Taylor series.
  // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
  // where x = (y - 1)/(y + 1)    (|x| < 1)
  sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);
  x2 = finalise(x.times(x), wpr, 1);
  denominator = 3;

  for (;;) {
    numerator = finalise(numerator.times(x2), wpr, 1);
    t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));

    if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
      sum = sum.times(2);

      // Reverse the argument reduction. Check that e is not 0 because, besides preventing an
      // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.
      if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
      sum = divide(sum, new Ctor(n), wpr, 1);

      // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has
      // been repeated previously) and the first 4 rounding digits 9999?
      // If so, restart the summation with a higher precision, otherwise
      // e.g. with precision: 12, rounding: 1
      // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.
      // `wpr - guard` is the index of first rounding digit.
      if (sd == null) {
        if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
          Ctor.precision = wpr += guard;
          t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);
          x2 = finalise(x.times(x), wpr, 1);
          denominator = rep = 1;
        } else {
          return finalise(sum, Ctor.precision = pr, rm, external = true);
        }
      } else {
        Ctor.precision = pr;
        return sum;
      }
    }

    sum = t;
    denominator += 2;
  }
}


// ±Infinity, NaN.
function nonFiniteToString(x) {
  // Unsigned.
  return String(x.s * x.s / 0);
}


/*
 * Parse the value of a new Decimal `x` from string `str`.
 */
function parseDecimal(x, str) {
  var e, i, len;

  // Decimal point?
  if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');

  // Exponential form?
  if ((i = str.search(/e/i)) > 0) {

    // Determine exponent.
    if (e < 0) e = i;
    e += +str.slice(i + 1);
    str = str.substring(0, i);
  } else if (e < 0) {

    // Integer.
    e = str.length;
  }

  // Determine leading zeros.
  for (i = 0; str.charCodeAt(i) === 48; i++);

  // Determine trailing zeros.
  for (len = str.length; str.charCodeAt(len - 1) === 48; --len);
  str = str.slice(i, len);

  if (str) {
    len -= i;
    x.e = e = e - i - 1;
    x.d = [];

    // Transform base

    // e is the base 10 exponent.
    // i is where to slice str to get the first word of the digits array.
    i = (e + 1) % LOG_BASE;
    if (e < 0) i += LOG_BASE;

    if (i < len) {
      if (i) x.d.push(+str.slice(0, i));
      for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
      str = str.slice(i);
      i = LOG_BASE - str.length;
    } else {
      i -= len;
    }

    for (; i--;) str += '0';
    x.d.push(+str);

    if (external) {

      // Overflow?
      if (x.e > x.constructor.maxE) {

        // Infinity.
        x.d = null;
        x.e = NaN;

      // Underflow?
      } else if (x.e < x.constructor.minE) {

        // Zero.
        x.e = 0;
        x.d = [0];
        // x.constructor.underflow = true;
      } // else x.constructor.underflow = false;
    }
  } else {

    // Zero.
    x.e = 0;
    x.d = [0];
  }

  return x;
}


/*
 * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.
 */
function parseOther(x, str) {
  var base, Ctor, divisor, i, isFloat, len, p, xd, xe;

  if (str.indexOf('_') > -1) {
    str = str.replace(/(\d)_(?=\d)/g, '$1');
    if (isDecimal.test(str)) return parseDecimal(x, str);
  } else if (str === 'Infinity' || str === 'NaN') {
    if (!+str) x.s = NaN;
    x.e = NaN;
    x.d = null;
    return x;
  }

  if (isHex.test(str))  {
    base = 16;
    str = str.toLowerCase();
  } else if (isBinary.test(str))  {
    base = 2;
  } else if (isOctal.test(str))  {
    base = 8;
  } else {
    throw Error(invalidArgument + str);
  }

  // Is there a binary exponent part?
  i = str.search(/p/i);

  if (i > 0) {
    p = +str.slice(i + 1);
    str = str.substring(2, i);
  } else {
    str = str.slice(2);
  }

  // Convert `str` as an integer then divide the result by `base` raised to a power such that the
  // fraction part will be restored.
  i = str.indexOf('.');
  isFloat = i >= 0;
  Ctor = x.constructor;

  if (isFloat) {
    str = str.replace('.', '');
    len = str.length;
    i = len - i;

    // log[10](16) = 1.2041... , log[10](88) = 1.9444....
    divisor = intPow(Ctor, new Ctor(base), i, i * 2);
  }

  xd = convertBase(str, base, BASE);
  xe = xd.length - 1;

  // Remove trailing zeros.
  for (i = xe; xd[i] === 0; --i) xd.pop();
  if (i < 0) return new Ctor(x.s * 0);
  x.e = getBase10Exponent(xd, xe);
  x.d = xd;
  external = false;

  // At what precision to perform the division to ensure exact conversion?
  // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)
  // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412
  // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.
  // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount
  // Therefore using 4 * the number of digits of str will always be enough.
  if (isFloat) x = divide(x, divisor, len * 4);

  // Multiply by the binary exponent part if present.
  if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p));
  external = true;

  return x;
}


/*
 * sin(x) = x - x^3/3! + x^5/5! - ...
 * |x| < pi/2
 *
 */
function sine(Ctor, x) {
  var k,
    len = x.d.length;

  if (len < 3) {
    return x.isZero() ? x : taylorSeries(Ctor, 2, x, x);
  }

  // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)
  // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)
  // and  sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))

  // Estimate the optimum number of times to use the argument reduction.
  k = 1.4 * Math.sqrt(len);
  k = k > 16 ? 16 : k | 0;

  x = x.times(1 / tinyPow(5, k));
  x = taylorSeries(Ctor, 2, x, x);

  // Reverse argument reduction
  var sin2_x,
    d5 = new Ctor(5),
    d16 = new Ctor(16),
    d20 = new Ctor(20);
  for (; k--;) {
    sin2_x = x.times(x);
    x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));
  }

  return x;
}


// Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.
function taylorSeries(Ctor, n, x, y, isHyperbolic) {
  var j, t, u, x2,
    pr = Ctor.precision,
    k = Math.ceil(pr / LOG_BASE);

  external = false;
  x2 = x.times(x);
  u = new Ctor(y);

  for (;;) {
    t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);
    u = isHyperbolic ? y.plus(t) : y.minus(t);
    y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);
    t = u.plus(y);

    if (t.d[k] !== void 0) {
      for (j = k; t.d[j] === u.d[j] && j--;);
      if (j == -1) break;
    }

    j = u;
    u = y;
    y = t;
    t = j;
  }

  external = true;
  t.d.length = k + 1;

  return t;
}


// Exponent e must be positive and non-zero.
function tinyPow(b, e) {
  var n = b;
  while (--e) n *= b;
  return n;
}


// Return the absolute value of `x` reduced to less than or equal to half pi.
function toLessThanHalfPi(Ctor, x) {
  var t,
    isNeg = x.s < 0,
    pi = getPi(Ctor, Ctor.precision, 1),
    halfPi = pi.times(0.5);

  x = x.abs();

  if (x.lte(halfPi)) {
    quadrant = isNeg ? 4 : 1;
    return x;
  }

  t = x.divToInt(pi);

  if (t.isZero()) {
    quadrant = isNeg ? 3 : 2;
  } else {
    x = x.minus(t.times(pi));

    // 0 <= x < pi
    if (x.lte(halfPi)) {
      quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);
      return x;
    }

    quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);
  }

  return x.minus(pi).abs();
}


/*
 * Return the value of Decimal `x` as a string in base `baseOut`.
 *
 * If the optional `sd` argument is present include a binary exponent suffix.
 */
function toStringBinary(x, baseOut, sd, rm) {
  var base, e, i, k, len, roundUp, str, xd, y,
    Ctor = x.constructor,
    isExp = sd !== void 0;

  if (isExp) {
    checkInt32(sd, 1, MAX_DIGITS);
    if (rm === void 0) rm = Ctor.rounding;
    else checkInt32(rm, 0, 8);
  } else {
    sd = Ctor.precision;
    rm = Ctor.rounding;
  }

  if (!x.isFinite()) {
    str = nonFiniteToString(x);
  } else {
    str = finiteToString(x);
    i = str.indexOf('.');

    // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:
    // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))
    // minBinaryExponent = floor(decimalExponent * log[2](10))
    // log[2](10) = 3.321928094887362347870319429489390175864

    if (isExp) {
      base = 2;
      if (baseOut == 16) {
        sd = sd * 4 - 3;
      } else if (baseOut == 8) {
        sd = sd * 3 - 2;
      }
    } else {
      base = baseOut;
    }

    // Convert the number as an integer then divide the result by its base raised to a power such
    // that the fraction part will be restored.

    // Non-integer.
    if (i >= 0) {
      str = str.replace('.', '');
      y = new Ctor(1);
      y.e = str.length - i;
      y.d = convertBase(finiteToString(y), 10, base);
      y.e = y.d.length;
    }

    xd = convertBase(str, 10, base);
    e = len = xd.length;

    // Remove trailing zeros.
    for (; xd[--len] == 0;) xd.pop();

    if (!xd[0]) {
      str = isExp ? '0p+0' : '0';
    } else {
      if (i < 0) {
        e--;
      } else {
        x = new Ctor(x);
        x.d = xd;
        x.e = e;
        x = divide(x, y, sd, rm, 0, base);
        xd = x.d;
        e = x.e;
        roundUp = inexact;
      }

      // The rounding digit, i.e. the digit after the digit that may be rounded up.
      i = xd[sd];
      k = base / 2;
      roundUp = roundUp || xd[sd + 1] !== void 0;

      roundUp = rm < 4
        ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))
        : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||
          rm === (x.s < 0 ? 8 : 7));

      xd.length = sd;

      if (roundUp) {

        // Rounding up may mean the previous digit has to be rounded up and so on.
        for (; ++xd[--sd] > base - 1;) {
          xd[sd] = 0;
          if (!sd) {
            ++e;
            xd.unshift(1);
          }
        }
      }

      // Determine trailing zeros.
      for (len = xd.length; !xd[len - 1]; --len);

      // E.g. [4, 11, 15] becomes 4bf.
      for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);

      // Add binary exponent suffix?
      if (isExp) {
        if (len > 1) {
          if (baseOut == 16 || baseOut == 8) {
            i = baseOut == 16 ? 4 : 3;
            for (--len; len % i; len++) str += '0';
            xd = convertBase(str, base, baseOut);
            for (len = xd.length; !xd[len - 1]; --len);

            // xd[0] will always be be 1
            for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);
          } else {
            str = str.charAt(0) + '.' + str.slice(1);
          }
        }

        str =  str + (e < 0 ? 'p' : 'p+') + e;
      } else if (e < 0) {
        for (; ++e;) str = '0' + str;
        str = '0.' + str;
      } else {
        if (++e > len) for (e -= len; e-- ;) str += '0';
        else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);
      }
    }

    str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;
  }

  return x.s < 0 ? '-' + str : str;
}


// Does not strip trailing zeros.
function truncate(arr, len) {
  if (arr.length > len) {
    arr.length = len;
    return true;
  }
}


// Decimal methods


/*
 *  abs
 *  acos
 *  acosh
 *  add
 *  asin
 *  asinh
 *  atan
 *  atanh
 *  atan2
 *  cbrt
 *  ceil
 *  clamp
 *  clone
 *  config
 *  cos
 *  cosh
 *  div
 *  exp
 *  floor
 *  hypot
 *  ln
 *  log
 *  log2
 *  log10
 *  max
 *  min
 *  mod
 *  mul
 *  pow
 *  random
 *  round
 *  set
 *  sign
 *  sin
 *  sinh
 *  sqrt
 *  sub
 *  sum
 *  tan
 *  tanh
 *  trunc
 */


/*
 * Return a new Decimal whose value is the absolute value of `x`.
 *
 * x {number|string|Decimal}
 *
 */
function abs(x) {
  return new this(x).abs();
}


/*
 * Return a new Decimal whose value is the arccosine in radians of `x`.
 *
 * x {number|string|Decimal}
 *
 */
function acos(x) {
  return new this(x).acos();
}


/*
 * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to
 * `precision` significant digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal} A value in radians.
 *
 */
function acosh(x) {
  return new this(x).acosh();
}


/*
 * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant
 * digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal}
 * y {number|string|Decimal}
 *
 */
function add(x, y) {
  return new this(x).plus(y);
}


/*
 * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`
 * significant digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal}
 *
 */
function asin(x) {
  return new this(x).asin();
}


/*
 * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to
 * `precision` significant digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal} A value in radians.
 *
 */
function asinh(x) {
  return new this(x).asinh();
}


/*
 * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`
 * significant digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal}
 *
 */
function atan(x) {
  return new this(x).atan();
}


/*
 * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to
 * `precision` significant digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal} A value in radians.
 *
 */
function atanh(x) {
  return new this(x).atanh();
}


/*
 * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi
 * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.
 *
 * Domain: [-Infinity, Infinity]
 * Range: [-pi, pi]
 *
 * y {number|string|Decimal} The y-coordinate.
 * x {number|string|Decimal} The x-coordinate.
 *
 * atan2(±0, -0)               = ±pi
 * atan2(±0, +0)               = ±0
 * atan2(±0, -x)               = ±pi for x > 0
 * atan2(±0, x)                = ±0 for x > 0
 * atan2(-y, ±0)               = -pi/2 for y > 0
 * atan2(y, ±0)                = pi/2 for y > 0
 * atan2(±y, -Infinity)        = ±pi for finite y > 0
 * atan2(±y, +Infinity)        = ±0 for finite y > 0
 * atan2(±Infinity, x)         = ±pi/2 for finite x
 * atan2(±Infinity, -Infinity) = ±3*pi/4
 * atan2(±Infinity, +Infinity) = ±pi/4
 * atan2(NaN, x) = NaN
 * atan2(y, NaN) = NaN
 *
 */
function atan2(y, x) {
  y = new this(y);
  x = new this(x);
  var r,
    pr = this.precision,
    rm = this.rounding,
    wpr = pr + 4;

  // Either NaN
  if (!y.s || !x.s) {
    r = new this(NaN);

  // Both ±Infinity
  } else if (!y.d && !x.d) {
    r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);
    r.s = y.s;

  // x is ±Infinity or y is ±0
  } else if (!x.d || y.isZero()) {
    r = x.s < 0 ? getPi(this, pr, rm) : new this(0);
    r.s = y.s;

  // y is ±Infinity or x is ±0
  } else if (!y.d || x.isZero()) {
    r = getPi(this, wpr, 1).times(0.5);
    r.s = y.s;

  // Both non-zero and finite
  } else if (x.s < 0) {
    this.precision = wpr;
    this.rounding = 1;
    r = this.atan(divide(y, x, wpr, 1));
    x = getPi(this, wpr, 1);
    this.precision = pr;
    this.rounding = rm;
    r = y.s < 0 ? r.minus(x) : r.plus(x);
  } else {
    r = this.atan(divide(y, x, wpr, 1));
  }

  return r;
}


/*
 * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant
 * digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal}
 *
 */
function cbrt(x) {
  return new this(x).cbrt();
}


/*
 * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.
 *
 * x {number|string|Decimal}
 *
 */
function ceil(x) {
  return finalise(x = new this(x), x.e + 1, 2);
}


/*
 * Return a new Decimal whose value is `x` clamped to the range delineated by `min` and `max`.
 *
 * x {number|string|Decimal}
 * min {number|string|Decimal}
 * max {number|string|Decimal}
 *
 */
function clamp(x, min, max) {
  return new this(x).clamp(min, max);
}


/*
 * Configure global settings for a Decimal constructor.
 *
 * `obj` is an object with one or more of the following properties,
 *
 *   precision  {number}
 *   rounding   {number}
 *   toExpNeg   {number}
 *   toExpPos   {number}
 *   maxE       {number}
 *   minE       {number}
 *   modulo     {number}
 *   crypto     {boolean|number}
 *   defaults   {true}
 *
 * E.g. Decimal.config({ precision: 20, rounding: 4 })
 *
 */
function config(obj) {
  if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');
  var i, p, v,
    useDefaults = obj.defaults === true,
    ps = [
      'precision', 1, MAX_DIGITS,
      'rounding', 0, 8,
      'toExpNeg', -EXP_LIMIT, 0,
      'toExpPos', 0, EXP_LIMIT,
      'maxE', 0, EXP_LIMIT,
      'minE', -EXP_LIMIT, 0,
      'modulo', 0, 9
    ];

  for (i = 0; i < ps.length; i += 3) {
    if (p = ps[i], useDefaults) this[p] = DEFAULTS[p];
    if ((v = obj[p]) !== void 0) {
      if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;
      else throw Error(invalidArgument + p + ': ' + v);
    }
  }

  if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p];
  if ((v = obj[p]) !== void 0) {
    if (v === true || v === false || v === 0 || v === 1) {
      if (v) {
        if (typeof crypto != 'undefined' && crypto &&
          (crypto.getRandomValues || crypto.randomBytes)) {
          this[p] = true;
        } else {
          throw Error(cryptoUnavailable);
        }
      } else {
        this[p] = false;
      }
    } else {
      throw Error(invalidArgument + p + ': ' + v);
    }
  }

  return this;
}


/*
 * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant
 * digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal} A value in radians.
 *
 */
function cos(x) {
  return new this(x).cos();
}


/*
 * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision
 * significant digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal} A value in radians.
 *
 */
function cosh(x) {
  return new this(x).cosh();
}


/*
 * Create and return a Decimal constructor with the same configuration properties as this Decimal
 * constructor.
 *
 */
function clone$1(obj) {
  var i, p, ps;

  /*
   * The Decimal constructor and exported function.
   * Return a new Decimal instance.
   *
   * v {number|string|Decimal} A numeric value.
   *
   */
  function Decimal(v) {
    var e, i, t,
      x = this;

    // Decimal called without new.
    if (!(x instanceof Decimal)) return new Decimal(v);

    // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
    // which points to Object.
    x.constructor = Decimal;

    // Duplicate.
    if (isDecimalInstance(v)) {
      x.s = v.s;

      if (external) {
        if (!v.d || v.e > Decimal.maxE) {

          // Infinity.
          x.e = NaN;
          x.d = null;
        } else if (v.e < Decimal.minE) {

          // Zero.
          x.e = 0;
          x.d = [0];
        } else {
          x.e = v.e;
          x.d = v.d.slice();
        }
      } else {
        x.e = v.e;
        x.d = v.d ? v.d.slice() : v.d;
      }

      return;
    }

    t = typeof v;

    if (t === 'number') {
      if (v === 0) {
        x.s = 1 / v < 0 ? -1 : 1;
        x.e = 0;
        x.d = [0];
        return;
      }

      if (v < 0) {
        v = -v;
        x.s = -1;
      } else {
        x.s = 1;
      }

      // Fast path for small integers.
      if (v === ~~v && v < 1e7) {
        for (e = 0, i = v; i >= 10; i /= 10) e++;

        if (external) {
          if (e > Decimal.maxE) {
            x.e = NaN;
            x.d = null;
          } else if (e < Decimal.minE) {
            x.e = 0;
            x.d = [0];
          } else {
            x.e = e;
            x.d = [v];
          }
        } else {
          x.e = e;
          x.d = [v];
        }

        return;

      // Infinity, NaN.
      } else if (v * 0 !== 0) {
        if (!v) x.s = NaN;
        x.e = NaN;
        x.d = null;
        return;
      }

      return parseDecimal(x, v.toString());

    } else if (t !== 'string') {
      throw Error(invalidArgument + v);
    }

    // Minus sign?
    if ((i = v.charCodeAt(0)) === 45) {
      v = v.slice(1);
      x.s = -1;
    } else {
      // Plus sign?
      if (i === 43) v = v.slice(1);
      x.s = 1;
    }

    return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);
  }

  Decimal.prototype = P$2;

  Decimal.ROUND_UP = 0;
  Decimal.ROUND_DOWN = 1;
  Decimal.ROUND_CEIL = 2;
  Decimal.ROUND_FLOOR = 3;
  Decimal.ROUND_HALF_UP = 4;
  Decimal.ROUND_HALF_DOWN = 5;
  Decimal.ROUND_HALF_EVEN = 6;
  Decimal.ROUND_HALF_CEIL = 7;
  Decimal.ROUND_HALF_FLOOR = 8;
  Decimal.EUCLID = 9;

  Decimal.config = Decimal.set = config;
  Decimal.clone = clone$1;
  Decimal.isDecimal = isDecimalInstance;

  Decimal.abs = abs;
  Decimal.acos = acos;
  Decimal.acosh = acosh;        // ES6
  Decimal.add = add;
  Decimal.asin = asin;
  Decimal.asinh = asinh;        // ES6
  Decimal.atan = atan;
  Decimal.atanh = atanh;        // ES6
  Decimal.atan2 = atan2;
  Decimal.cbrt = cbrt;          // ES6
  Decimal.ceil = ceil;
  Decimal.clamp = clamp;
  Decimal.cos = cos;
  Decimal.cosh = cosh;          // ES6
  Decimal.div = div;
  Decimal.exp = exp;
  Decimal.floor = floor;
  Decimal.hypot = hypot;        // ES6
  Decimal.ln = ln;
  Decimal.log = log;
  Decimal.log10 = log10;        // ES6
  Decimal.log2 = log2;          // ES6
  Decimal.max = max;
  Decimal.min = min;
  Decimal.mod = mod;
  Decimal.mul = mul;
  Decimal.pow = pow;
  Decimal.random = random;
  Decimal.round = round;
  Decimal.sign = sign;          // ES6
  Decimal.sin = sin;
  Decimal.sinh = sinh;          // ES6
  Decimal.sqrt = sqrt;
  Decimal.sub = sub;
  Decimal.sum = sum;
  Decimal.tan = tan;
  Decimal.tanh = tanh;          // ES6
  Decimal.trunc = trunc;        // ES6

  if (obj === void 0) obj = {};
  if (obj) {
    if (obj.defaults !== true) {
      ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];
      for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
    }
  }

  Decimal.config(obj);

  return Decimal;
}


/*
 * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant
 * digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal}
 * y {number|string|Decimal}
 *
 */
function div(x, y) {
  return new this(x).div(y);
}


/*
 * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`
 * significant digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal} The power to which to raise the base of the natural log.
 *
 */
function exp(x) {
  return new this(x).exp();
}


/*
 * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.
 *
 * x {number|string|Decimal}
 *
 */
function floor(x) {
  return finalise(x = new this(x), x.e + 1, 3);
}


/*
 * Return a new Decimal whose value is the square root of the sum of the squares of the arguments,
 * rounded to `precision` significant digits using rounding mode `rounding`.
 *
 * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)
 *
 * arguments {number|string|Decimal}
 *
 */
function hypot() {
  var i, n,
    t = new this(0);

  external = false;

  for (i = 0; i < arguments.length;) {
    n = new this(arguments[i++]);
    if (!n.d) {
      if (n.s) {
        external = true;
        return new this(1 / 0);
      }
      t = n;
    } else if (t.d) {
      t = t.plus(n.times(n));
    }
  }

  external = true;

  return t.sqrt();
}


/*
 * Return true if object is a Decimal instance (where Decimal is any Decimal constructor),
 * otherwise return false.
 *
 */
function isDecimalInstance(obj) {
  return obj instanceof Decimal || obj && obj.toStringTag === tag || false;
}


/*
 * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`
 * significant digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal}
 *
 */
function ln(x) {
  return new this(x).ln();
}


/*
 * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base
 * is specified, rounded to `precision` significant digits using rounding mode `rounding`.
 *
 * log[y](x)
 *
 * x {number|string|Decimal} The argument of the logarithm.
 * y {number|string|Decimal} The base of the logarithm.
 *
 */
function log(x, y) {
  return new this(x).log(y);
}


/*
 * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`
 * significant digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal}
 *
 */
function log2(x) {
  return new this(x).log(2);
}


/*
 * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`
 * significant digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal}
 *
 */
function log10(x) {
  return new this(x).log(10);
}


/*
 * Return a new Decimal whose value is the maximum of the arguments.
 *
 * arguments {number|string|Decimal}
 *
 */
function max() {
  return maxOrMin(this, arguments, 'lt');
}


/*
 * Return a new Decimal whose value is the minimum of the arguments.
 *
 * arguments {number|string|Decimal}
 *
 */
function min() {
  return maxOrMin(this, arguments, 'gt');
}


/*
 * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits
 * using rounding mode `rounding`.
 *
 * x {number|string|Decimal}
 * y {number|string|Decimal}
 *
 */
function mod(x, y) {
  return new this(x).mod(y);
}


/*
 * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant
 * digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal}
 * y {number|string|Decimal}
 *
 */
function mul(x, y) {
  return new this(x).mul(y);
}


/*
 * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision
 * significant digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal} The base.
 * y {number|string|Decimal} The exponent.
 *
 */
function pow(x, y) {
  return new this(x).pow(y);
}


/*
 * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with
 * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros
 * are produced).
 *
 * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.
 *
 */
function random(sd) {
  var d, e, k, n,
    i = 0,
    r = new this(1),
    rd = [];

  if (sd === void 0) sd = this.precision;
  else checkInt32(sd, 1, MAX_DIGITS);

  k = Math.ceil(sd / LOG_BASE);

  if (!this.crypto) {
    for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;

  // Browsers supporting crypto.getRandomValues.
  } else if (crypto.getRandomValues) {
    d = crypto.getRandomValues(new Uint32Array(k));

    for (; i < k;) {
      n = d[i];

      // 0 <= n < 4294967296
      // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).
      if (n >= 4.29e9) {
        d[i] = crypto.getRandomValues(new Uint32Array(1))[0];
      } else {

        // 0 <= n <= 4289999999
        // 0 <= (n % 1e7) <= 9999999
        rd[i++] = n % 1e7;
      }
    }

  // Node.js supporting crypto.randomBytes.
  } else if (crypto.randomBytes) {

    // buffer
    d = crypto.randomBytes(k *= 4);

    for (; i < k;) {

      // 0 <= n < 2147483648
      n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);

      // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).
      if (n >= 2.14e9) {
        crypto.randomBytes(4).copy(d, i);
      } else {

        // 0 <= n <= 2139999999
        // 0 <= (n % 1e7) <= 9999999
        rd.push(n % 1e7);
        i += 4;
      }
    }

    i = k / 4;
  } else {
    throw Error(cryptoUnavailable);
  }

  k = rd[--i];
  sd %= LOG_BASE;

  // Convert trailing digits to zeros according to sd.
  if (k && sd) {
    n = mathpow(10, LOG_BASE - sd);
    rd[i] = (k / n | 0) * n;
  }

  // Remove trailing words which are zero.
  for (; rd[i] === 0; i--) rd.pop();

  // Zero?
  if (i < 0) {
    e = 0;
    rd = [0];
  } else {
    e = -1;

    // Remove leading words which are zero and adjust exponent accordingly.
    for (; rd[0] === 0; e -= LOG_BASE) rd.shift();

    // Count the digits of the first word of rd to determine leading zeros.
    for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;

    // Adjust the exponent for leading zeros of the first word of rd.
    if (k < LOG_BASE) e -= LOG_BASE - k;
  }

  r.e = e;
  r.d = rd;

  return r;
}


/*
 * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.
 *
 * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).
 *
 * x {number|string|Decimal}
 *
 */
function round(x) {
  return finalise(x = new this(x), x.e + 1, this.rounding);
}


/*
 * Return
 *   1    if x > 0,
 *  -1    if x < 0,
 *   0    if x is 0,
 *  -0    if x is -0,
 *   NaN  otherwise
 *
 * x {number|string|Decimal}
 *
 */
function sign(x) {
  x = new this(x);
  return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;
}


/*
 * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits
 * using rounding mode `rounding`.
 *
 * x {number|string|Decimal} A value in radians.
 *
 */
function sin(x) {
  return new this(x).sin();
}


/*
 * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`
 * significant digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal} A value in radians.
 *
 */
function sinh(x) {
  return new this(x).sinh();
}


/*
 * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant
 * digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal}
 *
 */
function sqrt(x) {
  return new this(x).sqrt();
}


/*
 * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits
 * using rounding mode `rounding`.
 *
 * x {number|string|Decimal}
 * y {number|string|Decimal}
 *
 */
function sub(x, y) {
  return new this(x).sub(y);
}


/*
 * Return a new Decimal whose value is the sum of the arguments, rounded to `precision`
 * significant digits using rounding mode `rounding`.
 *
 * Only the result is rounded, not the intermediate calculations.
 *
 * arguments {number|string|Decimal}
 *
 */
function sum() {
  var i = 0,
    args = arguments,
    x = new this(args[i]);

  external = false;
  for (; x.s && ++i < args.length;) x = x.plus(args[i]);
  external = true;

  return finalise(x, this.precision, this.rounding);
}


/*
 * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant
 * digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal} A value in radians.
 *
 */
function tan(x) {
  return new this(x).tan();
}


/*
 * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`
 * significant digits using rounding mode `rounding`.
 *
 * x {number|string|Decimal} A value in radians.
 *
 */
function tanh(x) {
  return new this(x).tanh();
}


/*
 * Return a new Decimal whose value is `x` truncated to an integer.
 *
 * x {number|string|Decimal}
 *
 */
function trunc(x) {
  return finalise(x = new this(x), x.e + 1, 1);
}


P$2[Symbol.for('nodejs.util.inspect.custom')] = P$2.toString;
P$2[Symbol.toStringTag] = 'Decimal';

// Create and configure initial Decimal constructor.
var Decimal = P$2.constructor = clone$1(DEFAULTS);

// Create the internal constants from their string values.
LN10 = new Decimal(LN10);
PI = new Decimal(PI);

var name$4U = 'BigNumber';
var dependencies$4T = ['?on', 'config'];
var createBigNumberClass = /* #__PURE__ */factory(name$4U, dependencies$4T, _ref => {
  var {
    on,
    config
  } = _ref;
  var BigNumber = Decimal.clone({
    precision: config.precision,
    modulo: Decimal.EUCLID
  });
  BigNumber.prototype = Object.create(BigNumber.prototype);

  /**
   * Attach type information
   */
  BigNumber.prototype.type = 'BigNumber';
  BigNumber.prototype.isBigNumber = true;

  /**
   * Get a JSON representation of a BigNumber containing
   * type information
   * @returns {Object} Returns a JSON object structured as:
   *                   `{"mathjs": "BigNumber", "value": "0.2"}`
   */
  BigNumber.prototype.toJSON = function () {
    return {
      mathjs: 'BigNumber',
      value: this.toString()
    };
  };

  /**
   * Instantiate a BigNumber from a JSON object
   * @param {Object} json  a JSON object structured as:
   *                       `{"mathjs": "BigNumber", "value": "0.2"}`
   * @return {BigNumber}
   */
  BigNumber.fromJSON = function (json) {
    return new BigNumber(json.value);
  };
  if (on) {
    // listen for changed in the configuration, automatically apply changed precision
    on('config', function (curr, prev) {
      if (curr.precision !== prev.precision) {
        BigNumber.config({
          precision: curr.precision
        });
      }
    });
  }
  return BigNumber;
}, {
  isClass: true
});

var complex = {exports: {}};

/**
 * @license Complex.js v2.1.1 12/05/2020
 *
 * Copyright (c) 2020, Robert Eisele (robert@xarg.org)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 **/

(function (module, exports) {
/**
 *
 * This class allows the manipulation of complex numbers.
 * You can pass a complex number in different formats. Either as object, double, string or two integer parameters.
 *
 * Object form
 * { re: <real>, im: <imaginary> }
 * { arg: <angle>, abs: <radius> }
 * { phi: <angle>, r: <radius> }
 *
 * Array / Vector form
 * [ real, imaginary ]
 *
 * Double form
 * 99.3 - Single double value
 *
 * String form
 * '23.1337' - Simple real number
 * '15+3i' - a simple complex number
 * '3-i' - a simple complex number
 *
 * Example:
 *
 * var c = new Complex('99.3+8i');
 * c.mul({r: 3, i: 9}).div(4.9).sub(3, 2);
 *
 */

(function(root) {

  var cosh = Math.cosh || function(x) {
    return Math.abs(x) < 1e-9 ? 1 - x : (Math.exp(x) + Math.exp(-x)) * 0.5;
  };

  var sinh = Math.sinh || function(x) {
    return Math.abs(x) < 1e-9 ? x : (Math.exp(x) - Math.exp(-x)) * 0.5;
  };

  /**
   * Calculates cos(x) - 1 using Taylor series if x is small (-¼π ≤ x ≤ ¼π).
   *
   * @param {number} x
   * @returns {number} cos(x) - 1
   */
  var cosm1 = function(x) {

    var b = Math.PI / 4;
    if (-b > x || x > b) {
      return Math.cos(x) - 1.0;
    }

    /* Calculate horner form of polynomial of taylor series in Q
    var fac = 1, alt = 1, pol = {};
    for (var i = 0; i <= 16; i++) {
      fac*= i || 1;
      if (i % 2 == 0) {
        pol[i] = new Fraction(1, alt * fac);
        alt = -alt;
      }
    }
    console.log(new Polynomial(pol).toHorner()); // (((((((1/20922789888000x^2-1/87178291200)x^2+1/479001600)x^2-1/3628800)x^2+1/40320)x^2-1/720)x^2+1/24)x^2-1/2)x^2+1
    */

    var xx = x * x;
    return xx * (
      xx * (
        xx * (
          xx * (
            xx * (
              xx * (
                xx * (
                  xx / 20922789888000
                  - 1 / 87178291200)
                + 1 / 479001600)
              - 1 / 3628800)
            + 1 / 40320)
          - 1 / 720)
        + 1 / 24)
      - 1 / 2);
  };

  var hypot = function(x, y) {

    var a = Math.abs(x);
    var b = Math.abs(y);

    if (a < 3000 && b < 3000) {
      return Math.sqrt(a * a + b * b);
    }

    if (a < b) {
      a = b;
      b = x / y;
    } else {
      b = y / x;
    }
    return a * Math.sqrt(1 + b * b);
  };

  var parser_exit = function() {
    throw SyntaxError('Invalid Param');
  };

  /**
   * Calculates log(sqrt(a^2+b^2)) in a way to avoid overflows
   *
   * @param {number} a
   * @param {number} b
   * @returns {number}
   */
  function logHypot(a, b) {

    var _a = Math.abs(a);
    var _b = Math.abs(b);

    if (a === 0) {
      return Math.log(_b);
    }

    if (b === 0) {
      return Math.log(_a);
    }

    if (_a < 3000 && _b < 3000) {
      return Math.log(a * a + b * b) * 0.5;
    }

    /* I got 4 ideas to compute this property without overflow:
     *
     * Testing 1000000 times with random samples for a,b ∈ [1, 1000000000] against a big decimal library to get an error estimate
     *
     * 1. Only eliminate the square root: (OVERALL ERROR: 3.9122483030951116e-11)

     Math.log(a * a + b * b) / 2

     *
     *
     * 2. Try to use the non-overflowing pythagoras: (OVERALL ERROR: 8.889760039210159e-10)

     var fn = function(a, b) {
     a = Math.abs(a);
     b = Math.abs(b);
     var t = Math.min(a, b);
     a = Math.max(a, b);
     t = t / a;

     return Math.log(a) + Math.log(1 + t * t) / 2;
     };

     * 3. Abuse the identity cos(atan(y/x) = x / sqrt(x^2+y^2): (OVERALL ERROR: 3.4780178737037204e-10)

     Math.log(a / Math.cos(Math.atan2(b, a)))

     * 4. Use 3. and apply log rules: (OVERALL ERROR: 1.2014087502620896e-9)

     Math.log(a) - Math.log(Math.cos(Math.atan2(b, a)))

     */

     a = a / 2;
     b = b / 2;

    return 0.5 * Math.log(a * a + b * b) + Math.LN2;
  }

  var parse = function(a, b) {

    var z = { 're': 0, 'im': 0 };

    if (a === undefined || a === null) {
      z['re'] =
      z['im'] = 0;
    } else if (b !== undefined) {
      z['re'] = a;
      z['im'] = b;
    } else
      switch (typeof a) {

        case 'object':

          if ('im' in a && 're' in a) {
            z['re'] = a['re'];
            z['im'] = a['im'];
          } else if ('abs' in a && 'arg' in a) {
            if (!Number.isFinite(a['abs']) && Number.isFinite(a['arg'])) {
              return Complex['INFINITY'];
            }
            z['re'] = a['abs'] * Math.cos(a['arg']);
            z['im'] = a['abs'] * Math.sin(a['arg']);
          } else if ('r' in a && 'phi' in a) {
            if (!Number.isFinite(a['r']) && Number.isFinite(a['phi'])) {
              return Complex['INFINITY'];
            }
            z['re'] = a['r'] * Math.cos(a['phi']);
            z['im'] = a['r'] * Math.sin(a['phi']);
          } else if (a.length === 2) { // Quick array check
            z['re'] = a[0];
            z['im'] = a[1];
          } else {
            parser_exit();
          }
          break;

        case 'string':

          z['im'] = /* void */
          z['re'] = 0;

          var tokens = a.match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g);
          var plus = 1;
          var minus = 0;

          if (tokens === null) {
            parser_exit();
          }

          for (var i = 0; i < tokens.length; i++) {

            var c = tokens[i];

            if (c === ' ' || c === '\t' || c === '\n') ; else if (c === '+') {
              plus++;
            } else if (c === '-') {
              minus++;
            } else if (c === 'i' || c === 'I') {

              if (plus + minus === 0) {
                parser_exit();
              }

              if (tokens[i + 1] !== ' ' && !isNaN(tokens[i + 1])) {
                z['im'] += parseFloat((minus % 2 ? '-' : '') + tokens[i + 1]);
                i++;
              } else {
                z['im'] += parseFloat((minus % 2 ? '-' : '') + '1');
              }
              plus = minus = 0;

            } else {

              if (plus + minus === 0 || isNaN(c)) {
                parser_exit();
              }

              if (tokens[i + 1] === 'i' || tokens[i + 1] === 'I') {
                z['im'] += parseFloat((minus % 2 ? '-' : '') + c);
                i++;
              } else {
                z['re'] += parseFloat((minus % 2 ? '-' : '') + c);
              }
              plus = minus = 0;
            }
          }

          // Still something on the stack
          if (plus + minus > 0) {
            parser_exit();
          }
          break;

        case 'number':
          z['im'] = 0;
          z['re'] = a;
          break;

        default:
          parser_exit();
      }

    if (isNaN(z['re']) || isNaN(z['im'])) ;

    return z;
  };

  /**
   * @constructor
   * @returns {Complex}
   */
  function Complex(a, b) {

    if (!(this instanceof Complex)) {
      return new Complex(a, b);
    }

    var z = parse(a, b);

    this['re'] = z['re'];
    this['im'] = z['im'];
  }

  Complex.prototype = {

    're': 0,
    'im': 0,

    /**
     * Calculates the sign of a complex number, which is a normalized complex
     *
     * @returns {Complex}
     */
    'sign': function() {

      var abs = this['abs']();

      return new Complex(
        this['re'] / abs,
        this['im'] / abs);
    },

    /**
     * Adds two complex numbers
     *
     * @returns {Complex}
     */
    'add': function(a, b) {

      var z = new Complex(a, b);

      // Infinity + Infinity = NaN
      if (this['isInfinite']() && z['isInfinite']()) {
        return Complex['NAN'];
      }

      // Infinity + z = Infinity { where z != Infinity }
      if (this['isInfinite']() || z['isInfinite']()) {
        return Complex['INFINITY'];
      }

      return new Complex(
        this['re'] + z['re'],
        this['im'] + z['im']);
    },

    /**
     * Subtracts two complex numbers
     *
     * @returns {Complex}
     */
    'sub': function(a, b) {

      var z = new Complex(a, b);

      // Infinity - Infinity = NaN
      if (this['isInfinite']() && z['isInfinite']()) {
        return Complex['NAN'];
      }

      // Infinity - z = Infinity { where z != Infinity }
      if (this['isInfinite']() || z['isInfinite']()) {
        return Complex['INFINITY'];
      }

      return new Complex(
        this['re'] - z['re'],
        this['im'] - z['im']);
    },

    /**
     * Multiplies two complex numbers
     *
     * @returns {Complex}
     */
    'mul': function(a, b) {

      var z = new Complex(a, b);

      // Infinity * 0 = NaN
      if ((this['isInfinite']() && z['isZero']()) || (this['isZero']() && z['isInfinite']())) {
        return Complex['NAN'];
      }

      // Infinity * z = Infinity { where z != 0 }
      if (this['isInfinite']() || z['isInfinite']()) {
        return Complex['INFINITY'];
      }

      // Short circuit for real values
      if (z['im'] === 0 && this['im'] === 0) {
        return new Complex(this['re'] * z['re'], 0);
      }

      return new Complex(
        this['re'] * z['re'] - this['im'] * z['im'],
        this['re'] * z['im'] + this['im'] * z['re']);
    },

    /**
     * Divides two complex numbers
     *
     * @returns {Complex}
     */
    'div': function(a, b) {

      var z = new Complex(a, b);

      // 0 / 0 = NaN and Infinity / Infinity = NaN
      if ((this['isZero']() && z['isZero']()) || (this['isInfinite']() && z['isInfinite']())) {
        return Complex['NAN'];
      }

      // Infinity / 0 = Infinity
      if (this['isInfinite']() || z['isZero']()) {
        return Complex['INFINITY'];
      }

      // 0 / Infinity = 0
      if (this['isZero']() || z['isInfinite']()) {
        return Complex['ZERO'];
      }

      a = this['re'];
      b = this['im'];

      var c = z['re'];
      var d = z['im'];
      var t, x;

      if (0 === d) {
        // Divisor is real
        return new Complex(a / c, b / c);
      }

      if (Math.abs(c) < Math.abs(d)) {

        x = c / d;
        t = c * x + d;

        return new Complex(
          (a * x + b) / t,
          (b * x - a) / t);

      } else {

        x = d / c;
        t = d * x + c;

        return new Complex(
          (a + b * x) / t,
          (b - a * x) / t);
      }
    },

    /**
     * Calculate the power of two complex numbers
     *
     * @returns {Complex}
     */
    'pow': function(a, b) {

      var z = new Complex(a, b);

      a = this['re'];
      b = this['im'];

      if (z['isZero']()) {
        return Complex['ONE'];
      }

      // If the exponent is real
      if (z['im'] === 0) {

        if (b === 0 && a > 0) {

          return new Complex(Math.pow(a, z['re']), 0);

        } else if (a === 0) { // If base is fully imaginary

          switch ((z['re'] % 4 + 4) % 4) {
            case 0:
              return new Complex(Math.pow(b, z['re']), 0);
            case 1:
              return new Complex(0, Math.pow(b, z['re']));
            case 2:
              return new Complex(-Math.pow(b, z['re']), 0);
            case 3:
              return new Complex(0, -Math.pow(b, z['re']));
          }
        }
      }

      /* I couldn't find a good formula, so here is a derivation and optimization
       *
       * z_1^z_2 = (a + bi)^(c + di)
       *         = exp((c + di) * log(a + bi)
       *         = pow(a^2 + b^2, (c + di) / 2) * exp(i(c + di)atan2(b, a))
       * =>...
       * 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))
       * 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))
       *
       * =>...
       * 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))
       * 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))
       *
       * =>
       * Re = exp(c * logsq2 - d * arg(z_1)) * cos(d * logsq2 + c * arg(z_1))
       * Im = exp(c * logsq2 - d * arg(z_1)) * sin(d * logsq2 + c * arg(z_1))
       *
       */

      if (a === 0 && b === 0 && z['re'] > 0 && z['im'] >= 0) {
        return Complex['ZERO'];
      }

      var arg = Math.atan2(b, a);
      var loh = logHypot(a, b);

      a = Math.exp(z['re'] * loh - z['im'] * arg);
      b = z['im'] * loh + z['re'] * arg;
      return new Complex(
        a * Math.cos(b),
        a * Math.sin(b));
    },

    /**
     * Calculate the complex square root
     *
     * @returns {Complex}
     */
    'sqrt': function() {

      var a = this['re'];
      var b = this['im'];
      var r = this['abs']();

      var re, im;

      if (a >= 0) {

        if (b === 0) {
          return new Complex(Math.sqrt(a), 0);
        }

        re = 0.5 * Math.sqrt(2.0 * (r + a));
      } else {
        re = Math.abs(b) / Math.sqrt(2 * (r - a));
      }

      if (a <= 0) {
        im = 0.5 * Math.sqrt(2.0 * (r - a));
      } else {
        im = Math.abs(b) / Math.sqrt(2 * (r + a));
      }

      return new Complex(re, b < 0 ? -im : im);
    },

    /**
     * Calculate the complex exponent
     *
     * @returns {Complex}
     */
    'exp': function() {

      var tmp = Math.exp(this['re']);

      if (this['im'] === 0) ;
      return new Complex(
        tmp * Math.cos(this['im']),
        tmp * Math.sin(this['im']));
    },

    /**
     * Calculate the complex exponent and subtracts one.
     *
     * This may be more accurate than `Complex(x).exp().sub(1)` if
     * `x` is small.
     *
     * @returns {Complex}
     */
    'expm1': function() {

      /**
       * exp(a + i*b) - 1
       = exp(a) * (cos(b) + j*sin(b)) - 1
       = expm1(a)*cos(b) + cosm1(b) + j*exp(a)*sin(b)
       */

      var a = this['re'];
      var b = this['im'];

      return new Complex(
        Math.expm1(a) * Math.cos(b) + cosm1(b),
        Math.exp(a) * Math.sin(b));
    },

    /**
     * Calculate the natural log
     *
     * @returns {Complex}
     */
    'log': function() {

      var a = this['re'];
      var b = this['im'];

      return new Complex(
        logHypot(a, b),
        Math.atan2(b, a));
    },

    /**
     * Calculate the magnitude of the complex number
     *
     * @returns {number}
     */
    'abs': function() {

      return hypot(this['re'], this['im']);
    },

    /**
     * Calculate the angle of the complex number
     *
     * @returns {number}
     */
    'arg': function() {

      return Math.atan2(this['im'], this['re']);
    },

    /**
     * Calculate the sine of the complex number
     *
     * @returns {Complex}
     */
    'sin': function() {

      // sin(z) = ( e^iz - e^-iz ) / 2i 
      //        = sin(a)cosh(b) + i cos(a)sinh(b)

      var a = this['re'];
      var b = this['im'];

      return new Complex(
        Math.sin(a) * cosh(b),
        Math.cos(a) * sinh(b));
    },

    /**
     * Calculate the cosine
     *
     * @returns {Complex}
     */
    'cos': function() {

      // cos(z) = ( e^iz + e^-iz ) / 2 
      //        = cos(a)cosh(b) - i sin(a)sinh(b)

      var a = this['re'];
      var b = this['im'];

      return new Complex(
        Math.cos(a) * cosh(b),
        -Math.sin(a) * sinh(b));
    },

    /**
     * Calculate the tangent
     *
     * @returns {Complex}
     */
    'tan': function() {

      // tan(z) = sin(z) / cos(z) 
      //        = ( e^iz - e^-iz ) / ( i( e^iz + e^-iz ) )
      //        = ( e^2iz - 1 ) / i( e^2iz + 1 )
      //        = ( sin(2a) + i sinh(2b) ) / ( cos(2a) + cosh(2b) )

      var a = 2 * this['re'];
      var b = 2 * this['im'];
      var d = Math.cos(a) + cosh(b);

      return new Complex(
        Math.sin(a) / d,
        sinh(b) / d);
    },

    /**
     * Calculate the cotangent
     *
     * @returns {Complex}
     */
    'cot': function() {

      // cot(c) = i(e^(ci) + e^(-ci)) / (e^(ci) - e^(-ci))

      var a = 2 * this['re'];
      var b = 2 * this['im'];
      var d = Math.cos(a) - cosh(b);

      return new Complex(
        -Math.sin(a) / d,
        sinh(b) / d);
    },

    /**
     * Calculate the secant
     *
     * @returns {Complex}
     */
    'sec': function() {

      // sec(c) = 2 / (e^(ci) + e^(-ci))

      var a = this['re'];
      var b = this['im'];
      var d = 0.5 * cosh(2 * b) + 0.5 * Math.cos(2 * a);

      return new Complex(
        Math.cos(a) * cosh(b) / d,
        Math.sin(a) * sinh(b) / d);
    },

    /**
     * Calculate the cosecans
     *
     * @returns {Complex}
     */
    'csc': function() {

      // csc(c) = 2i / (e^(ci) - e^(-ci))

      var a = this['re'];
      var b = this['im'];
      var d = 0.5 * cosh(2 * b) - 0.5 * Math.cos(2 * a);

      return new Complex(
        Math.sin(a) * cosh(b) / d,
        -Math.cos(a) * sinh(b) / d);
    },

    /**
     * Calculate the complex arcus sinus
     *
     * @returns {Complex}
     */
    'asin': function() {

      // asin(c) = -i * log(ci + sqrt(1 - c^2))

      var a = this['re'];
      var b = this['im'];

      var t1 = new Complex(
        b * b - a * a + 1,
        -2 * a * b)['sqrt']();

      var t2 = new Complex(
        t1['re'] - b,
        t1['im'] + a)['log']();

      return new Complex(t2['im'], -t2['re']);
    },

    /**
     * Calculate the complex arcus cosinus
     *
     * @returns {Complex}
     */
    'acos': function() {

      // acos(c) = i * log(c - i * sqrt(1 - c^2))

      var a = this['re'];
      var b = this['im'];

      var t1 = new Complex(
        b * b - a * a + 1,
        -2 * a * b)['sqrt']();

      var t2 = new Complex(
        t1['re'] - b,
        t1['im'] + a)['log']();

      return new Complex(Math.PI / 2 - t2['im'], t2['re']);
    },

    /**
     * Calculate the complex arcus tangent
     *
     * @returns {Complex}
     */
    'atan': function() {

      // atan(c) = i / 2 log((i + x) / (i - x))

      var a = this['re'];
      var b = this['im'];

      if (a === 0) {

        if (b === 1) {
          return new Complex(0, Infinity);
        }

        if (b === -1) {
          return new Complex(0, -Infinity);
        }
      }

      var d = a * a + (1.0 - b) * (1.0 - b);

      var t1 = new Complex(
        (1 - b * b - a * a) / d,
        -2 * a / d).log();

      return new Complex(-0.5 * t1['im'], 0.5 * t1['re']);
    },

    /**
     * Calculate the complex arcus cotangent
     *
     * @returns {Complex}
     */
    'acot': function() {

      // acot(c) = i / 2 log((c - i) / (c + i))

      var a = this['re'];
      var b = this['im'];

      if (b === 0) {
        return new Complex(Math.atan2(1, a), 0);
      }

      var d = a * a + b * b;
      return (d !== 0)
        ? new Complex(
          a / d,
          -b / d).atan()
        : new Complex(
          (a !== 0) ? a / 0 : 0,
          (b !== 0) ? -b / 0 : 0).atan();
    },

    /**
     * Calculate the complex arcus secant
     *
     * @returns {Complex}
     */
    'asec': function() {

      // asec(c) = -i * log(1 / c + sqrt(1 - i / c^2))

      var a = this['re'];
      var b = this['im'];

      if (a === 0 && b === 0) {
        return new Complex(0, Infinity);
      }

      var d = a * a + b * b;
      return (d !== 0)
        ? new Complex(
          a / d,
          -b / d).acos()
        : new Complex(
          (a !== 0) ? a / 0 : 0,
          (b !== 0) ? -b / 0 : 0).acos();
    },

    /**
     * Calculate the complex arcus cosecans
     *
     * @returns {Complex}
     */
    'acsc': function() {

      // acsc(c) = -i * log(i / c + sqrt(1 - 1 / c^2))

      var a = this['re'];
      var b = this['im'];

      if (a === 0 && b === 0) {
        return new Complex(Math.PI / 2, Infinity);
      }

      var d = a * a + b * b;
      return (d !== 0)
        ? new Complex(
          a / d,
          -b / d).asin()
        : new Complex(
          (a !== 0) ? a / 0 : 0,
          (b !== 0) ? -b / 0 : 0).asin();
    },

    /**
     * Calculate the complex sinh
     *
     * @returns {Complex}
     */
    'sinh': function() {

      // sinh(c) = (e^c - e^-c) / 2

      var a = this['re'];
      var b = this['im'];

      return new Complex(
        sinh(a) * Math.cos(b),
        cosh(a) * Math.sin(b));
    },

    /**
     * Calculate the complex cosh
     *
     * @returns {Complex}
     */
    'cosh': function() {

      // cosh(c) = (e^c + e^-c) / 2

      var a = this['re'];
      var b = this['im'];

      return new Complex(
        cosh(a) * Math.cos(b),
        sinh(a) * Math.sin(b));
    },

    /**
     * Calculate the complex tanh
     *
     * @returns {Complex}
     */
    'tanh': function() {

      // tanh(c) = (e^c - e^-c) / (e^c + e^-c)

      var a = 2 * this['re'];
      var b = 2 * this['im'];
      var d = cosh(a) + Math.cos(b);

      return new Complex(
        sinh(a) / d,
        Math.sin(b) / d);
    },

    /**
     * Calculate the complex coth
     *
     * @returns {Complex}
     */
    'coth': function() {

      // coth(c) = (e^c + e^-c) / (e^c - e^-c)

      var a = 2 * this['re'];
      var b = 2 * this['im'];
      var d = cosh(a) - Math.cos(b);

      return new Complex(
        sinh(a) / d,
        -Math.sin(b) / d);
    },

    /**
     * Calculate the complex coth
     *
     * @returns {Complex}
     */
    'csch': function() {

      // csch(c) = 2 / (e^c - e^-c)

      var a = this['re'];
      var b = this['im'];
      var d = Math.cos(2 * b) - cosh(2 * a);

      return new Complex(
        -2 * sinh(a) * Math.cos(b) / d,
        2 * cosh(a) * Math.sin(b) / d);
    },

    /**
     * Calculate the complex sech
     *
     * @returns {Complex}
     */
    'sech': function() {

      // sech(c) = 2 / (e^c + e^-c)

      var a = this['re'];
      var b = this['im'];
      var d = Math.cos(2 * b) + cosh(2 * a);

      return new Complex(
        2 * cosh(a) * Math.cos(b) / d,
        -2 * sinh(a) * Math.sin(b) / d);
    },

    /**
     * Calculate the complex asinh
     *
     * @returns {Complex}
     */
    'asinh': function() {

      // asinh(c) = log(c + sqrt(c^2 + 1))

      var tmp = this['im'];
      this['im'] = -this['re'];
      this['re'] = tmp;
      var res = this['asin']();

      this['re'] = -this['im'];
      this['im'] = tmp;
      tmp = res['re'];

      res['re'] = -res['im'];
      res['im'] = tmp;
      return res;
    },

    /**
     * Calculate the complex acosh
     *
     * @returns {Complex}
     */
    'acosh': function() {

      // acosh(c) = log(c + sqrt(c^2 - 1))

      var res = this['acos']();
      if (res['im'] <= 0) {
        var tmp = res['re'];
        res['re'] = -res['im'];
        res['im'] = tmp;
      } else {
        var tmp = res['im'];
        res['im'] = -res['re'];
        res['re'] = tmp;
      }
      return res;
    },

    /**
     * Calculate the complex atanh
     *
     * @returns {Complex}
     */
    'atanh': function() {

      // atanh(c) = log((1+c) / (1-c)) / 2

      var a = this['re'];
      var b = this['im'];

      var noIM = a > 1 && b === 0;
      var oneMinus = 1 - a;
      var onePlus = 1 + a;
      var d = oneMinus * oneMinus + b * b;

      var x = (d !== 0)
        ? new Complex(
          (onePlus * oneMinus - b * b) / d,
          (b * oneMinus + onePlus * b) / d)
        : new Complex(
          (a !== -1) ? (a / 0) : 0,
          (b !== 0) ? (b / 0) : 0);

      var temp = x['re'];
      x['re'] = logHypot(x['re'], x['im']) / 2;
      x['im'] = Math.atan2(x['im'], temp) / 2;
      if (noIM) {
        x['im'] = -x['im'];
      }
      return x;
    },

    /**
     * Calculate the complex acoth
     *
     * @returns {Complex}
     */
    'acoth': function() {

      // acoth(c) = log((c+1) / (c-1)) / 2

      var a = this['re'];
      var b = this['im'];

      if (a === 0 && b === 0) {
        return new Complex(0, Math.PI / 2);
      }

      var d = a * a + b * b;
      return (d !== 0)
        ? new Complex(
          a / d,
          -b / d).atanh()
        : new Complex(
          (a !== 0) ? a / 0 : 0,
          (b !== 0) ? -b / 0 : 0).atanh();
    },

    /**
     * Calculate the complex acsch
     *
     * @returns {Complex}
     */
    'acsch': function() {

      // acsch(c) = log((1+sqrt(1+c^2))/c)

      var a = this['re'];
      var b = this['im'];

      if (b === 0) {

        return new Complex(
          (a !== 0)
            ? Math.log(a + Math.sqrt(a * a + 1))
            : Infinity, 0);
      }

      var d = a * a + b * b;
      return (d !== 0)
        ? new Complex(
          a / d,
          -b / d).asinh()
        : new Complex(
          (a !== 0) ? a / 0 : 0,
          (b !== 0) ? -b / 0 : 0).asinh();
    },

    /**
     * Calculate the complex asech
     *
     * @returns {Complex}
     */
    'asech': function() {

      // asech(c) = log((1+sqrt(1-c^2))/c)

      var a = this['re'];
      var b = this['im'];

      if (this['isZero']()) {
        return Complex['INFINITY'];
      }

      var d = a * a + b * b;
      return (d !== 0)
        ? new Complex(
          a / d,
          -b / d).acosh()
        : new Complex(
          (a !== 0) ? a / 0 : 0,
          (b !== 0) ? -b / 0 : 0).acosh();
    },

    /**
     * Calculate the complex inverse 1/z
     *
     * @returns {Complex}
     */
    'inverse': function() {

      // 1 / 0 = Infinity and 1 / Infinity = 0
      if (this['isZero']()) {
        return Complex['INFINITY'];
      }

      if (this['isInfinite']()) {
        return Complex['ZERO'];
      }

      var a = this['re'];
      var b = this['im'];

      var d = a * a + b * b;

      return new Complex(a / d, -b / d);
    },

    /**
     * Returns the complex conjugate
     *
     * @returns {Complex}
     */
    'conjugate': function() {

      return new Complex(this['re'], -this['im']);
    },

    /**
     * Gets the negated complex number
     *
     * @returns {Complex}
     */
    'neg': function() {

      return new Complex(-this['re'], -this['im']);
    },

    /**
     * Ceils the actual complex number
     *
     * @returns {Complex}
     */
    'ceil': function(places) {

      places = Math.pow(10, places || 0);

      return new Complex(
        Math.ceil(this['re'] * places) / places,
        Math.ceil(this['im'] * places) / places);
    },

    /**
     * Floors the actual complex number
     *
     * @returns {Complex}
     */
    'floor': function(places) {

      places = Math.pow(10, places || 0);

      return new Complex(
        Math.floor(this['re'] * places) / places,
        Math.floor(this['im'] * places) / places);
    },

    /**
     * Ceils the actual complex number
     *
     * @returns {Complex}
     */
    'round': function(places) {

      places = Math.pow(10, places || 0);

      return new Complex(
        Math.round(this['re'] * places) / places,
        Math.round(this['im'] * places) / places);
    },

    /**
     * Compares two complex numbers
     *
     * **Note:** new Complex(Infinity).equals(Infinity) === false
     *
     * @returns {boolean}
     */
    'equals': function(a, b) {

      var z = new Complex(a, b);

      return Math.abs(z['re'] - this['re']) <= Complex['EPSILON'] &&
        Math.abs(z['im'] - this['im']) <= Complex['EPSILON'];
    },

    /**
     * Clones the actual object
     *
     * @returns {Complex}
     */
    'clone': function() {

      return new Complex(this['re'], this['im']);
    },

    /**
     * Gets a string of the actual complex number
     *
     * @returns {string}
     */
    'toString': function() {

      var a = this['re'];
      var b = this['im'];
      var ret = "";

      if (this['isNaN']()) {
        return 'NaN';
      }

      if (this['isInfinite']()) {
        return 'Infinity';
      }

      if (Math.abs(a) < Complex['EPSILON']) {
        a = 0;
      }

      if (Math.abs(b) < Complex['EPSILON']) {
        b = 0;
      }

      // If is real number
      if (b === 0) {
        return ret + a;
      }

      if (a !== 0) {
        ret += a;
        ret += " ";
        if (b < 0) {
          b = -b;
          ret += "-";
        } else {
          ret += "+";
        }
        ret += " ";
      } else if (b < 0) {
        b = -b;
        ret += "-";
      }

      if (1 !== b) { // b is the absolute imaginary part
        ret += b;
      }
      return ret + "i";
    },

    /**
     * Returns the actual number as a vector
     *
     * @returns {Array}
     */
    'toVector': function() {

      return [this['re'], this['im']];
    },

    /**
     * Returns the actual real value of the current object
     *
     * @returns {number|null}
     */
    'valueOf': function() {

      if (this['im'] === 0) {
        return this['re'];
      }
      return null;
    },

    /**
     * Determines whether a complex number is not on the Riemann sphere.
     *
     * @returns {boolean}
     */
    'isNaN': function() {
      return isNaN(this['re']) || isNaN(this['im']);
    },

    /**
     * Determines whether or not a complex number is at the zero pole of the
     * Riemann sphere.
     *
     * @returns {boolean}
     */
    'isZero': function() {
      return this['im'] === 0 && this['re'] === 0;
    },

    /**
     * Determines whether a complex number is not at the infinity pole of the
     * Riemann sphere.
     *
     * @returns {boolean}
     */
    'isFinite': function() {
      return isFinite(this['re']) && isFinite(this['im']);
    },

    /**
     * Determines whether or not a complex number is at the infinity pole of the
     * Riemann sphere.
     *
     * @returns {boolean}
     */
    'isInfinite': function() {
      return !(this['isNaN']() || this['isFinite']());
    }
  };

  Complex['ZERO'] = new Complex(0, 0);
  Complex['ONE'] = new Complex(1, 0);
  Complex['I'] = new Complex(0, 1);
  Complex['PI'] = new Complex(Math.PI, 0);
  Complex['E'] = new Complex(Math.E, 0);
  Complex['INFINITY'] = new Complex(Infinity, Infinity);
  Complex['NAN'] = new Complex(NaN, NaN);
  Complex['EPSILON'] = 1e-15;

  {
    Object.defineProperty(Complex, "__esModule", { 'value': true });
    Complex['default'] = Complex;
    Complex['Complex'] = Complex;
    module['exports'] = Complex;
  }

})();
}(complex));

var Complex = /*@__PURE__*/getDefaultExportFromCjs(complex.exports);

var name$4T = 'Complex';
var dependencies$4S = [];
var createComplexClass = /* #__PURE__ */factory(name$4T, dependencies$4S, () => {
  /**
   * Attach type information
   */
  Object.defineProperty(Complex, 'name', {
    value: 'Complex'
  });
  Complex.prototype.constructor = Complex;
  Complex.prototype.type = 'Complex';
  Complex.prototype.isComplex = true;

  /**
   * Get a JSON representation of the complex number
   * @returns {Object} Returns a JSON object structured as:
   *                   `{"mathjs": "Complex", "re": 2, "im": 3}`
   */
  Complex.prototype.toJSON = function () {
    return {
      mathjs: 'Complex',
      re: this.re,
      im: this.im
    };
  };

  /*
   * Return the value of the complex number in polar notation
   * The angle phi will be set in the interval of [-pi, pi].
   * @return {{r: number, phi: number}} Returns and object with properties r and phi.
   */
  Complex.prototype.toPolar = function () {
    return {
      r: this.abs(),
      phi: this.arg()
    };
  };

  /**
   * Get a string representation of the complex number,
   * with optional formatting options.
   * @param {Object | number | Function} [options]  Formatting options. See
   *                                                lib/utils/number:format for a
   *                                                description of the available
   *                                                options.
   * @return {string} str
   */
  Complex.prototype.format = function (options) {
    var str = '';
    var im = this.im;
    var re = this.re;
    var strRe = format$2(this.re, options);
    var strIm = format$2(this.im, options);

    // round either re or im when smaller than the configured precision
    var precision = isNumber(options) ? options : options ? options.precision : null;
    if (precision !== null) {
      var epsilon = Math.pow(10, -precision);
      if (Math.abs(re / im) < epsilon) {
        re = 0;
      }
      if (Math.abs(im / re) < epsilon) {
        im = 0;
      }
    }
    if (im === 0) {
      // real value
      str = strRe;
    } else if (re === 0) {
      // purely complex value
      if (im === 1) {
        str = 'i';
      } else if (im === -1) {
        str = '-i';
      } else {
        str = strIm + 'i';
      }
    } else {
      // complex value
      if (im < 0) {
        if (im === -1) {
          str = strRe + ' - i';
        } else {
          str = strRe + ' - ' + strIm.substring(1) + 'i';
        }
      } else {
        if (im === 1) {
          str = strRe + ' + i';
        } else {
          str = strRe + ' + ' + strIm + 'i';
        }
      }
    }
    return str;
  };

  /**
   * Create a complex number from polar coordinates
   *
   * Usage:
   *
   *     Complex.fromPolar(r: number, phi: number) : Complex
   *     Complex.fromPolar({r: number, phi: number}) : Complex
   *
   * @param {*} args...
   * @return {Complex}
   */
  Complex.fromPolar = function (args) {
    switch (arguments.length) {
      case 1:
        {
          var arg = arguments[0];
          if (typeof arg === 'object') {
            return Complex(arg);
          } else {
            throw new TypeError('Input has to be an object with r and phi keys.');
          }
        }
      case 2:
        {
          var r = arguments[0];
          var phi = arguments[1];
          if (isNumber(r)) {
            if (isUnit(phi) && phi.hasBase('ANGLE')) {
              // convert unit to a number in radians
              phi = phi.toNumber('rad');
            }
            if (isNumber(phi)) {
              return new Complex({
                r,
                phi
              });
            }
            throw new TypeError('Phi is not a number nor an angle unit.');
          } else {
            throw new TypeError('Radius r is not a number.');
          }
        }
      default:
        throw new SyntaxError('Wrong number of arguments in function fromPolar');
    }
  };
  Complex.prototype.valueOf = Complex.prototype.toString;

  /**
   * Create a Complex number from a JSON object
   * @param {Object} json  A JSON Object structured as
   *                       {"mathjs": "Complex", "re": 2, "im": 3}
   *                       All properties are optional, default values
   *                       for `re` and `im` are 0.
   * @return {Complex} Returns a new Complex number
   */
  Complex.fromJSON = function (json) {
    return new Complex(json);
  };

  /**
   * Compare two complex numbers, `a` and `b`:
   *
   * - Returns 1 when the real part of `a` is larger than the real part of `b`
   * - Returns -1 when the real part of `a` is smaller than the real part of `b`
   * - Returns 1 when the real parts are equal
   *   and the imaginary part of `a` is larger than the imaginary part of `b`
   * - Returns -1 when the real parts are equal
   *   and the imaginary part of `a` is smaller than the imaginary part of `b`
   * - Returns 0 when both real and imaginary parts are equal.
   *
   * @params {Complex} a
   * @params {Complex} b
   * @returns {number} Returns the comparison result: -1, 0, or 1
   */
  Complex.compare = function (a, b) {
    if (a.re > b.re) {
      return 1;
    }
    if (a.re < b.re) {
      return -1;
    }
    if (a.im > b.im) {
      return 1;
    }
    if (a.im < b.im) {
      return -1;
    }
    return 0;
  };
  return Complex;
}, {
  isClass: true
});

/**
 * @license Fraction.js v4.3.7 31/08/2023
 * https://www.xarg.org/2014/03/rational-numbers-in-javascript/
 *
 * Copyright (c) 2023, Robert Eisele (robert@raw.org)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 **/


/**
 *
 * This class offers the possibility to calculate fractions.
 * You can pass a fraction in different formats. Either as array, as double, as string or as an integer.
 *
 * Array/Object form
 * [ 0 => <numerator>, 1 => <denominator> ]
 * [ n => <numerator>, d => <denominator> ]
 *
 * Integer form
 * - Single integer value
 *
 * Double form
 * - Single double value
 *
 * String form
 * 123.456 - a simple double
 * 123/456 - a string fraction
 * 123.'456' - a double with repeating decimal places
 * 123.(456) - synonym
 * 123.45'6' - a double with repeating last place
 * 123.45(6) - synonym
 *
 * Example:
 *
 * var f = new Fraction("9.4'31'");
 * f.mul([-4, 3]).div(4.9);
 *
 */


// Maximum search depth for cyclic rational numbers. 2000 should be more than enough.
// Example: 1/7 = 0.(142857) has 6 repeating decimal places.
// If MAX_CYCLE_LEN gets reduced, long cycles will not be detected and toString() only gets the first 10 digits
var MAX_CYCLE_LEN = 2000;

// Parsed data to avoid calling "new" all the time
var P$1 = {
  "s": 1,
  "n": 0,
  "d": 1
};

function assign(n, s) {

  if (isNaN(n = parseInt(n, 10))) {
    throw InvalidParameter();
  }
  return n * s;
}

// Creates a new Fraction internally without the need of the bulky constructor
function newFraction(n, d) {

  if (d === 0) {
    throw DivisionByZero();
  }

  var f = Object.create(Fraction.prototype);
  f["s"] = n < 0 ? -1 : 1;

  n = n < 0 ? -n : n;

  var a = gcd(n, d);

  f["n"] = n / a;
  f["d"] = d / a;
  return f;
}

function factorize(num) {

  var factors = {};

  var n = num;
  var i = 2;
  var s = 4;

  while (s <= n) {

    while (n % i === 0) {
      n/= i;
      factors[i] = (factors[i] || 0) + 1;
    }
    s+= 1 + 2 * i++;
  }

  if (n !== num) {
    if (n > 1)
      factors[n] = (factors[n] || 0) + 1;
  } else {
    factors[num] = (factors[num] || 0) + 1;
  }
  return factors;
}

var parse = function(p1, p2) {

  var n = 0, d = 1, s = 1;
  var v = 0, w = 0, x = 0, y = 1, z = 1;

  var A = 0, B = 1;
  var C = 1, D = 1;

  var N = 10000000;
  var M;

  if (p1 === undefined || p1 === null) ; else if (p2 !== undefined) {
    n = p1;
    d = p2;
    s = n * d;

    if (n % 1 !== 0 || d % 1 !== 0) {
      throw NonIntegerParameter();
    }

  } else
    switch (typeof p1) {

      case "object":
        {
          if ("d" in p1 && "n" in p1) {
            n = p1["n"];
            d = p1["d"];
            if ("s" in p1)
              n*= p1["s"];
          } else if (0 in p1) {
            n = p1[0];
            if (1 in p1)
              d = p1[1];
          } else {
            throw InvalidParameter();
          }
          s = n * d;
          break;
        }
      case "number":
        {
          if (p1 < 0) {
            s = p1;
            p1 = -p1;
          }

          if (p1 % 1 === 0) {
            n = p1;
          } else if (p1 > 0) { // check for != 0, scale would become NaN (log(0)), which converges really slow

            if (p1 >= 1) {
              z = Math.pow(10, Math.floor(1 + Math.log(p1) / Math.LN10));
              p1/= z;
            }

            // Using Farey Sequences
            // http://www.johndcook.com/blog/2010/10/20/best-rational-approximation/

            while (B <= N && D <= N) {
              M = (A + C) / (B + D);

              if (p1 === M) {
                if (B + D <= N) {
                  n = A + C;
                  d = B + D;
                } else if (D > B) {
                  n = C;
                  d = D;
                } else {
                  n = A;
                  d = B;
                }
                break;

              } else {

                if (p1 > M) {
                  A+= C;
                  B+= D;
                } else {
                  C+= A;
                  D+= B;
                }

                if (B > N) {
                  n = C;
                  d = D;
                } else {
                  n = A;
                  d = B;
                }
              }
            }
            n*= z;
          } else if (isNaN(p1) || isNaN(p2)) {
            d = n = NaN;
          }
          break;
        }
      case "string":
        {
          B = p1.match(/\d+|./g);

          if (B === null)
            throw InvalidParameter();

          if (B[A] === '-') {// Check for minus sign at the beginning
            s = -1;
            A++;
          } else if (B[A] === '+') {// Check for plus sign at the beginning
            A++;
          }

          if (B.length === A + 1) { // Check if it's just a simple number "1234"
            w = assign(B[A++], s);
          } else if (B[A + 1] === '.' || B[A] === '.') { // Check if it's a decimal number

            if (B[A] !== '.') { // Handle 0.5 and .5
              v = assign(B[A++], s);
            }
            A++;

            // Check for decimal places
            if (A + 1 === B.length || B[A + 1] === '(' && B[A + 3] === ')' || B[A + 1] === "'" && B[A + 3] === "'") {
              w = assign(B[A], s);
              y = Math.pow(10, B[A].length);
              A++;
            }

            // Check for repeating places
            if (B[A] === '(' && B[A + 2] === ')' || B[A] === "'" && B[A + 2] === "'") {
              x = assign(B[A + 1], s);
              z = Math.pow(10, B[A + 1].length) - 1;
              A+= 3;
            }

          } else if (B[A + 1] === '/' || B[A + 1] === ':') { // Check for a simple fraction "123/456" or "123:456"
            w = assign(B[A], s);
            y = assign(B[A + 2], 1);
            A+= 3;
          } else if (B[A + 3] === '/' && B[A + 1] === ' ') { // Check for a complex fraction "123 1/2"
            v = assign(B[A], s);
            w = assign(B[A + 2], s);
            y = assign(B[A + 4], 1);
            A+= 5;
          }

          if (B.length <= A) { // Check for more tokens on the stack
            d = y * z;
            s = /* void */
            n = x + d * v + z * w;
            break;
          }

          /* Fall through on error */
        }
      default:
        throw InvalidParameter();
    }

  if (d === 0) {
    throw DivisionByZero();
  }

  P$1["s"] = s < 0 ? -1 : 1;
  P$1["n"] = Math.abs(n);
  P$1["d"] = Math.abs(d);
};

function modpow(b, e, m) {

  var r = 1;
  for (; e > 0; b = (b * b) % m, e >>= 1) {

    if (e & 1) {
      r = (r * b) % m;
    }
  }
  return r;
}


function cycleLen(n, d) {

  for (; d % 2 === 0;
    d/= 2) {
  }

  for (; d % 5 === 0;
    d/= 5) {
  }

  if (d === 1) // Catch non-cyclic numbers
    return 0;

  // If we would like to compute really large numbers quicker, we could make use of Fermat's little theorem:
  // 10^(d-1) % d == 1
  // However, we don't need such large numbers and MAX_CYCLE_LEN should be the capstone,
  // as we want to translate the numbers to strings.

  var rem = 10 % d;
  var t = 1;

  for (; rem !== 1; t++) {
    rem = rem * 10 % d;

    if (t > MAX_CYCLE_LEN)
      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`
  }
  return t;
}


function cycleStart(n, d, len) {

  var rem1 = 1;
  var rem2 = modpow(10, len, d);

  for (var t = 0; t < 300; t++) { // s < ~log10(Number.MAX_VALUE)
    // Solve 10^s == 10^(s+t) (mod d)

    if (rem1 === rem2)
      return t;

    rem1 = rem1 * 10 % d;
    rem2 = rem2 * 10 % d;
  }
  return 0;
}

function gcd(a, b) {

  if (!a)
    return b;
  if (!b)
    return a;

  while (1) {
    a%= b;
    if (!a)
      return b;
    b%= a;
    if (!b)
      return a;
  }
}
/**
 * Module constructor
 *
 * @constructor
 * @param {number|Fraction=} a
 * @param {number=} b
 */
function Fraction(a, b) {

  parse(a, b);

  if (this instanceof Fraction) {
    a = gcd(P$1["d"], P$1["n"]); // Abuse variable a
    this["s"] = P$1["s"];
    this["n"] = P$1["n"] / a;
    this["d"] = P$1["d"] / a;
  } else {
    return newFraction(P$1['s'] * P$1['n'], P$1['d']);
  }
}

var DivisionByZero = function() { return new Error("Division by Zero"); };
var InvalidParameter = function() { return new Error("Invalid argument"); };
var NonIntegerParameter = function() { return new Error("Parameters must be integer"); };

Fraction.prototype = {

  "s": 1,
  "n": 0,
  "d": 1,

  /**
   * Calculates the absolute value
   *
   * Ex: new Fraction(-4).abs() => 4
   **/
  "abs": function() {

    return newFraction(this["n"], this["d"]);
  },

  /**
   * Inverts the sign of the current fraction
   *
   * Ex: new Fraction(-4).neg() => 4
   **/
  "neg": function() {

    return newFraction(-this["s"] * this["n"], this["d"]);
  },

  /**
   * Adds two rational numbers
   *
   * Ex: new Fraction({n: 2, d: 3}).add("14.9") => 467 / 30
   **/
  "add": function(a, b) {

    parse(a, b);
    return newFraction(
      this["s"] * this["n"] * P$1["d"] + P$1["s"] * this["d"] * P$1["n"],
      this["d"] * P$1["d"]
    );
  },

  /**
   * Subtracts two rational numbers
   *
   * Ex: new Fraction({n: 2, d: 3}).add("14.9") => -427 / 30
   **/
  "sub": function(a, b) {

    parse(a, b);
    return newFraction(
      this["s"] * this["n"] * P$1["d"] - P$1["s"] * this["d"] * P$1["n"],
      this["d"] * P$1["d"]
    );
  },

  /**
   * Multiplies two rational numbers
   *
   * Ex: new Fraction("-17.(345)").mul(3) => 5776 / 111
   **/
  "mul": function(a, b) {

    parse(a, b);
    return newFraction(
      this["s"] * P$1["s"] * this["n"] * P$1["n"],
      this["d"] * P$1["d"]
    );
  },

  /**
   * Divides two rational numbers
   *
   * Ex: new Fraction("-17.(345)").inverse().div(3)
   **/
  "div": function(a, b) {

    parse(a, b);
    return newFraction(
      this["s"] * P$1["s"] * this["n"] * P$1["d"],
      this["d"] * P$1["n"]
    );
  },

  /**
   * Clones the actual object
   *
   * Ex: new Fraction("-17.(345)").clone()
   **/
  "clone": function() {
    return newFraction(this['s'] * this['n'], this['d']);
  },

  /**
   * Calculates the modulo of two rational numbers - a more precise fmod
   *
   * Ex: new Fraction('4.(3)').mod([7, 8]) => (13/3) % (7/8) = (5/6)
   **/
  "mod": function(a, b) {

    if (isNaN(this['n']) || isNaN(this['d'])) {
      return new Fraction(NaN);
    }

    if (a === undefined) {
      return newFraction(this["s"] * this["n"] % this["d"], 1);
    }

    parse(a, b);
    if (0 === P$1["n"] && 0 === this["d"]) {
      throw DivisionByZero();
    }

    /*
     * First silly attempt, kinda slow
     *
     return that["sub"]({
     "n": num["n"] * Math.floor((this.n / this.d) / (num.n / num.d)),
     "d": num["d"],
     "s": this["s"]
     });*/

    /*
     * New attempt: a1 / b1 = a2 / b2 * q + r
     * => b2 * a1 = a2 * b1 * q + b1 * b2 * r
     * => (b2 * a1 % a2 * b1) / (b1 * b2)
     */
    return newFraction(
      this["s"] * (P$1["d"] * this["n"]) % (P$1["n"] * this["d"]),
      P$1["d"] * this["d"]
    );
  },

  /**
   * Calculates the fractional gcd of two rational numbers
   *
   * Ex: new Fraction(5,8).gcd(3,7) => 1/56
   */
  "gcd": function(a, b) {

    parse(a, b);

    // gcd(a / b, c / d) = gcd(a, c) / lcm(b, d)

    return newFraction(gcd(P$1["n"], this["n"]) * gcd(P$1["d"], this["d"]), P$1["d"] * this["d"]);
  },

  /**
   * Calculates the fractional lcm of two rational numbers
   *
   * Ex: new Fraction(5,8).lcm(3,7) => 15
   */
  "lcm": function(a, b) {

    parse(a, b);

    // lcm(a / b, c / d) = lcm(a, c) / gcd(b, d)

    if (P$1["n"] === 0 && this["n"] === 0) {
      return newFraction(0, 1);
    }
    return newFraction(P$1["n"] * this["n"], gcd(P$1["n"], this["n"]) * gcd(P$1["d"], this["d"]));
  },

  /**
   * Calculates the ceil of a rational number
   *
   * Ex: new Fraction('4.(3)').ceil() => (5 / 1)
   **/
  "ceil": function(places) {

    places = Math.pow(10, places || 0);

    if (isNaN(this["n"]) || isNaN(this["d"])) {
      return new Fraction(NaN);
    }
    return newFraction(Math.ceil(places * this["s"] * this["n"] / this["d"]), places);
  },

  /**
   * Calculates the floor of a rational number
   *
   * Ex: new Fraction('4.(3)').floor() => (4 / 1)
   **/
  "floor": function(places) {

    places = Math.pow(10, places || 0);

    if (isNaN(this["n"]) || isNaN(this["d"])) {
      return new Fraction(NaN);
    }
    return newFraction(Math.floor(places * this["s"] * this["n"] / this["d"]), places);
  },

  /**
   * Rounds a rational number
   *
   * Ex: new Fraction('4.(3)').round() => (4 / 1)
   **/
  "round": function(places) {

    places = Math.pow(10, places || 0);

    if (isNaN(this["n"]) || isNaN(this["d"])) {
      return new Fraction(NaN);
    }
    return newFraction(Math.round(places * this["s"] * this["n"] / this["d"]), places);
  },

  /**
   * Rounds a rational number to a multiple of another rational number
   *
   * Ex: new Fraction('0.9').roundTo("1/8") => 7 / 8
   **/
  "roundTo": function(a, b) {

    /*
    k * x/y ≤ a/b < (k+1) * x/y
    ⇔ k ≤ a/b / (x/y) < (k+1)
    ⇔ k = floor(a/b * y/x)
    */

    parse(a, b);

    return newFraction(this['s'] * Math.round(this['n'] * P$1['d'] / (this['d'] * P$1['n'])) * P$1['n'], P$1['d']);
  },

  /**
   * Gets the inverse of the fraction, means numerator and denominator are exchanged
   *
   * Ex: new Fraction([-3, 4]).inverse() => -4 / 3
   **/
  "inverse": function() {

    return newFraction(this["s"] * this["d"], this["n"]);
  },

  /**
   * Calculates the fraction to some rational exponent, if possible
   *
   * Ex: new Fraction(-1,2).pow(-3) => -8
   */
  "pow": function(a, b) {

    parse(a, b);

    // Trivial case when exp is an integer

    if (P$1['d'] === 1) {

      if (P$1['s'] < 0) {
        return newFraction(Math.pow(this['s'] * this["d"], P$1['n']), Math.pow(this["n"], P$1['n']));
      } else {
        return newFraction(Math.pow(this['s'] * this["n"], P$1['n']), Math.pow(this["d"], P$1['n']));
      }
    }

    // Negative roots become complex
    //     (-a/b)^(c/d) = x
    // <=> (-1)^(c/d) * (a/b)^(c/d) = x
    // <=> (cos(pi) + i*sin(pi))^(c/d) * (a/b)^(c/d) = x         # rotate 1 by 180°
    // <=> (cos(c*pi/d) + i*sin(c*pi/d)) * (a/b)^(c/d) = x       # DeMoivre's formula in Q ( https://proofwiki.org/wiki/De_Moivre%27s_Formula/Rational_Index )
    // From which follows that only for c=0 the root is non-complex. c/d is a reduced fraction, so that sin(c/dpi)=0 occurs for d=1, which is handled by our trivial case.
    if (this['s'] < 0) return null;

    // Now prime factor n and d
    var N = factorize(this['n']);
    var D = factorize(this['d']);

    // Exponentiate and take root for n and d individually
    var n = 1;
    var d = 1;
    for (var k in N) {
      if (k === '1') continue;
      if (k === '0') {
        n = 0;
        break;
      }
      N[k]*= P$1['n'];

      if (N[k] % P$1['d'] === 0) {
        N[k]/= P$1['d'];
      } else return null;
      n*= Math.pow(k, N[k]);
    }

    for (var k in D) {
      if (k === '1') continue;
      D[k]*= P$1['n'];

      if (D[k] % P$1['d'] === 0) {
        D[k]/= P$1['d'];
      } else return null;
      d*= Math.pow(k, D[k]);
    }

    if (P$1['s'] < 0) {
      return newFraction(d, n);
    }
    return newFraction(n, d);
  },

  /**
   * Check if two rational numbers are the same
   *
   * Ex: new Fraction(19.6).equals([98, 5]);
   **/
  "equals": function(a, b) {

    parse(a, b);
    return this["s"] * this["n"] * P$1["d"] === P$1["s"] * P$1["n"] * this["d"]; // Same as compare() === 0
  },

  /**
   * Check if two rational numbers are the same
   *
   * Ex: new Fraction(19.6).equals([98, 5]);
   **/
  "compare": function(a, b) {

    parse(a, b);
    var t = (this["s"] * this["n"] * P$1["d"] - P$1["s"] * P$1["n"] * this["d"]);
    return (0 < t) - (t < 0);
  },

  "simplify": function(eps) {

    if (isNaN(this['n']) || isNaN(this['d'])) {
      return this;
    }

    eps = eps || 0.001;

    var thisABS = this['abs']();
    var cont = thisABS['toContinued']();

    for (var i = 1; i < cont.length; i++) {

      var s = newFraction(cont[i - 1], 1);
      for (var k = i - 2; k >= 0; k--) {
        s = s['inverse']()['add'](cont[k]);
      }

      if (Math.abs(s['sub'](thisABS).valueOf()) < eps) {
        return s['mul'](this['s']);
      }
    }
    return this;
  },

  /**
   * Check if two rational numbers are divisible
   *
   * Ex: new Fraction(19.6).divisible(1.5);
   */
  "divisible": function(a, b) {

    parse(a, b);
    return !(!(P$1["n"] * this["d"]) || ((this["n"] * P$1["d"]) % (P$1["n"] * this["d"])));
  },

  /**
   * Returns a decimal representation of the fraction
   *
   * Ex: new Fraction("100.'91823'").valueOf() => 100.91823918239183
   **/
  'valueOf': function() {

    return this["s"] * this["n"] / this["d"];
  },

  /**
   * Returns a string-fraction representation of a Fraction object
   *
   * Ex: new Fraction("1.'3'").toFraction(true) => "4 1/3"
   **/
  'toFraction': function(excludeWhole) {

    var whole, str = "";
    var n = this["n"];
    var d = this["d"];
    if (this["s"] < 0) {
      str+= '-';
    }

    if (d === 1) {
      str+= n;
    } else {

      if (excludeWhole && (whole = Math.floor(n / d)) > 0) {
        str+= whole;
        str+= " ";
        n%= d;
      }

      str+= n;
      str+= '/';
      str+= d;
    }
    return str;
  },

  /**
   * Returns a latex representation of a Fraction object
   *
   * Ex: new Fraction("1.'3'").toLatex() => "\frac{4}{3}"
   **/
  'toLatex': function(excludeWhole) {

    var whole, str = "";
    var n = this["n"];
    var d = this["d"];
    if (this["s"] < 0) {
      str+= '-';
    }

    if (d === 1) {
      str+= n;
    } else {

      if (excludeWhole && (whole = Math.floor(n / d)) > 0) {
        str+= whole;
        n%= d;
      }

      str+= "\\frac{";
      str+= n;
      str+= '}{';
      str+= d;
      str+= '}';
    }
    return str;
  },

  /**
   * Returns an array of continued fraction elements
   *
   * Ex: new Fraction("7/8").toContinued() => [0,1,7]
   */
  'toContinued': function() {

    var t;
    var a = this['n'];
    var b = this['d'];
    var res = [];

    if (isNaN(a) || isNaN(b)) {
      return res;
    }

    do {
      res.push(Math.floor(a / b));
      t = a % b;
      a = b;
      b = t;
    } while (a !== 1);

    return res;
  },

  /**
   * Creates a string representation of a fraction with all digits
   *
   * Ex: new Fraction("100.'91823'").toString() => "100.(91823)"
   **/
  'toString': function(dec) {

    var N = this["n"];
    var D = this["d"];

    if (isNaN(N) || isNaN(D)) {
      return "NaN";
    }

    dec = dec || 15; // 15 = decimal places when no repetation

    var cycLen = cycleLen(N, D); // Cycle length
    var cycOff = cycleStart(N, D, cycLen); // Cycle start

    var str = this['s'] < 0 ? "-" : "";

    str+= N / D | 0;

    N%= D;
    N*= 10;

    if (N)
      str+= ".";

    if (cycLen) {

      for (var i = cycOff; i--;) {
        str+= N / D | 0;
        N%= D;
        N*= 10;
      }
      str+= "(";
      for (var i = cycLen; i--;) {
        str+= N / D | 0;
        N%= D;
        N*= 10;
      }
      str+= ")";
    } else {
      for (var i = dec; N && i--;) {
        str+= N / D | 0;
        N%= D;
        N*= 10;
      }
    }
    return str;
  }
};

var name$4S = 'Fraction';
var dependencies$4R = [];
var createFractionClass = /* #__PURE__ */factory(name$4S, dependencies$4R, () => {
  /**
   * Attach type information
   */
  Object.defineProperty(Fraction, 'name', {
    value: 'Fraction'
  });
  Fraction.prototype.constructor = Fraction;
  Fraction.prototype.type = 'Fraction';
  Fraction.prototype.isFraction = true;

  /**
   * Get a JSON representation of a Fraction containing type information
   * @returns {Object} Returns a JSON object structured as:
   *                   `{"mathjs": "Fraction", "n": 3, "d": 8}`
   */
  Fraction.prototype.toJSON = function () {
    return {
      mathjs: 'Fraction',
      n: this.s * this.n,
      d: this.d
    };
  };

  /**
   * Instantiate a Fraction from a JSON object
   * @param {Object} json  a JSON object structured as:
   *                       `{"mathjs": "Fraction", "n": 3, "d": 8}`
   * @return {BigNumber}
   */
  Fraction.fromJSON = function (json) {
    return new Fraction(json);
  };
  return Fraction;
}, {
  isClass: true
});

var name$4R = 'Range';
var dependencies$4Q = [];
var createRangeClass = /* #__PURE__ */factory(name$4R, dependencies$4Q, () => {
  /**
   * Create a range. A range has a start, step, and end, and contains functions
   * to iterate over the range.
   *
   * A range can be constructed as:
   *
   *     const range = new Range(start, end)
   *     const range = new Range(start, end, step)
   *
   * To get the result of the range:
   *     range.forEach(function (x) {
   *         console.log(x)
   *     })
   *     range.map(function (x) {
   *         return math.sin(x)
   *     })
   *     range.toArray()
   *
   * Example usage:
   *
   *     const c = new Range(2, 6)       // 2:1:5
   *     c.toArray()                     // [2, 3, 4, 5]
   *     const d = new Range(2, -3, -1)  // 2:-1:-2
   *     d.toArray()                     // [2, 1, 0, -1, -2]
   *
   * @class Range
   * @constructor Range
   * @param {number} start  included lower bound
   * @param {number} end    excluded upper bound
   * @param {number} [step] step size, default value is 1
   */
  function Range(start, end, step) {
    if (!(this instanceof Range)) {
      throw new SyntaxError('Constructor must be called with the new operator');
    }
    var hasStart = start !== null && start !== undefined;
    var hasEnd = end !== null && end !== undefined;
    var hasStep = step !== null && step !== undefined;
    if (hasStart) {
      if (isBigNumber(start)) {
        start = start.toNumber();
      } else if (typeof start !== 'number') {
        throw new TypeError('Parameter start must be a number');
      }
    }
    if (hasEnd) {
      if (isBigNumber(end)) {
        end = end.toNumber();
      } else if (typeof end !== 'number') {
        throw new TypeError('Parameter end must be a number');
      }
    }
    if (hasStep) {
      if (isBigNumber(step)) {
        step = step.toNumber();
      } else if (typeof step !== 'number') {
        throw new TypeError('Parameter step must be a number');
      }
    }
    this.start = hasStart ? parseFloat(start) : 0;
    this.end = hasEnd ? parseFloat(end) : 0;
    this.step = hasStep ? parseFloat(step) : 1;
  }

  /**
   * Attach type information
   */
  Range.prototype.type = 'Range';
  Range.prototype.isRange = true;

  /**
   * Parse a string into a range,
   * The string contains the start, optional step, and end, separated by a colon.
   * If the string does not contain a valid range, null is returned.
   * For example str='0:2:11'.
   * @memberof Range
   * @param {string} str
   * @return {Range | null} range
   */
  Range.parse = function (str) {
    if (typeof str !== 'string') {
      return null;
    }
    var args = str.split(':');
    var nums = args.map(function (arg) {
      return parseFloat(arg);
    });
    var invalid = nums.some(function (num) {
      return isNaN(num);
    });
    if (invalid) {
      return null;
    }
    switch (nums.length) {
      case 2:
        return new Range(nums[0], nums[1]);
      case 3:
        return new Range(nums[0], nums[2], nums[1]);
      default:
        return null;
    }
  };

  /**
   * Create a clone of the range
   * @return {Range} clone
   */
  Range.prototype.clone = function () {
    return new Range(this.start, this.end, this.step);
  };

  /**
   * Retrieve the size of the range.
   * Returns an array containing one number, the number of elements in the range.
   * @memberof Range
   * @returns {number[]} size
   */
  Range.prototype.size = function () {
    var len = 0;
    var start = this.start;
    var step = this.step;
    var end = this.end;
    var diff = end - start;
    if (sign$1(step) === sign$1(diff)) {
      len = Math.ceil(diff / step);
    } else if (diff === 0) {
      len = 0;
    }
    if (isNaN(len)) {
      len = 0;
    }
    return [len];
  };

  /**
   * Calculate the minimum value in the range
   * @memberof Range
   * @return {number | undefined} min
   */
  Range.prototype.min = function () {
    var size = this.size()[0];
    if (size > 0) {
      if (this.step > 0) {
        // positive step
        return this.start;
      } else {
        // negative step
        return this.start + (size - 1) * this.step;
      }
    } else {
      return undefined;
    }
  };

  /**
   * Calculate the maximum value in the range
   * @memberof Range
   * @return {number | undefined} max
   */
  Range.prototype.max = function () {
    var size = this.size()[0];
    if (size > 0) {
      if (this.step > 0) {
        // positive step
        return this.start + (size - 1) * this.step;
      } else {
        // negative step
        return this.start;
      }
    } else {
      return undefined;
    }
  };

  /**
   * Execute a callback function for each value in the range.
   * @memberof Range
   * @param {function} callback   The callback method is invoked with three
   *                              parameters: the value of the element, the index
   *                              of the element, and the Range being traversed.
   */
  Range.prototype.forEach = function (callback) {
    var x = this.start;
    var step = this.step;
    var end = this.end;
    var i = 0;
    if (step > 0) {
      while (x < end) {
        callback(x, [i], this);
        x += step;
        i++;
      }
    } else if (step < 0) {
      while (x > end) {
        callback(x, [i], this);
        x += step;
        i++;
      }
    }
  };

  /**
   * Execute a callback function for each value in the Range, and return the
   * results as an array
   * @memberof Range
   * @param {function} callback   The callback method is invoked with three
   *                              parameters: the value of the element, the index
   *                              of the element, and the Matrix being traversed.
   * @returns {Array} array
   */
  Range.prototype.map = function (callback) {
    var array = [];
    this.forEach(function (value, index, obj) {
      array[index[0]] = callback(value, index, obj);
    });
    return array;
  };

  /**
   * Create an Array with a copy of the Ranges data
   * @memberof Range
   * @returns {Array} array
   */
  Range.prototype.toArray = function () {
    var array = [];
    this.forEach(function (value, index) {
      array[index[0]] = value;
    });
    return array;
  };

  /**
   * Get the primitive value of the Range, a one dimensional array
   * @memberof Range
   * @returns {Array} array
   */
  Range.prototype.valueOf = function () {
    // TODO: implement a caching mechanism for range.valueOf()
    return this.toArray();
  };

  /**
   * Get a string representation of the range, with optional formatting options.
   * Output is formatted as 'start:step:end', for example '2:6' or '0:0.2:11'
   * @memberof Range
   * @param {Object | number | function} [options]  Formatting options. See
   *                                                lib/utils/number:format for a
   *                                                description of the available
   *                                                options.
   * @returns {string} str
   */
  Range.prototype.format = function (options) {
    var str = format$2(this.start, options);
    if (this.step !== 1) {
      str += ':' + format$2(this.step, options);
    }
    str += ':' + format$2(this.end, options);
    return str;
  };

  /**
   * Get a string representation of the range.
   * @memberof Range
   * @returns {string}
   */
  Range.prototype.toString = function () {
    return this.format();
  };

  /**
   * Get a JSON representation of the range
   * @memberof Range
   * @returns {Object} Returns a JSON object structured as:
   *                   `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}`
   */
  Range.prototype.toJSON = function () {
    return {
      mathjs: 'Range',
      start: this.start,
      end: this.end,
      step: this.step
    };
  };

  /**
   * Instantiate a Range from a JSON object
   * @memberof Range
   * @param {Object} json A JSON object structured as:
   *                      `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}`
   * @return {Range}
   */
  Range.fromJSON = function (json) {
    return new Range(json.start, json.end, json.step);
  };
  return Range;
}, {
  isClass: true
});

var name$4Q = 'Matrix';
var dependencies$4P = [];
var createMatrixClass = /* #__PURE__ */factory(name$4Q, dependencies$4P, () => {
  /**
   * @constructor Matrix
   *
   * A Matrix is a wrapper around an Array. A matrix can hold a multi dimensional
   * array. A matrix can be constructed as:
   *
   *     let matrix = math.matrix(data)
   *
   * Matrix contains the functions to resize, get and set values, get the size,
   * clone the matrix and to convert the matrix to a vector, array, or scalar.
   * Furthermore, one can iterate over the matrix using map and forEach.
   * The internal Array of the Matrix can be accessed using the function valueOf.
   *
   * Example usage:
   *
   *     let matrix = math.matrix([[1, 2], [3, 4]])
   *     matix.size()              // [2, 2]
   *     matrix.resize([3, 2], 5)
   *     matrix.valueOf()          // [[1, 2], [3, 4], [5, 5]]
   *     matrix.subset([1,2])       // 3 (indexes are zero-based)
   *
   */
  function Matrix() {
    if (!(this instanceof Matrix)) {
      throw new SyntaxError('Constructor must be called with the new operator');
    }
  }

  /**
   * Attach type information
   */
  Matrix.prototype.type = 'Matrix';
  Matrix.prototype.isMatrix = true;

  /**
   * Get the storage format used by the matrix.
   *
   * Usage:
   *     const format = matrix.storage()   // retrieve storage format
   *
   * @return {string}           The storage format.
   */
  Matrix.prototype.storage = function () {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke storage on a Matrix interface');
  };

  /**
   * Get the datatype of the data stored in the matrix.
   *
   * Usage:
   *     const format = matrix.datatype()    // retrieve matrix datatype
   *
   * @return {string}           The datatype.
   */
  Matrix.prototype.datatype = function () {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke datatype on a Matrix interface');
  };

  /**
   * Create a new Matrix With the type of the current matrix instance
   * @param {Array | Object} data
   * @param {string} [datatype]
   */
  Matrix.prototype.create = function (data, datatype) {
    throw new Error('Cannot invoke create on a Matrix interface');
  };

  /**
   * Get a subset of the matrix, or replace a subset of the matrix.
   *
   * Usage:
   *     const subset = matrix.subset(index)               // retrieve subset
   *     const value = matrix.subset(index, replacement)   // replace subset
   *
   * @param {Index} index
   * @param {Array | Matrix | *} [replacement]
   * @param {*} [defaultValue=0]      Default value, filled in on new entries when
   *                                  the matrix is resized. If not provided,
   *                                  new matrix elements will be filled with zeros.
   */
  Matrix.prototype.subset = function (index, replacement, defaultValue) {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke subset on a Matrix interface');
  };

  /**
   * Get a single element from the matrix.
   * @param {number[]} index   Zero-based index
   * @return {*} value
   */
  Matrix.prototype.get = function (index) {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke get on a Matrix interface');
  };

  /**
   * Replace a single element in the matrix.
   * @param {number[]} index   Zero-based index
   * @param {*} value
   * @param {*} [defaultValue]        Default value, filled in on new entries when
   *                                  the matrix is resized. If not provided,
   *                                  new matrix elements will be left undefined.
   * @return {Matrix} self
   */
  Matrix.prototype.set = function (index, value, defaultValue) {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke set on a Matrix interface');
  };

  /**
   * Resize the matrix to the given size. Returns a copy of the matrix when
   * `copy=true`, otherwise return the matrix itself (resize in place).
   *
   * @param {number[]} size           The new size the matrix should have.
   * @param {*} [defaultValue=0]      Default value, filled in on new entries.
   *                                  If not provided, the matrix elements will
   *                                  be filled with zeros.
   * @param {boolean} [copy]          Return a resized copy of the matrix
   *
   * @return {Matrix}                 The resized matrix
   */
  Matrix.prototype.resize = function (size, defaultValue) {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke resize on a Matrix interface');
  };

  /**
   * Reshape the matrix to the given size. Returns a copy of the matrix when
   * `copy=true`, otherwise return the matrix itself (reshape in place).
   *
   * @param {number[]} size           The new size the matrix should have.
   * @param {boolean} [copy]          Return a reshaped copy of the matrix
   *
   * @return {Matrix}                 The reshaped matrix
   */
  Matrix.prototype.reshape = function (size, defaultValue) {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke reshape on a Matrix interface');
  };

  /**
   * Create a clone of the matrix
   * @return {Matrix} clone
   */
  Matrix.prototype.clone = function () {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke clone on a Matrix interface');
  };

  /**
   * Retrieve the size of the matrix.
   * @returns {number[]} size
   */
  Matrix.prototype.size = function () {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke size on a Matrix interface');
  };

  /**
   * Create a new matrix with the results of the callback function executed on
   * each entry of the matrix.
   * @param {Function} callback   The callback function is invoked with three
   *                              parameters: the value of the element, the index
   *                              of the element, and the Matrix being traversed.
   * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.
   *
   * @return {Matrix} matrix
   */
  Matrix.prototype.map = function (callback, skipZeros) {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke map on a Matrix interface');
  };

  /**
   * Execute a callback function on each entry of the matrix.
   * @param {Function} callback   The callback function is invoked with three
   *                              parameters: the value of the element, the index
   *                              of the element, and the Matrix being traversed.
   */
  Matrix.prototype.forEach = function (callback) {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke forEach on a Matrix interface');
  };

  /**
   * Iterate over the matrix elements
   * @return {Iterable<{ value, index: number[] }>}
   */
  Matrix.prototype[Symbol.iterator] = function () {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot iterate a Matrix interface');
  };

  /**
   * Create an Array with a copy of the data of the Matrix
   * @returns {Array} array
   */
  Matrix.prototype.toArray = function () {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke toArray on a Matrix interface');
  };

  /**
   * Get the primitive value of the Matrix: a multidimensional array
   * @returns {Array} array
   */
  Matrix.prototype.valueOf = function () {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke valueOf on a Matrix interface');
  };

  /**
   * Get a string representation of the matrix, with optional formatting options.
   * @param {Object | number | Function} [options]  Formatting options. See
   *                                                lib/utils/number:format for a
   *                                                description of the available
   *                                                options.
   * @returns {string} str
   */
  Matrix.prototype.format = function (options) {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke format on a Matrix interface');
  };

  /**
   * Get a string representation of the matrix
   * @returns {string} str
   */
  Matrix.prototype.toString = function () {
    // must be implemented by each of the Matrix implementations
    throw new Error('Cannot invoke toString on a Matrix interface');
  };
  return Matrix;
}, {
  isClass: true
});

/**
 * Formats a BigNumber in a given base
 * @param {BigNumber} n
 * @param {number} base
 * @param {number} size
 * @returns {string}
 */
function formatBigNumberToBase(n, base, size) {
  var BigNumberCtor = n.constructor;
  var big2 = new BigNumberCtor(2);
  var suffix = '';
  if (size) {
    if (size < 1) {
      throw new Error('size must be in greater than 0');
    }
    if (!isInteger(size)) {
      throw new Error('size must be an integer');
    }
    if (n.greaterThan(big2.pow(size - 1).sub(1)) || n.lessThan(big2.pow(size - 1).mul(-1))) {
      throw new Error("Value must be in range [-2^".concat(size - 1, ", 2^").concat(size - 1, "-1]"));
    }
    if (!n.isInteger()) {
      throw new Error('Value must be an integer');
    }
    if (n.lessThan(0)) {
      n = n.add(big2.pow(size));
    }
    suffix = "i".concat(size);
  }
  switch (base) {
    case 2:
      return "".concat(n.toBinary()).concat(suffix);
    case 8:
      return "".concat(n.toOctal()).concat(suffix);
    case 16:
      return "".concat(n.toHexadecimal()).concat(suffix);
    default:
      throw new Error("Base ".concat(base, " not supported "));
  }
}

/**
 * Convert a BigNumber to a formatted string representation.
 *
 * Syntax:
 *
 *    format(value)
 *    format(value, options)
 *    format(value, precision)
 *    format(value, fn)
 *
 * Where:
 *
 *    {number} value   The value to be formatted
 *    {Object} options An object with formatting options. Available options:
 *                     {string} notation
 *                         Number notation. Choose from:
 *                         'fixed'          Always use regular number notation.
 *                                          For example '123.40' and '14000000'
 *                         'exponential'    Always use exponential notation.
 *                                          For example '1.234e+2' and '1.4e+7'
 *                         'auto' (default) Regular number notation for numbers
 *                                          having an absolute value between
 *                                          `lower` and `upper` bounds, and uses
 *                                          exponential notation elsewhere.
 *                                          Lower bound is included, upper bound
 *                                          is excluded.
 *                                          For example '123.4' and '1.4e7'.
 *                         'bin', 'oct, or
 *                         'hex'            Format the number using binary, octal,
 *                                          or hexadecimal notation.
 *                                          For example '0b1101' and '0x10fe'.
 *                     {number} wordSize    The word size in bits to use for formatting
 *                                          in binary, octal, or hexadecimal notation.
 *                                          To be used only with 'bin', 'oct', or 'hex'
 *                                          values for 'notation' option. When this option
 *                                          is defined the value is formatted as a signed
 *                                          twos complement integer of the given word size
 *                                          and the size suffix is appended to the output.
 *                                          For example
 *                                          format(-1, {notation: 'hex', wordSize: 8}) === '0xffi8'.
 *                                          Default value is undefined.
 *                     {number} precision   A number between 0 and 16 to round
 *                                          the digits of the number.
 *                                          In case of notations 'exponential',
 *                                          'engineering', and 'auto',
 *                                          `precision` defines the total
 *                                          number of significant digits returned.
 *                                          In case of notation 'fixed',
 *                                          `precision` defines the number of
 *                                          significant digits after the decimal
 *                                          point.
 *                                          `precision` is undefined by default.
 *                     {number} lowerExp    Exponent determining the lower boundary
 *                                          for formatting a value with an exponent
 *                                          when `notation='auto`.
 *                                          Default value is `-3`.
 *                     {number} upperExp    Exponent determining the upper boundary
 *                                          for formatting a value with an exponent
 *                                          when `notation='auto`.
 *                                          Default value is `5`.
 *    {Function} fn    A custom formatting function. Can be used to override the
 *                     built-in notations. Function `fn` is called with `value` as
 *                     parameter and must return a string. Is useful for example to
 *                     format all values inside a matrix in a particular way.
 *
 * Examples:
 *
 *    format(6.4)                                        // '6.4'
 *    format(1240000)                                    // '1.24e6'
 *    format(1/3)                                        // '0.3333333333333333'
 *    format(1/3, 3)                                     // '0.333'
 *    format(21385, 2)                                   // '21000'
 *    format(12e8, {notation: 'fixed'})                  // returns '1200000000'
 *    format(2.3,    {notation: 'fixed', precision: 4})  // returns '2.3000'
 *    format(52.8,   {notation: 'exponential'})          // returns '5.28e+1'
 *    format(12400,  {notation: 'engineering'})          // returns '12.400e+3'
 *
 * @param {BigNumber} value
 * @param {Object | Function | number | BigNumber} [options]
 * @return {string} str The formatted value
 */
function format$1(value, options) {
  if (typeof options === 'function') {
    // handle format(value, fn)
    return options(value);
  }

  // handle special cases
  if (!value.isFinite()) {
    return value.isNaN() ? 'NaN' : value.gt(0) ? 'Infinity' : '-Infinity';
  }
  var {
    notation,
    precision,
    wordSize
  } = normalizeFormatOptions(options);

  // handle the various notations
  switch (notation) {
    case 'fixed':
      return toFixed(value, precision);
    case 'exponential':
      return toExponential(value, precision);
    case 'engineering':
      return toEngineering(value, precision);
    case 'bin':
      return formatBigNumberToBase(value, 2, wordSize);
    case 'oct':
      return formatBigNumberToBase(value, 8, wordSize);
    case 'hex':
      return formatBigNumberToBase(value, 16, wordSize);
    case 'auto':
      {
        // determine lower and upper bound for exponential notation.
        // TODO: implement support for upper and lower to be BigNumbers themselves
        var lowerExp = _toNumberOrDefault(options === null || options === void 0 ? void 0 : options.lowerExp, -3);
        var upperExp = _toNumberOrDefault(options === null || options === void 0 ? void 0 : options.upperExp, 5);

        // handle special case zero
        if (value.isZero()) return '0';

        // determine whether or not to output exponential notation
        var str;
        var rounded = value.toSignificantDigits(precision);
        var exp = rounded.e;
        if (exp >= lowerExp && exp < upperExp) {
          // normal number notation
          str = rounded.toFixed();
        } else {
          // exponential notation
          str = toExponential(value, precision);
        }

        // remove trailing zeros after the decimal point
        return str.replace(/((\.\d*?)(0+))($|e)/, function () {
          var digits = arguments[2];
          var e = arguments[4];
          return digits !== '.' ? digits + e : e;
        });
      }
    default:
      throw new Error('Unknown notation "' + notation + '". ' + 'Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.');
  }
}

/**
 * Format a BigNumber in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3'
 * @param {BigNumber} value
 * @param {number} [precision]        Optional number of significant figures to return.
 */
function toEngineering(value, precision) {
  // find nearest lower multiple of 3 for exponent
  var e = value.e;
  var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3;

  // find difference in exponents, and calculate the value without exponent
  var valueWithoutExp = value.mul(Math.pow(10, -newExp));
  var valueStr = valueWithoutExp.toPrecision(precision);
  if (valueStr.includes('e')) {
    var BigNumber = value.constructor;
    valueStr = new BigNumber(valueStr).toFixed();
  }
  return valueStr + 'e' + (e >= 0 ? '+' : '') + newExp.toString();
}

/**
 * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3'
 * @param {BigNumber} value
 * @param {number} [precision]  Number of digits in formatted output.
 *                              If not provided, the maximum available digits
 *                              is used.
 * @returns {string} str
 */
function toExponential(value, precision) {
  if (precision !== undefined) {
    return value.toExponential(precision - 1); // Note the offset of one
  } else {
    return value.toExponential();
  }
}

/**
 * Format a number with fixed notation.
 * @param {BigNumber} value
 * @param {number} [precision=undefined] Optional number of decimals after the
 *                                       decimal point. Undefined by default.
 */
function toFixed(value, precision) {
  return value.toFixed(precision);
}
function _toNumberOrDefault(value, defaultValue) {
  if (isNumber(value)) {
    return value;
  } else if (isBigNumber(value)) {
    return value.toNumber();
  } else {
    return defaultValue;
  }
}

/**
 * Check if a text ends with a certain string.
 * @param {string} text
 * @param {string} search
 */
function endsWith(text, search) {
  var start = text.length - search.length;
  var end = text.length;
  return text.substring(start, end) === search;
}

/**
 * Format a value of any type into a string.
 *
 * Usage:
 *     math.format(value)
 *     math.format(value, precision)
 *     math.format(value, options)
 *
 * When value is a function:
 *
 * - When the function has a property `syntax`, it returns this
 *   syntax description.
 * - In other cases, a string `'function'` is returned.
 *
 * When `value` is an Object:
 *
 * - When the object contains a property `format` being a function, this
 *   function is invoked as `value.format(options)` and the result is returned.
 * - When the object has its own `toString` method, this method is invoked
 *   and the result is returned.
 * - In other cases the function will loop over all object properties and
 *   return JSON object notation like '{"a": 2, "b": 3}'.
 *
 * Example usage:
 *     math.format(2/7)                // '0.2857142857142857'
 *     math.format(math.pi, 3)         // '3.14'
 *     math.format(new Complex(2, 3))  // '2 + 3i'
 *     math.format('hello')            // '"hello"'
 *
 * @param {*} value             Value to be stringified
 * @param {Object | number | Function} [options]
 *     Formatting options. See src/utils/number.js:format for a
 *     description of the available options controlling number output.
 *     This generic "format" also supports the option property `truncate: NN`
 *     giving the maximum number NN of characters to return (if there would
 *     have been more, they are deleted and replaced by an ellipsis).
 * @return {string} str
 */
function format(value, options) {
  var result = _format(value, options);
  if (options && typeof options === 'object' && 'truncate' in options && result.length > options.truncate) {
    return result.substring(0, options.truncate - 3) + '...';
  }
  return result;
}
function _format(value, options) {
  if (typeof value === 'number') {
    return format$2(value, options);
  }
  if (isBigNumber(value)) {
    return format$1(value, options);
  }

  // note: we use unsafe duck-typing here to check for Fractions, this is
  // ok here since we're only invoking toString or concatenating its values
  if (looksLikeFraction(value)) {
    if (!options || options.fraction !== 'decimal') {
      // output as ratio, like '1/3'
      return value.s * value.n + '/' + value.d;
    } else {
      // output as decimal, like '0.(3)'
      return value.toString();
    }
  }
  if (Array.isArray(value)) {
    return formatArray(value, options);
  }
  if (isString(value)) {
    return stringify(value);
  }
  if (typeof value === 'function') {
    return value.syntax ? String(value.syntax) : 'function';
  }
  if (value && typeof value === 'object') {
    if (typeof value.format === 'function') {
      return value.format(options);
    } else if (value && value.toString(options) !== {}.toString()) {
      // this object has a non-native toString method, use that one
      return value.toString(options);
    } else {
      var entries = Object.keys(value).map(key => {
        return stringify(key) + ': ' + format(value[key], options);
      });
      return '{' + entries.join(', ') + '}';
    }
  }
  return String(value);
}

/**
 * Stringify a value into a string enclosed in double quotes.
 * Unescaped double quotes and backslashes inside the value are escaped.
 * @param {*} value
 * @return {string}
 */
function stringify(value) {
  var text = String(value);
  var escaped = '';
  var i = 0;
  while (i < text.length) {
    var c = text.charAt(i);
    escaped += c in controlCharacters ? controlCharacters[c] : c;
    i++;
  }
  return '"' + escaped + '"';
}
var controlCharacters = {
  '"': '\\"',
  '\\': '\\\\',
  '\b': '\\b',
  '\f': '\\f',
  '\n': '\\n',
  '\r': '\\r',
  '\t': '\\t'
};

/**
 * Escape special HTML characters
 * @param {*} value
 * @return {string}
 */
function escape(value) {
  var text = String(value);
  text = text.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  return text;
}

/**
 * Recursively format an n-dimensional matrix
 * Example output: "[[1, 2], [3, 4]]"
 * @param {Array} array
 * @param {Object | number | Function} [options]  Formatting options. See
 *                                                lib/utils/number:format for a
 *                                                description of the available
 *                                                options.
 * @returns {string} str
 */
function formatArray(array, options) {
  if (Array.isArray(array)) {
    var str = '[';
    var len = array.length;
    for (var i = 0; i < len; i++) {
      if (i !== 0) {
        str += ', ';
      }
      str += formatArray(array[i], options);
    }
    str += ']';
    return str;
  } else {
    return format(array, options);
  }
}

/**
 * Check whether a value looks like a Fraction (unsafe duck-type check)
 * @param {*} value
 * @return {boolean}
 */
function looksLikeFraction(value) {
  return value && typeof value === 'object' && typeof value.s === 'number' && typeof value.n === 'number' && typeof value.d === 'number' || false;
}

/**
 * Compare two strings
 * @param {string} x
 * @param {string} y
 * @returns {number}
 */
function compareText(x, y) {
  // we don't want to convert numbers to string, only accept string input
  if (!isString(x)) {
    throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + typeOf(x) + ', index: 0)');
  }
  if (!isString(y)) {
    throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + typeOf(y) + ', index: 1)');
  }
  return x === y ? 0 : x > y ? 1 : -1;
}

/**
 * Create a range error with the message:
 *     'Dimension mismatch (<actual size> != <expected size>)'
 * @param {number | number[]} actual        The actual size
 * @param {number | number[]} expected      The expected size
 * @param {string} [relation='!=']          Optional relation between actual
 *                                          and expected size: '!=', '<', etc.
 * @extends RangeError
 */
function DimensionError(actual, expected, relation) {
  if (!(this instanceof DimensionError)) {
    throw new SyntaxError('Constructor must be called with the new operator');
  }
  this.actual = actual;
  this.expected = expected;
  this.relation = relation;
  this.message = 'Dimension mismatch (' + (Array.isArray(actual) ? '[' + actual.join(', ') + ']' : actual) + ' ' + (this.relation || '!=') + ' ' + (Array.isArray(expected) ? '[' + expected.join(', ') + ']' : expected) + ')';
  this.stack = new Error().stack;
}
DimensionError.prototype = new RangeError();
DimensionError.prototype.constructor = RangeError;
DimensionError.prototype.name = 'DimensionError';
DimensionError.prototype.isDimensionError = true;

/**
 * Create a range error with the message:
 *     'Index out of range (index < min)'
 *     'Index out of range (index < max)'
 *
 * @param {number} index     The actual index
 * @param {number} [min=0]   Minimum index (included)
 * @param {number} [max]     Maximum index (excluded)
 * @extends RangeError
 */
function IndexError(index, min, max) {
  if (!(this instanceof IndexError)) {
    throw new SyntaxError('Constructor must be called with the new operator');
  }
  this.index = index;
  if (arguments.length < 3) {
    this.min = 0;
    this.max = min;
  } else {
    this.min = min;
    this.max = max;
  }
  if (this.min !== undefined && this.index < this.min) {
    this.message = 'Index out of range (' + this.index + ' < ' + this.min + ')';
  } else if (this.max !== undefined && this.index >= this.max) {
    this.message = 'Index out of range (' + this.index + ' > ' + (this.max - 1) + ')';
  } else {
    this.message = 'Index out of range (' + this.index + ')';
  }
  this.stack = new Error().stack;
}
IndexError.prototype = new RangeError();
IndexError.prototype.constructor = RangeError;
IndexError.prototype.name = 'IndexError';
IndexError.prototype.isIndexError = true;

/**
 * Calculate the size of a multi dimensional array.
 * This function checks the size of the first entry, it does not validate
 * whether all dimensions match. (use function `validate` for that)
 * @param {Array} x
 * @Return {Number[]} size
 */
function arraySize(x) {
  var s = [];
  while (Array.isArray(x)) {
    s.push(x.length);
    x = x[0];
  }
  return s;
}

/**
 * Recursively validate whether each element in a multi dimensional array
 * has a size corresponding to the provided size array.
 * @param {Array} array    Array to be validated
 * @param {number[]} size  Array with the size of each dimension
 * @param {number} dim   Current dimension
 * @throws DimensionError
 * @private
 */
function _validate(array, size, dim) {
  var i;
  var len = array.length;
  if (len !== size[dim]) {
    throw new DimensionError(len, size[dim]);
  }
  if (dim < size.length - 1) {
    // recursively validate each child array
    var dimNext = dim + 1;
    for (i = 0; i < len; i++) {
      var child = array[i];
      if (!Array.isArray(child)) {
        throw new DimensionError(size.length - 1, size.length, '<');
      }
      _validate(array[i], size, dimNext);
    }
  } else {
    // last dimension. none of the childs may be an array
    for (i = 0; i < len; i++) {
      if (Array.isArray(array[i])) {
        throw new DimensionError(size.length + 1, size.length, '>');
      }
    }
  }
}

/**
 * Validate whether each element in a multi dimensional array has
 * a size corresponding to the provided size array.
 * @param {Array} array    Array to be validated
 * @param {number[]} size  Array with the size of each dimension
 * @throws DimensionError
 */
function validate(array, size) {
  var isScalar = size.length === 0;
  if (isScalar) {
    // scalar
    if (Array.isArray(array)) {
      throw new DimensionError(array.length, 0);
    }
  } else {
    // array
    _validate(array, size, 0);
  }
}

/**
 * Validate whether the source of the index matches the size of the Array
 * @param {Array | Matrix} array    Array to be validated
 * @param {Index} index  Index with the source information to validate
 * @throws DimensionError
 */
function validateIndexSourceSize(value, index) {
  var valueSize = value.isMatrix ? value._size : arraySize(value);
  var sourceSize = index._sourceSize;
  // checks if the source size is not null and matches the valueSize
  sourceSize.forEach((sourceDim, i) => {
    if (sourceDim !== null && sourceDim !== valueSize[i]) {
      throw new DimensionError(sourceDim, valueSize[i]);
    }
  });
}

/**
 * Test whether index is an integer number with index >= 0 and index < length
 * when length is provided
 * @param {number} index    Zero-based index
 * @param {number} [length] Length of the array
 */
function validateIndex(index, length) {
  if (index !== undefined) {
    if (!isNumber(index) || !isInteger(index)) {
      throw new TypeError('Index must be an integer (value: ' + index + ')');
    }
    if (index < 0 || typeof length === 'number' && index >= length) {
      throw new IndexError(index, length);
    }
  }
}

/**
 * Test if and index has empty values
 * @param {number} index    Zero-based index
 */
function isEmptyIndex(index) {
  for (var i = 0; i < index._dimensions.length; ++i) {
    var dimension = index._dimensions[i];
    if (dimension._data && isArray(dimension._data)) {
      if (dimension._size[0] === 0) {
        return true;
      }
    } else if (dimension.isRange) {
      if (dimension.start === dimension.end) {
        return true;
      }
    } else if (isString(dimension)) {
      if (dimension.length === 0) {
        return true;
      }
    }
  }
  return false;
}

/**
 * Resize a multi dimensional array. The resized array is returned.
 * @param {Array | number} array         Array to be resized
 * @param {number[]} size Array with the size of each dimension
 * @param {*} [defaultValue=0]  Value to be filled in in new entries,
 *                              zero by default. Specify for example `null`,
 *                              to clearly see entries that are not explicitly
 *                              set.
 * @return {Array} array         The resized array
 */
function resize(array, size, defaultValue) {
  // check the type of the arguments
  if (!Array.isArray(size)) {
    throw new TypeError('Array expected');
  }
  if (size.length === 0) {
    throw new Error('Resizing to scalar is not supported');
  }

  // check whether size contains positive integers
  size.forEach(function (value) {
    if (!isNumber(value) || !isInteger(value) || value < 0) {
      throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + format(size) + ')');
    }
  });

  // convert number to an array
  if (isNumber(array) || isBigNumber(array)) {
    array = [array];
  }

  // recursively resize the array
  var _defaultValue = defaultValue !== undefined ? defaultValue : 0;
  _resize(array, size, 0, _defaultValue);
  return array;
}

/**
 * Recursively resize a multi dimensional array
 * @param {Array} array         Array to be resized
 * @param {number[]} size       Array with the size of each dimension
 * @param {number} dim          Current dimension
 * @param {*} [defaultValue]    Value to be filled in in new entries,
 *                              undefined by default.
 * @private
 */
function _resize(array, size, dim, defaultValue) {
  var i;
  var elem;
  var oldLen = array.length;
  var newLen = size[dim];
  var minLen = Math.min(oldLen, newLen);

  // apply new length
  array.length = newLen;
  if (dim < size.length - 1) {
    // non-last dimension
    var dimNext = dim + 1;

    // resize existing child arrays
    for (i = 0; i < minLen; i++) {
      // resize child array
      elem = array[i];
      if (!Array.isArray(elem)) {
        elem = [elem]; // add a dimension
        array[i] = elem;
      }
      _resize(elem, size, dimNext, defaultValue);
    }

    // create new child arrays
    for (i = minLen; i < newLen; i++) {
      // get child array
      elem = [];
      array[i] = elem;

      // resize new child array
      _resize(elem, size, dimNext, defaultValue);
    }
  } else {
    // last dimension

    // remove dimensions of existing values
    for (i = 0; i < minLen; i++) {
      while (Array.isArray(array[i])) {
        array[i] = array[i][0];
      }
    }

    // fill new elements with the default value
    for (i = minLen; i < newLen; i++) {
      array[i] = defaultValue;
    }
  }
}

/**
 * Re-shape a multi dimensional array to fit the specified dimensions
 * @param {Array} array           Array to be reshaped
 * @param {number[]} sizes        List of sizes for each dimension
 * @returns {Array}               Array whose data has been formatted to fit the
 *                                specified dimensions
 *
 * @throws {DimensionError}       If the product of the new dimension sizes does
 *                                not equal that of the old ones
 */
function reshape(array, sizes) {
  var flatArray = flatten(array);
  var currentLength = flatArray.length;
  if (!Array.isArray(array) || !Array.isArray(sizes)) {
    throw new TypeError('Array expected');
  }
  if (sizes.length === 0) {
    throw new DimensionError(0, currentLength, '!=');
  }
  sizes = processSizesWildcard(sizes, currentLength);
  var newLength = product$1(sizes);
  if (currentLength !== newLength) {
    throw new DimensionError(newLength, currentLength, '!=');
  }
  try {
    return _reshape(flatArray, sizes);
  } catch (e) {
    if (e instanceof DimensionError) {
      throw new DimensionError(newLength, currentLength, '!=');
    }
    throw e;
  }
}

/**
 * Replaces the wildcard -1 in the sizes array.
 * @param {number[]} sizes  List of sizes for each dimension. At most on wildcard.
 * @param {number} currentLength  Number of elements in the array.
 * @throws {Error}                If more than one wildcard or unable to replace it.
 * @returns {number[]}      The sizes array with wildcard replaced.
 */
function processSizesWildcard(sizes, currentLength) {
  var newLength = product$1(sizes);
  var processedSizes = sizes.slice();
  var WILDCARD = -1;
  var wildCardIndex = sizes.indexOf(WILDCARD);
  var isMoreThanOneWildcard = sizes.indexOf(WILDCARD, wildCardIndex + 1) >= 0;
  if (isMoreThanOneWildcard) {
    throw new Error('More than one wildcard in sizes');
  }
  var hasWildcard = wildCardIndex >= 0;
  var canReplaceWildcard = currentLength % newLength === 0;
  if (hasWildcard) {
    if (canReplaceWildcard) {
      processedSizes[wildCardIndex] = -currentLength / newLength;
    } else {
      throw new Error('Could not replace wildcard, since ' + currentLength + ' is no multiple of ' + -newLength);
    }
  }
  return processedSizes;
}

/**
 * Computes the product of all array elements.
 * @param {number[]} array Array of factors
 * @returns {number}            Product of all elements
 */
function product$1(array) {
  return array.reduce((prev, curr) => prev * curr, 1);
}

/**
 * Iteratively re-shape a multi dimensional array to fit the specified dimensions
 * @param {Array} array           Array to be reshaped
 * @param {number[]} sizes  List of sizes for each dimension
 * @returns {Array}               Array whose data has been formatted to fit the
 *                                specified dimensions
 */

function _reshape(array, sizes) {
  // testing if there are enough elements for the requested shape
  var tmpArray = array;
  var tmpArray2;
  // for each dimensions starting by the last one and ignoring the first one
  for (var sizeIndex = sizes.length - 1; sizeIndex > 0; sizeIndex--) {
    var size = sizes[sizeIndex];
    tmpArray2 = [];

    // aggregate the elements of the current tmpArray in elements of the requested size
    var length = tmpArray.length / size;
    for (var i = 0; i < length; i++) {
      tmpArray2.push(tmpArray.slice(i * size, (i + 1) * size));
    }
    // set it as the new tmpArray for the next loop turn or for return
    tmpArray = tmpArray2;
  }
  return tmpArray;
}

/**
 * Squeeze a multi dimensional array
 * @param {Array} array
 * @param {Array} [size]
 * @returns {Array} returns the array itself
 */
function squeeze(array, size) {
  var s = size || arraySize(array);

  // squeeze outer dimensions
  while (Array.isArray(array) && array.length === 1) {
    array = array[0];
    s.shift();
  }

  // find the first dimension to be squeezed
  var dims = s.length;
  while (s[dims - 1] === 1) {
    dims--;
  }

  // squeeze inner dimensions
  if (dims < s.length) {
    array = _squeeze(array, dims, 0);
    s.length = dims;
  }
  return array;
}

/**
 * Recursively squeeze a multi dimensional array
 * @param {Array} array
 * @param {number} dims Required number of dimensions
 * @param {number} dim  Current dimension
 * @returns {Array | *} Returns the squeezed array
 * @private
 */
function _squeeze(array, dims, dim) {
  var i, ii;
  if (dim < dims) {
    var next = dim + 1;
    for (i = 0, ii = array.length; i < ii; i++) {
      array[i] = _squeeze(array[i], dims, next);
    }
  } else {
    while (Array.isArray(array)) {
      array = array[0];
    }
  }
  return array;
}

/**
 * Unsqueeze a multi dimensional array: add dimensions when missing
 *
 * Paramter `size` will be mutated to match the new, unqueezed matrix size.
 *
 * @param {Array} array
 * @param {number} dims       Desired number of dimensions of the array
 * @param {number} [outer]    Number of outer dimensions to be added
 * @param {Array} [size] Current size of array.
 * @returns {Array} returns the array itself
 * @private
 */
function unsqueeze(array, dims, outer, size) {
  var s = size || arraySize(array);

  // unsqueeze outer dimensions
  if (outer) {
    for (var i = 0; i < outer; i++) {
      array = [array];
      s.unshift(1);
    }
  }

  // unsqueeze inner dimensions
  array = _unsqueeze(array, dims, 0);
  while (s.length < dims) {
    s.push(1);
  }
  return array;
}

/**
 * Recursively unsqueeze a multi dimensional array
 * @param {Array} array
 * @param {number} dims Required number of dimensions
 * @param {number} dim  Current dimension
 * @returns {Array | *} Returns the squeezed array
 * @private
 */
function _unsqueeze(array, dims, dim) {
  var i, ii;
  if (Array.isArray(array)) {
    var next = dim + 1;
    for (i = 0, ii = array.length; i < ii; i++) {
      array[i] = _unsqueeze(array[i], dims, next);
    }
  } else {
    for (var d = dim; d < dims; d++) {
      array = [array];
    }
  }
  return array;
}
/**
 * Flatten a multi dimensional array, put all elements in a one dimensional
 * array
 * @param {Array} array   A multi dimensional array
 * @return {Array}        The flattened array (1 dimensional)
 */
function flatten(array) {
  if (!Array.isArray(array)) {
    // if not an array, return as is
    return array;
  }
  var flat = [];
  array.forEach(function callback(value) {
    if (Array.isArray(value)) {
      value.forEach(callback); // traverse through sub-arrays recursively
    } else {
      flat.push(value);
    }
  });
  return flat;
}

/**
 * A safe map
 * @param {Array} array
 * @param {function} callback
 */
function map(array, callback) {
  return Array.prototype.map.call(array, callback);
}

/**
 * A safe forEach
 * @param {Array} array
 * @param {function} callback
 */
function forEach(array, callback) {
  Array.prototype.forEach.call(array, callback);
}

/**
 * A safe filter
 * @param {Array} array
 * @param {function} callback
 */
function filter(array, callback) {
  if (arraySize(array).length !== 1) {
    throw new Error('Only one dimensional matrices supported');
  }
  return Array.prototype.filter.call(array, callback);
}

/**
 * Filter values in a callback given a regular expression
 * @param {Array} array
 * @param {RegExp} regexp
 * @return {Array} Returns the filtered array
 * @private
 */
function filterRegExp(array, regexp) {
  if (arraySize(array).length !== 1) {
    throw new Error('Only one dimensional matrices supported');
  }
  return Array.prototype.filter.call(array, entry => regexp.test(entry));
}

/**
 * A safe join
 * @param {Array} array
 * @param {string} separator
 */
function join(array, separator) {
  return Array.prototype.join.call(array, separator);
}

/**
 * Assign a numeric identifier to every element of a sorted array
 * @param {Array} a  An array
 * @return {Array} An array of objects containing the original value and its identifier
 */
function identify(a) {
  if (!Array.isArray(a)) {
    throw new TypeError('Array input expected');
  }
  if (a.length === 0) {
    return a;
  }
  var b = [];
  var count = 0;
  b[0] = {
    value: a[0],
    identifier: 0
  };
  for (var i = 1; i < a.length; i++) {
    if (a[i] === a[i - 1]) {
      count++;
    } else {
      count = 0;
    }
    b.push({
      value: a[i],
      identifier: count
    });
  }
  return b;
}

/**
 * Remove the numeric identifier from the elements
 * @param {array} a  An array
 * @return {array} An array of values without identifiers
 */
function generalize(a) {
  if (!Array.isArray(a)) {
    throw new TypeError('Array input expected');
  }
  if (a.length === 0) {
    return a;
  }
  var b = [];
  for (var i = 0; i < a.length; i++) {
    b.push(a[i].value);
  }
  return b;
}

/**
 * Check the datatype of a given object
 * This is a low level implementation that should only be used by
 * parent Matrix classes such as SparseMatrix or DenseMatrix
 * This method does not validate Array Matrix shape
 * @param {Array} array
 * @param {function} typeOf   Callback function to use to determine the type of a value
 * @return {string}
 */
function getArrayDataType(array, typeOf) {
  var type; // to hold type info
  var length = 0; // to hold length value to ensure it has consistent sizes

  for (var i = 0; i < array.length; i++) {
    var item = array[i];
    var _isArray = Array.isArray(item);

    // Saving the target matrix row size
    if (i === 0 && _isArray) {
      length = item.length;
    }

    // If the current item is an array but the length does not equal the targetVectorSize
    if (_isArray && item.length !== length) {
      return undefined;
    }
    var itemType = _isArray ? getArrayDataType(item, typeOf) // recurse into a nested array
    : typeOf(item);
    if (type === undefined) {
      type = itemType; // first item
    } else if (type !== itemType) {
      return 'mixed';
    } else ;
  }
  return type;
}

/**
 * Recursively concatenate two matrices.
 * The contents of the matrices is not cloned.
 * @param {Array} a             Multi dimensional array
 * @param {Array} b             Multi dimensional array
 * @param {number} concatDim    The dimension on which to concatenate (zero-based)
 * @param {number} dim          The current dim (zero-based)
 * @return {Array} c            The concatenated matrix
 * @private
 */
function concatRecursive(a, b, concatDim, dim) {
  if (dim < concatDim) {
    // recurse into next dimension
    if (a.length !== b.length) {
      throw new DimensionError(a.length, b.length);
    }
    var c = [];
    for (var i = 0; i < a.length; i++) {
      c[i] = concatRecursive(a[i], b[i], concatDim, dim + 1);
    }
    return c;
  } else {
    // concatenate this dimension
    return a.concat(b);
  }
}

/**
 * Concatenates many arrays in the specified direction
 * @param {...Array} arrays All the arrays to concatenate
 * @param {number} concatDim The dimension on which to concatenate (zero-based)
 * @returns
*/
function concat() {
  var arrays = Array.prototype.slice.call(arguments, 0, -1);
  var concatDim = Array.prototype.slice.call(arguments, -1);
  if (arrays.length === 1) {
    return arrays[0];
  }
  if (arrays.length > 1) {
    return arrays.slice(1).reduce(function (A, B) {
      return concatRecursive(A, B, concatDim, 0);
    }, arrays[0]);
  } else {
    throw new Error('Wrong number of arguments in function concat');
  }
}

/**
 * Receives two or more sizes and get's the broadcasted size for both.
 * @param  {...number[]} sizes Sizes to broadcast together
 * @returns
 */
function broadcastSizes() {
  for (var _len = arguments.length, sizes = new Array(_len), _key = 0; _key < _len; _key++) {
    sizes[_key] = arguments[_key];
  }
  var dimensions = sizes.map(s => s.length);
  var N = Math.max(...dimensions);
  var sizeMax = new Array(N).fill(null);
  // check for every size
  for (var i = 0; i < sizes.length; i++) {
    var size = sizes[i];
    var dim = dimensions[i];
    for (var j = 0; j < dim; j++) {
      var n = N - dim + j;
      if (size[j] > sizeMax[n]) {
        sizeMax[n] = size[j];
      }
    }
  }
  for (var _i = 0; _i < sizes.length; _i++) {
    checkBroadcastingRules(sizes[_i], sizeMax);
  }
  return sizeMax;
}

/**
 * Checks if it's possible to broadcast a size to another size
 * @param {number[]} size The size of the array to check
 * @param {number[]} toSize The size of the array to validate if it can be broadcasted to
 */
function checkBroadcastingRules(size, toSize) {
  var N = toSize.length;
  var dim = size.length;
  for (var j = 0; j < dim; j++) {
    var n = N - dim + j;
    if (size[j] < toSize[n] && size[j] > 1 || size[j] > toSize[n]) {
      throw new Error("shape missmatch: missmatch is found in arg with shape (".concat(size, ") not possible to broadcast dimension ").concat(dim, " with size ").concat(size[j], " to size ").concat(toSize[n]));
    }
  }
}

/**
 * Broadcasts a single array to a certain size
 * @param {array} array Array to be broadcasted
 * @param {number[]} toSize Size to broadcast the array
 * @returns The broadcasted array
 */
function broadcastTo(array, toSize) {
  var Asize = arraySize(array);
  if (deepStrictEqual(Asize, toSize)) {
    return array;
  }
  checkBroadcastingRules(Asize, toSize);
  var broadcastedSize = broadcastSizes(Asize, toSize);
  var N = broadcastedSize.length;
  var paddedSize = [...Array(N - Asize.length).fill(1), ...Asize];
  var A = clone(array);
  // reshape A if needed to make it ready for concat
  if (Asize.length < N) {
    A = reshape(A, paddedSize);
    Asize = arraySize(A);
  }

  // stretches the array on each dimension to make it the same size as index
  for (var dim = 0; dim < N; dim++) {
    if (Asize[dim] < broadcastedSize[dim]) {
      A = stretch(A, broadcastedSize[dim], dim);
      Asize = arraySize(A);
    }
  }
  return A;
}

/**
 * stretches a matrix up to a certain size in a certain dimension
 * @param {Array} arrayToStretch
 * @param {number[]} sizeToStretch
 * @param {number} dimToStretch
 * @returns
 */
function stretch(arrayToStretch, sizeToStretch, dimToStretch) {
  return concat(...Array(sizeToStretch).fill(arrayToStretch), dimToStretch);
}

/**
 * Deep clones a multidimensional array
 * @param {Array} array
 * @returns cloned array
 */
function clone(array) {
  return _extends$1([], array);
}

// (c) 2018, Mariusz Nowak
// SPDX-License-Identifier: ISC
// Derived from https://github.com/medikoo/lru-queue
function lruQueue(limit) {
  var size = 0;
  var base = 1;
  var queue = Object.create(null);
  var map = Object.create(null);
  var index = 0;
  var del = function del(id) {
    var oldIndex = map[id];
    if (!oldIndex) return;
    delete queue[oldIndex];
    delete map[id];
    --size;
    if (base !== oldIndex) return;
    if (!size) {
      index = 0;
      base = 1;
      return;
    }
    while (!Object.prototype.hasOwnProperty.call(queue, ++base)) {/* empty */}
  };
  limit = Math.abs(limit);
  return {
    hit: function hit(id) {
      var oldIndex = map[id];
      var nuIndex = ++index;
      queue[nuIndex] = id;
      map[id] = nuIndex;
      if (!oldIndex) {
        ++size;
        if (size <= limit) return undefined;
        id = queue[base];
        del(id);
        return id;
      }
      delete queue[oldIndex];
      if (base !== oldIndex) return undefined;
      while (!Object.prototype.hasOwnProperty.call(queue, ++base)) {/* empty */}
      return undefined;
    },
    delete: del,
    clear: function clear() {
      size = index = 0;
      base = 1;
      queue = Object.create(null);
      map = Object.create(null);
    }
  };
}

// function utils

/**
 * Memoize a given function by caching the computed result.
 * The cache of a memoized function can be cleared by deleting the `cache`
 * property of the function.
 *
 * @param {function} fn                     The function to be memoized.
 *                                          Must be a pure function.
 * @param {Object} [options]
 * @param {function(args: Array): string} [options.hasher]
 *    A custom hash builder. Is JSON.stringify by default.
 * @param {number | undefined} [options.limit]
 *    Maximum number of values that may be cached. Undefined indicates
 *    unlimited (default)
 * @return {function}                       Returns the memoized function
 */
function memoize(fn) {
  var {
    hasher,
    limit
  } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  limit = limit == null ? Number.POSITIVE_INFINITY : limit;
  hasher = hasher == null ? JSON.stringify : hasher;
  return function memoize() {
    if (typeof memoize.cache !== 'object') {
      memoize.cache = {
        values: new Map(),
        lru: lruQueue(limit || Number.POSITIVE_INFINITY)
      };
    }
    var args = [];
    for (var i = 0; i < arguments.length; i++) {
      args[i] = arguments[i];
    }
    var hash = hasher(args);
    if (memoize.cache.values.has(hash)) {
      memoize.cache.lru.hit(hash);
      return memoize.cache.values.get(hash);
    }
    var newVal = fn.apply(fn, args);
    memoize.cache.values.set(hash, newVal);
    memoize.cache.values.delete(memoize.cache.lru.hit(hash));
    return newVal;
  };
}

/**
 * Find the maximum number of arguments expected by a typed function.
 * @param {function} fn   A typed function
 * @return {number} Returns the maximum number of expected arguments.
 *                  Returns -1 when no signatures where found on the function.
 */
function maxArgumentCount(fn) {
  return Object.keys(fn.signatures || {}).reduce(function (args, signature) {
    var count = (signature.match(/,/g) || []).length + 1;
    return Math.max(args, count);
  }, -1);
}

var name$4P = 'DenseMatrix';
var dependencies$4O = ['Matrix'];
var createDenseMatrixClass = /* #__PURE__ */factory(name$4P, dependencies$4O, _ref => {
  var {
    Matrix
  } = _ref;
  /**
   * Dense Matrix implementation. A regular, dense matrix, supporting multi-dimensional matrices. This is the default matrix type.
   * @class DenseMatrix
   * @enum {{ value, index: number[] }}
   */
  function DenseMatrix(data, datatype) {
    if (!(this instanceof DenseMatrix)) {
      throw new SyntaxError('Constructor must be called with the new operator');
    }
    if (datatype && !isString(datatype)) {
      throw new Error('Invalid datatype: ' + datatype);
    }
    if (isMatrix(data)) {
      // check data is a DenseMatrix
      if (data.type === 'DenseMatrix') {
        // clone data & size
        this._data = clone$2(data._data);
        this._size = clone$2(data._size);
        this._datatype = datatype || data._datatype;
      } else {
        // build data from existing matrix
        this._data = data.toArray();
        this._size = data.size();
        this._datatype = datatype || data._datatype;
      }
    } else if (data && isArray(data.data) && isArray(data.size)) {
      // initialize fields from JSON representation
      this._data = data.data;
      this._size = data.size;
      // verify the dimensions of the array
      validate(this._data, this._size);
      this._datatype = datatype || data.datatype;
    } else if (isArray(data)) {
      // replace nested Matrices with Arrays
      this._data = preprocess(data);
      // get the dimensions of the array
      this._size = arraySize(this._data);
      // verify the dimensions of the array, TODO: compute size while processing array
      validate(this._data, this._size);
      // data type unknown
      this._datatype = datatype;
    } else if (data) {
      // unsupported type
      throw new TypeError('Unsupported type of data (' + typeOf(data) + ')');
    } else {
      // nothing provided
      this._data = [];
      this._size = [0];
      this._datatype = datatype;
    }
  }
  DenseMatrix.prototype = new Matrix();

  /**
   * Create a new DenseMatrix
   */
  DenseMatrix.prototype.createDenseMatrix = function (data, datatype) {
    return new DenseMatrix(data, datatype);
  };

  /**
   * Attach type information
   */
  Object.defineProperty(DenseMatrix, 'name', {
    value: 'DenseMatrix'
  });
  DenseMatrix.prototype.constructor = DenseMatrix;
  DenseMatrix.prototype.type = 'DenseMatrix';
  DenseMatrix.prototype.isDenseMatrix = true;

  /**
   * Get the matrix type
   *
   * Usage:
   *    const matrixType = matrix.getDataType()  // retrieves the matrix type
   *
   * @memberOf DenseMatrix
   * @return {string}   type information; if multiple types are found from the Matrix, it will return "mixed"
   */
  DenseMatrix.prototype.getDataType = function () {
    return getArrayDataType(this._data, typeOf);
  };

  /**
   * Get the storage format used by the matrix.
   *
   * Usage:
   *     const format = matrix.storage()  // retrieve storage format
   *
   * @memberof DenseMatrix
   * @return {string}           The storage format.
   */
  DenseMatrix.prototype.storage = function () {
    return 'dense';
  };

  /**
   * Get the datatype of the data stored in the matrix.
   *
   * Usage:
   *     const format = matrix.datatype()   // retrieve matrix datatype
   *
   * @memberof DenseMatrix
   * @return {string}           The datatype.
   */
  DenseMatrix.prototype.datatype = function () {
    return this._datatype;
  };

  /**
   * Create a new DenseMatrix
   * @memberof DenseMatrix
   * @param {Array} data
   * @param {string} [datatype]
   */
  DenseMatrix.prototype.create = function (data, datatype) {
    return new DenseMatrix(data, datatype);
  };

  /**
   * Get a subset of the matrix, or replace a subset of the matrix.
   *
   * Usage:
   *     const subset = matrix.subset(index)               // retrieve subset
   *     const value = matrix.subset(index, replacement)   // replace subset
   *
   * @memberof DenseMatrix
   * @param {Index} index
   * @param {Array | Matrix | *} [replacement]
   * @param {*} [defaultValue=0]      Default value, filled in on new entries when
   *                                  the matrix is resized. If not provided,
   *                                  new matrix elements will be filled with zeros.
   */
  DenseMatrix.prototype.subset = function (index, replacement, defaultValue) {
    switch (arguments.length) {
      case 1:
        return _get(this, index);

      // intentional fall through
      case 2:
      case 3:
        return _set(this, index, replacement, defaultValue);
      default:
        throw new SyntaxError('Wrong number of arguments');
    }
  };

  /**
   * Get a single element from the matrix.
   * @memberof DenseMatrix
   * @param {number[]} index   Zero-based index
   * @return {*} value
   */
  DenseMatrix.prototype.get = function (index) {
    if (!isArray(index)) {
      throw new TypeError('Array expected');
    }
    if (index.length !== this._size.length) {
      throw new DimensionError(index.length, this._size.length);
    }

    // check index
    for (var x = 0; x < index.length; x++) {
      validateIndex(index[x], this._size[x]);
    }
    var data = this._data;
    for (var i = 0, ii = index.length; i < ii; i++) {
      var indexI = index[i];
      validateIndex(indexI, data.length);
      data = data[indexI];
    }
    return data;
  };

  /**
   * Replace a single element in the matrix.
   * @memberof DenseMatrix
   * @param {number[]} index   Zero-based index
   * @param {*} value
   * @param {*} [defaultValue]        Default value, filled in on new entries when
   *                                  the matrix is resized. If not provided,
   *                                  new matrix elements will be left undefined.
   * @return {DenseMatrix} self
   */
  DenseMatrix.prototype.set = function (index, value, defaultValue) {
    if (!isArray(index)) {
      throw new TypeError('Array expected');
    }
    if (index.length < this._size.length) {
      throw new DimensionError(index.length, this._size.length, '<');
    }
    var i, ii, indexI;

    // enlarge matrix when needed
    var size = index.map(function (i) {
      return i + 1;
    });
    _fit(this, size, defaultValue);

    // traverse over the dimensions
    var data = this._data;
    for (i = 0, ii = index.length - 1; i < ii; i++) {
      indexI = index[i];
      validateIndex(indexI, data.length);
      data = data[indexI];
    }

    // set new value
    indexI = index[index.length - 1];
    validateIndex(indexI, data.length);
    data[indexI] = value;
    return this;
  };

  /**
   * Get a submatrix of this matrix
   * @memberof DenseMatrix
   * @param {DenseMatrix} matrix
   * @param {Index} index   Zero-based index
   * @private
   */
  function _get(matrix, index) {
    if (!isIndex(index)) {
      throw new TypeError('Invalid index');
    }
    var isScalar = index.isScalar();
    if (isScalar) {
      // return a scalar
      return matrix.get(index.min());
    } else {
      // validate dimensions
      var size = index.size();
      if (size.length !== matrix._size.length) {
        throw new DimensionError(size.length, matrix._size.length);
      }

      // validate if any of the ranges in the index is out of range
      var min = index.min();
      var max = index.max();
      for (var i = 0, ii = matrix._size.length; i < ii; i++) {
        validateIndex(min[i], matrix._size[i]);
        validateIndex(max[i], matrix._size[i]);
      }

      // retrieve submatrix
      // TODO: more efficient when creating an empty matrix and setting _data and _size manually
      return new DenseMatrix(_getSubmatrix(matrix._data, index, size.length, 0), matrix._datatype);
    }
  }

  /**
   * Recursively get a submatrix of a multi dimensional matrix.
   * Index is not checked for correct number or length of dimensions.
   * @memberof DenseMatrix
   * @param {Array} data
   * @param {Index} index
   * @param {number} dims   Total number of dimensions
   * @param {number} dim    Current dimension
   * @return {Array} submatrix
   * @private
   */
  function _getSubmatrix(data, index, dims, dim) {
    var last = dim === dims - 1;
    var range = index.dimension(dim);
    if (last) {
      return range.map(function (i) {
        validateIndex(i, data.length);
        return data[i];
      }).valueOf();
    } else {
      return range.map(function (i) {
        validateIndex(i, data.length);
        var child = data[i];
        return _getSubmatrix(child, index, dims, dim + 1);
      }).valueOf();
    }
  }

  /**
   * Replace a submatrix in this matrix
   * Indexes are zero-based.
   * @memberof DenseMatrix
   * @param {DenseMatrix} matrix
   * @param {Index} index
   * @param {DenseMatrix | Array | *} submatrix
   * @param {*} defaultValue          Default value, filled in on new entries when
   *                                  the matrix is resized.
   * @return {DenseMatrix} matrix
   * @private
   */
  function _set(matrix, index, submatrix, defaultValue) {
    if (!index || index.isIndex !== true) {
      throw new TypeError('Invalid index');
    }

    // get index size and check whether the index contains a single value
    var iSize = index.size();
    var isScalar = index.isScalar();

    // calculate the size of the submatrix, and convert it into an Array if needed
    var sSize;
    if (isMatrix(submatrix)) {
      sSize = submatrix.size();
      submatrix = submatrix.valueOf();
    } else {
      sSize = arraySize(submatrix);
    }
    if (isScalar) {
      // set a scalar

      // check whether submatrix is a scalar
      if (sSize.length !== 0) {
        throw new TypeError('Scalar expected');
      }
      matrix.set(index.min(), submatrix, defaultValue);
    } else {
      // set a submatrix

      // broadcast submatrix
      if (!deepStrictEqual(sSize, iSize)) {
        try {
          if (sSize.length === 0) {
            submatrix = broadcastTo([submatrix], iSize);
          } else {
            submatrix = broadcastTo(submatrix, iSize);
          }
          sSize = arraySize(submatrix);
        } catch (_unused) {}
      }

      // validate dimensions
      if (iSize.length < matrix._size.length) {
        throw new DimensionError(iSize.length, matrix._size.length, '<');
      }
      if (sSize.length < iSize.length) {
        // calculate number of missing outer dimensions
        var i = 0;
        var outer = 0;
        while (iSize[i] === 1 && sSize[i] === 1) {
          i++;
        }
        while (iSize[i] === 1) {
          outer++;
          i++;
        }

        // unsqueeze both outer and inner dimensions
        submatrix = unsqueeze(submatrix, iSize.length, outer, sSize);
      }

      // check whether the size of the submatrix matches the index size
      if (!deepStrictEqual(iSize, sSize)) {
        throw new DimensionError(iSize, sSize, '>');
      }

      // enlarge matrix when needed
      var size = index.max().map(function (i) {
        return i + 1;
      });
      _fit(matrix, size, defaultValue);

      // insert the sub matrix
      var dims = iSize.length;
      var dim = 0;
      _setSubmatrix(matrix._data, index, submatrix, dims, dim);
    }
    return matrix;
  }

  /**
   * Replace a submatrix of a multi dimensional matrix.
   * @memberof DenseMatrix
   * @param {Array} data
   * @param {Index} index
   * @param {Array} submatrix
   * @param {number} dims   Total number of dimensions
   * @param {number} dim
   * @private
   */
  function _setSubmatrix(data, index, submatrix, dims, dim) {
    var last = dim === dims - 1;
    var range = index.dimension(dim);
    if (last) {
      range.forEach(function (dataIndex, subIndex) {
        validateIndex(dataIndex);
        data[dataIndex] = submatrix[subIndex[0]];
      });
    } else {
      range.forEach(function (dataIndex, subIndex) {
        validateIndex(dataIndex);
        _setSubmatrix(data[dataIndex], index, submatrix[subIndex[0]], dims, dim + 1);
      });
    }
  }

  /**
   * Resize the matrix to the given size. Returns a copy of the matrix when
   * `copy=true`, otherwise return the matrix itself (resize in place).
   *
   * @memberof DenseMatrix
   * @param {number[] || Matrix} size The new size the matrix should have.
   * @param {*} [defaultValue=0]      Default value, filled in on new entries.
   *                                  If not provided, the matrix elements will
   *                                  be filled with zeros.
   * @param {boolean} [copy]          Return a resized copy of the matrix
   *
   * @return {Matrix}                 The resized matrix
   */
  DenseMatrix.prototype.resize = function (size, defaultValue, copy) {
    // validate arguments
    if (!isCollection(size)) {
      throw new TypeError('Array or Matrix expected');
    }

    // SparseMatrix input is always 2d, flatten this into 1d if it's indeed a vector
    var sizeArray = size.valueOf().map(value => {
      return Array.isArray(value) && value.length === 1 ? value[0] : value;
    });

    // matrix to resize
    var m = copy ? this.clone() : this;
    // resize matrix
    return _resize(m, sizeArray, defaultValue);
  };
  function _resize(matrix, size, defaultValue) {
    // check size
    if (size.length === 0) {
      // first value in matrix
      var v = matrix._data;
      // go deep
      while (isArray(v)) {
        v = v[0];
      }
      return v;
    }
    // resize matrix
    matrix._size = size.slice(0); // copy the array
    matrix._data = resize(matrix._data, matrix._size, defaultValue);
    // return matrix
    return matrix;
  }

  /**
   * Reshape the matrix to the given size. Returns a copy of the matrix when
   * `copy=true`, otherwise return the matrix itself (reshape in place).
   *
   * NOTE: This might be better suited to copy by default, instead of modifying
   *       in place. For now, it operates in place to remain consistent with
   *       resize().
   *
   * @memberof DenseMatrix
   * @param {number[]} size           The new size the matrix should have.
   * @param {boolean} [copy]          Return a reshaped copy of the matrix
   *
   * @return {Matrix}                 The reshaped matrix
   */
  DenseMatrix.prototype.reshape = function (size, copy) {
    var m = copy ? this.clone() : this;
    m._data = reshape(m._data, size);
    var currentLength = m._size.reduce((length, size) => length * size);
    m._size = processSizesWildcard(size, currentLength);
    return m;
  };

  /**
   * Enlarge the matrix when it is smaller than given size.
   * If the matrix is larger or equal sized, nothing is done.
   * @memberof DenseMatrix
   * @param {DenseMatrix} matrix           The matrix to be resized
   * @param {number[]} size
   * @param {*} defaultValue          Default value, filled in on new entries.
   * @private
   */
  function _fit(matrix, size, defaultValue) {
    var
    // copy the array
    newSize = matrix._size.slice(0);
    var changed = false;

    // add dimensions when needed
    while (newSize.length < size.length) {
      newSize.push(0);
      changed = true;
    }

    // enlarge size when needed
    for (var i = 0, ii = size.length; i < ii; i++) {
      if (size[i] > newSize[i]) {
        newSize[i] = size[i];
        changed = true;
      }
    }
    if (changed) {
      // resize only when size is changed
      _resize(matrix, newSize, defaultValue);
    }
  }

  /**
   * Create a clone of the matrix
   * @memberof DenseMatrix
   * @return {DenseMatrix} clone
   */
  DenseMatrix.prototype.clone = function () {
    var m = new DenseMatrix({
      data: clone$2(this._data),
      size: clone$2(this._size),
      datatype: this._datatype
    });
    return m;
  };

  /**
   * Retrieve the size of the matrix.
   * @memberof DenseMatrix
   * @returns {number[]} size
   */
  DenseMatrix.prototype.size = function () {
    return this._size.slice(0); // return a clone of _size
  };

  /**
   * Create a new matrix with the results of the callback function executed on
   * each entry of the matrix.
   * @memberof DenseMatrix
   * @param {Function} callback   The callback function is invoked with three
   *                              parameters: the value of the element, the index
   *                              of the element, and the Matrix being traversed.
   *
   * @return {DenseMatrix} matrix
   */
  DenseMatrix.prototype.map = function (callback) {
    // matrix instance
    var me = this;
    var args = maxArgumentCount(callback);
    var recurse = function recurse(value, index) {
      if (isArray(value)) {
        return value.map(function (child, i) {
          return recurse(child, index.concat(i));
        });
      } else {
        // invoke the callback function with the right number of arguments
        if (args === 1) {
          return callback(value);
        } else if (args === 2) {
          return callback(value, index);
        } else {
          // 3 or -1
          return callback(value, index, me);
        }
      }
    };

    // determine the new datatype when the original matrix has datatype defined
    // TODO: should be done in matrix constructor instead
    var data = recurse(this._data, []);
    var datatype = this._datatype !== undefined ? getArrayDataType(data, typeOf) : undefined;
    return new DenseMatrix(data, datatype);
  };

  /**
   * Execute a callback function on each entry of the matrix.
   * @memberof DenseMatrix
   * @param {Function} callback   The callback function is invoked with three
   *                              parameters: the value of the element, the index
   *                              of the element, and the Matrix being traversed.
   */
  DenseMatrix.prototype.forEach = function (callback) {
    // matrix instance
    var me = this;
    var recurse = function recurse(value, index) {
      if (isArray(value)) {
        value.forEach(function (child, i) {
          recurse(child, index.concat(i));
        });
      } else {
        callback(value, index, me);
      }
    };
    recurse(this._data, []);
  };

  /**
   * Iterate over the matrix elements
   * @return {Iterable<{ value, index: number[] }>}
   */
  DenseMatrix.prototype[Symbol.iterator] = function* () {
    var recurse = function* recurse(value, index) {
      if (isArray(value)) {
        for (var i = 0; i < value.length; i++) {
          yield* recurse(value[i], index.concat(i));
        }
      } else {
        yield {
          value,
          index
        };
      }
    };
    yield* recurse(this._data, []);
  };

  /**
   * Returns an array containing the rows of a 2D matrix
   * @returns {Array<Matrix>}
   */
  DenseMatrix.prototype.rows = function () {
    var result = [];
    var s = this.size();
    if (s.length !== 2) {
      throw new TypeError('Rows can only be returned for a 2D matrix.');
    }
    var data = this._data;
    for (var row of data) {
      result.push(new DenseMatrix([row], this._datatype));
    }
    return result;
  };

  /**
   * Returns an array containing the columns of a 2D matrix
   * @returns {Array<Matrix>}
   */
  DenseMatrix.prototype.columns = function () {
    var _this = this;
    var result = [];
    var s = this.size();
    if (s.length !== 2) {
      throw new TypeError('Rows can only be returned for a 2D matrix.');
    }
    var data = this._data;
    var _loop = function _loop(i) {
      var col = data.map(row => [row[i]]);
      result.push(new DenseMatrix(col, _this._datatype));
    };
    for (var i = 0; i < s[1]; i++) {
      _loop(i);
    }
    return result;
  };

  /**
   * Create an Array with a copy of the data of the DenseMatrix
   * @memberof DenseMatrix
   * @returns {Array} array
   */
  DenseMatrix.prototype.toArray = function () {
    return clone$2(this._data);
  };

  /**
   * Get the primitive value of the DenseMatrix: a multidimensional array
   * @memberof DenseMatrix
   * @returns {Array} array
   */
  DenseMatrix.prototype.valueOf = function () {
    return this._data;
  };

  /**
   * Get a string representation of the matrix, with optional formatting options.
   * @memberof DenseMatrix
   * @param {Object | number | Function} [options]  Formatting options. See
   *                                                lib/utils/number:format for a
   *                                                description of the available
   *                                                options.
   * @returns {string} str
   */
  DenseMatrix.prototype.format = function (options) {
    return format(this._data, options);
  };

  /**
   * Get a string representation of the matrix
   * @memberof DenseMatrix
   * @returns {string} str
   */
  DenseMatrix.prototype.toString = function () {
    return format(this._data);
  };

  /**
   * Get a JSON representation of the matrix
   * @memberof DenseMatrix
   * @returns {Object}
   */
  DenseMatrix.prototype.toJSON = function () {
    return {
      mathjs: 'DenseMatrix',
      data: this._data,
      size: this._size,
      datatype: this._datatype
    };
  };

  /**
   * Get the kth Matrix diagonal.
   *
   * @memberof DenseMatrix
   * @param {number | BigNumber} [k=0]     The kth diagonal where the vector will retrieved.
   *
   * @returns {Matrix}                     The matrix with the diagonal values.
   */
  DenseMatrix.prototype.diagonal = function (k) {
    // validate k if any
    if (k) {
      // convert BigNumber to a number
      if (isBigNumber(k)) {
        k = k.toNumber();
      }
      // is must be an integer
      if (!isNumber(k) || !isInteger(k)) {
        throw new TypeError('The parameter k must be an integer number');
      }
    } else {
      // default value
      k = 0;
    }
    var kSuper = k > 0 ? k : 0;
    var kSub = k < 0 ? -k : 0;

    // rows & columns
    var rows = this._size[0];
    var columns = this._size[1];

    // number diagonal values
    var n = Math.min(rows - kSub, columns - kSuper);

    // x is a matrix get diagonal from matrix
    var data = [];

    // loop rows
    for (var i = 0; i < n; i++) {
      data[i] = this._data[i + kSub][i + kSuper];
    }

    // create DenseMatrix
    return new DenseMatrix({
      data,
      size: [n],
      datatype: this._datatype
    });
  };

  /**
   * Create a diagonal matrix.
   *
   * @memberof DenseMatrix
   * @param {Array} size                     The matrix size.
   * @param {number | Matrix | Array } value The values for the diagonal.
   * @param {number | BigNumber} [k=0]       The kth diagonal where the vector will be filled in.
   * @param {number} [defaultValue]          The default value for non-diagonal
   * @param {string} [datatype]              The datatype for the diagonal
   *
   * @returns {DenseMatrix}
   */
  DenseMatrix.diagonal = function (size, value, k, defaultValue) {
    if (!isArray(size)) {
      throw new TypeError('Array expected, size parameter');
    }
    if (size.length !== 2) {
      throw new Error('Only two dimensions matrix are supported');
    }

    // map size & validate
    size = size.map(function (s) {
      // check it is a big number
      if (isBigNumber(s)) {
        // convert it
        s = s.toNumber();
      }
      // validate arguments
      if (!isNumber(s) || !isInteger(s) || s < 1) {
        throw new Error('Size values must be positive integers');
      }
      return s;
    });

    // validate k if any
    if (k) {
      // convert BigNumber to a number
      if (isBigNumber(k)) {
        k = k.toNumber();
      }
      // is must be an integer
      if (!isNumber(k) || !isInteger(k)) {
        throw new TypeError('The parameter k must be an integer number');
      }
    } else {
      // default value
      k = 0;
    }
    var kSuper = k > 0 ? k : 0;
    var kSub = k < 0 ? -k : 0;

    // rows and columns
    var rows = size[0];
    var columns = size[1];

    // number of non-zero items
    var n = Math.min(rows - kSub, columns - kSuper);

    // value extraction function
    var _value;

    // check value
    if (isArray(value)) {
      // validate array
      if (value.length !== n) {
        // number of values in array must be n
        throw new Error('Invalid value array length');
      }
      // define function
      _value = function _value(i) {
        // return value @ i
        return value[i];
      };
    } else if (isMatrix(value)) {
      // matrix size
      var ms = value.size();
      // validate matrix
      if (ms.length !== 1 || ms[0] !== n) {
        // number of values in array must be n
        throw new Error('Invalid matrix length');
      }
      // define function
      _value = function _value(i) {
        // return value @ i
        return value.get([i]);
      };
    } else {
      // define function
      _value = function _value() {
        // return value
        return value;
      };
    }

    // discover default value if needed
    if (!defaultValue) {
      // check first value in array
      defaultValue = isBigNumber(_value(0)) ? _value(0).mul(0) // trick to create a BigNumber with value zero
      : 0;
    }

    // empty array
    var data = [];

    // check we need to resize array
    if (size.length > 0) {
      // resize array
      data = resize(data, size, defaultValue);
      // fill diagonal
      for (var d = 0; d < n; d++) {
        data[d + kSub][d + kSuper] = _value(d);
      }
    }

    // create DenseMatrix
    return new DenseMatrix({
      data,
      size: [rows, columns]
    });
  };

  /**
   * Generate a matrix from a JSON object
   * @memberof DenseMatrix
   * @param {Object} json  An object structured like
   *                       `{"mathjs": "DenseMatrix", data: [], size: []}`,
   *                       where mathjs is optional
   * @returns {DenseMatrix}
   */
  DenseMatrix.fromJSON = function (json) {
    return new DenseMatrix(json);
  };

  /**
   * Swap rows i and j in Matrix.
   *
   * @memberof DenseMatrix
   * @param {number} i       Matrix row index 1
   * @param {number} j       Matrix row index 2
   *
   * @return {Matrix}        The matrix reference
   */
  DenseMatrix.prototype.swapRows = function (i, j) {
    // check index
    if (!isNumber(i) || !isInteger(i) || !isNumber(j) || !isInteger(j)) {
      throw new Error('Row index must be positive integers');
    }
    // check dimensions
    if (this._size.length !== 2) {
      throw new Error('Only two dimensional matrix is supported');
    }
    // validate index
    validateIndex(i, this._size[0]);
    validateIndex(j, this._size[0]);

    // swap rows
    DenseMatrix._swapRows(i, j, this._data);
    // return current instance
    return this;
  };

  /**
   * Swap rows i and j in Dense Matrix data structure.
   *
   * @param {number} i       Matrix row index 1
   * @param {number} j       Matrix row index 2
   * @param {Array} data     Matrix data
   */
  DenseMatrix._swapRows = function (i, j, data) {
    // swap values i <-> j
    var vi = data[i];
    data[i] = data[j];
    data[j] = vi;
  };

  /**
   * Preprocess data, which can be an Array or DenseMatrix with nested Arrays and
   * Matrices. Clones all (nested) Arrays, and replaces all nested Matrices with Arrays
   * @memberof DenseMatrix
   * @param {Array | Matrix} data
   * @return {Array} data
   */
  function preprocess(data) {
    if (isMatrix(data)) {
      return preprocess(data.valueOf());
    }
    if (isArray(data)) {
      return data.map(preprocess);
    }
    return data;
  }
  return DenseMatrix;
}, {
  isClass: true
});

var name$4O = 'clone';
var dependencies$4N = ['typed'];
var createClone = /* #__PURE__ */factory(name$4O, dependencies$4N, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Clone an object. Will make a deep copy of the data.
   *
   * Syntax:
   *
   *     math.clone(x)
   *
   * Examples:
   *
   *    math.clone(3.5)                   // returns number 3.5
   *    math.clone(math.complex('2-4i'))  // returns Complex 2 - 4i
   *    math.clone(math.unit(45, 'deg'))  // returns Unit 45 deg
   *    math.clone([[1, 2], [3, 4]])      // returns Array [[1, 2], [3, 4]]
   *    math.clone("hello world")         // returns string "hello world"
   *
   * @param {*} x   Object to be cloned
   * @return {*} A clone of object x
   */
  return typed(name$4O, {
    any: clone$2
  });
});

/**
 * Transpose a matrix
 * @param {Array} mat
 * @returns {Array} ret
 * @private
 */
function _switch$1(mat) {
  var I = mat.length;
  var J = mat[0].length;
  var i, j;
  var ret = [];
  for (j = 0; j < J; j++) {
    var tmp = [];
    for (i = 0; i < I; i++) {
      tmp.push(mat[i][j]);
    }
    ret.push(tmp);
  }
  return ret;
}

/**
 * Test whether an array contains collections
 * @param {Array} array
 * @returns {boolean} Returns true when the array contains one or multiple
 *                    collections (Arrays or Matrices). Returns false otherwise.
 */
function containsCollections(array) {
  for (var i = 0; i < array.length; i++) {
    if (isCollection(array[i])) {
      return true;
    }
  }
  return false;
}

/**
 * Recursively loop over all elements in a given multi dimensional array
 * and invoke the callback on each of the elements.
 * @param {Array | Matrix} array
 * @param {Function} callback     The callback method is invoked with one
 *                                parameter: the current element in the array
 */
function deepForEach(array, callback) {
  if (isMatrix(array)) {
    array = array.valueOf();
  }
  for (var i = 0, ii = array.length; i < ii; i++) {
    var value = array[i];
    if (Array.isArray(value)) {
      deepForEach(value, callback);
    } else {
      callback(value);
    }
  }
}

/**
 * Execute the callback function element wise for each element in array and any
 * nested array
 * Returns an array with the results
 * @param {Array | Matrix} array
 * @param {Function} callback   The callback is called with two parameters:
 *                              value1 and value2, which contain the current
 *                              element of both arrays.
 * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.
 *
 * @return {Array | Matrix} res
 */
function deepMap(array, callback, skipZeros) {
  if (array && typeof array.map === 'function') {
    // TODO: replace array.map with a for loop to improve performance
    return array.map(function (x) {
      return deepMap(x, callback);
    });
  } else {
    return callback(array);
  }
}

/**
 * Reduce a given matrix or array to a new matrix or
 * array with one less dimension, applying the given
 * callback in the selected dimension.
 * @param {Array | Matrix} mat
 * @param {number} dim
 * @param {Function} callback
 * @return {Array | Matrix} res
 */
function reduce(mat, dim, callback) {
  var size = Array.isArray(mat) ? arraySize(mat) : mat.size();
  if (dim < 0 || dim >= size.length) {
    // TODO: would be more clear when throwing a DimensionError here
    throw new IndexError(dim, size.length);
  }
  if (isMatrix(mat)) {
    return mat.create(_reduce(mat.valueOf(), dim, callback));
  } else {
    return _reduce(mat, dim, callback);
  }
}

/**
 * Recursively reduce a matrix
 * @param {Array} mat
 * @param {number} dim
 * @param {Function} callback
 * @returns {Array} ret
 * @private
 */
function _reduce(mat, dim, callback) {
  var i, ret, val, tran;
  if (dim <= 0) {
    if (!Array.isArray(mat[0])) {
      val = mat[0];
      for (i = 1; i < mat.length; i++) {
        val = callback(val, mat[i]);
      }
      return val;
    } else {
      tran = _switch$1(mat);
      ret = [];
      for (i = 0; i < tran.length; i++) {
        ret[i] = _reduce(tran[i], dim - 1, callback);
      }
      return ret;
    }
  } else {
    ret = [];
    for (i = 0; i < mat.length; i++) {
      ret[i] = _reduce(mat[i], dim - 1, callback);
    }
    return ret;
  }
}

// TODO: document function scatter
function scatter(a, j, w, x, u, mark, cindex, f, inverse, update, value) {
  // a arrays
  var avalues = a._values;
  var aindex = a._index;
  var aptr = a._ptr;

  // vars
  var k, k0, k1, i;

  // check we need to process values (pattern matrix)
  if (x) {
    // values in j
    for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
      // row
      i = aindex[k];
      // check value exists in current j
      if (w[i] !== mark) {
        // i is new entry in j
        w[i] = mark;
        // add i to pattern of C
        cindex.push(i);
        // x(i) = A, check we need to call function this time
        if (update) {
          // copy value to workspace calling callback function
          x[i] = inverse ? f(avalues[k], value) : f(value, avalues[k]);
          // function was called on current row
          u[i] = mark;
        } else {
          // copy value to workspace
          x[i] = avalues[k];
        }
      } else {
        // i exists in C already
        x[i] = inverse ? f(avalues[k], x[i]) : f(x[i], avalues[k]);
        // function was called on current row
        u[i] = mark;
      }
    }
  } else {
    // values in j
    for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
      // row
      i = aindex[k];
      // check value exists in current j
      if (w[i] !== mark) {
        // i is new entry in j
        w[i] = mark;
        // add i to pattern of C
        cindex.push(i);
      } else {
        // indicate function was called on current row
        u[i] = mark;
      }
    }
  }
}

var name$4N = 'isInteger';
var dependencies$4M = ['typed'];
var createIsInteger = /* #__PURE__ */factory(name$4N, dependencies$4M, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Test whether a value is an integer number.
   * The function supports `number`, `BigNumber`, and `Fraction`.
   *
   * The function is evaluated element-wise in case of Array or Matrix input.
   *
   * Syntax:
   *
   *     math.isInteger(x)
   *
   * Examples:
   *
   *    math.isInteger(2)                     // returns true
   *    math.isInteger(0)                     // returns true
   *    math.isInteger(0.5)                   // returns false
   *    math.isInteger(math.bignumber(500))   // returns true
   *    math.isInteger(math.fraction(4))      // returns true
   *    math.isInteger('3')                   // returns true
   *    math.isInteger([3, 0.5, -2])          // returns [true, false, true]
   *    math.isInteger(math.complex('2-4i'))  // throws an error
   *
   * See also:
   *
   *    isNumeric, isPositive, isNegative, isZero
   *
   * @param {number | BigNumber | bigint | Fraction | Array | Matrix} x   Value to be tested
   * @return {boolean}  Returns true when `x` contains a numeric, integer value.
   *                    Throws an error in case of an unknown data type.
   */
  return typed(name$4N, {
    number: isInteger,
    // TODO: what to do with isInteger(add(0.1, 0.2))  ?

    BigNumber: function BigNumber(x) {
      return x.isInt();
    },
    bigint: function bigint(x) {
      return true;
    },
    Fraction: function Fraction(x) {
      return x.d === 1 && isFinite(x.n);
    },
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var n1$4 = 'number';
var n2$2 = 'number, number';
function absNumber(a) {
  return Math.abs(a);
}
absNumber.signature = n1$4;
function addNumber(a, b) {
  return a + b;
}
addNumber.signature = n2$2;
function subtractNumber(a, b) {
  return a - b;
}
subtractNumber.signature = n2$2;
function multiplyNumber(a, b) {
  return a * b;
}
multiplyNumber.signature = n2$2;
function unaryMinusNumber(x) {
  return -x;
}
unaryMinusNumber.signature = n1$4;
function unaryPlusNumber(x) {
  return x;
}
unaryPlusNumber.signature = n1$4;
function cbrtNumber(x) {
  return cbrt$1(x);
}
cbrtNumber.signature = n1$4;
function cubeNumber(x) {
  return x * x * x;
}
cubeNumber.signature = n1$4;
function expNumber(x) {
  return Math.exp(x);
}
expNumber.signature = n1$4;
function expm1Number(x) {
  return expm1(x);
}
expm1Number.signature = n1$4;

/**
 * Calculate lcm for two numbers
 * @param {number} a
 * @param {number} b
 * @returns {number} Returns the least common multiple of a and b
 */
function lcmNumber(a, b) {
  if (!isInteger(a) || !isInteger(b)) {
    throw new Error('Parameters in function lcm must be integer numbers');
  }
  if (a === 0 || b === 0) {
    return 0;
  }

  // https://en.wikipedia.org/wiki/Euclidean_algorithm
  // evaluate lcm here inline to reduce overhead
  var t;
  var prod = a * b;
  while (b !== 0) {
    t = b;
    b = a % t;
    a = t;
  }
  return Math.abs(prod / a);
}
lcmNumber.signature = n2$2;

/**
 * Calculate the logarithm of a value, optionally to a given base.
 * @param {number} x
 * @param {number | null | undefined} base
 * @return {number}
 */
function logNumber(x, y) {
  if (y) {
    return Math.log(x) / Math.log(y);
  }
  return Math.log(x);
}

/**
 * Calculate the 10-base logarithm of a number
 * @param {number} x
 * @return {number}
 */
function log10Number(x) {
  return log10$1(x);
}
log10Number.signature = n1$4;

/**
 * Calculate the 2-base logarithm of a number
 * @param {number} x
 * @return {number}
 */
function log2Number(x) {
  return log2$1(x);
}
log2Number.signature = n1$4;

/**
 * Calculate the nth root of a, solve x^root == a
 * http://rosettacode.org/wiki/Nth_root#JavaScript
 * @param {number} a
 * @param {number} [2] root
 * @private
 */
function nthRootNumber(a) {
  var root = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
  var inv = root < 0;
  if (inv) {
    root = -root;
  }
  if (root === 0) {
    throw new Error('Root must be non-zero');
  }
  if (a < 0 && Math.abs(root) % 2 !== 1) {
    throw new Error('Root must be odd when a is negative.');
  }

  // edge cases zero and infinity
  if (a === 0) {
    return inv ? Infinity : 0;
  }
  if (!isFinite(a)) {
    return inv ? 0 : a;
  }
  var x = Math.pow(Math.abs(a), 1 / root);
  // If a < 0, we require that root is an odd integer,
  // so (-1) ^ (1/root) = -1
  x = a < 0 ? -x : x;
  return inv ? 1 / x : x;

  // Very nice algorithm, but fails with nthRoot(-2, 3).
  // Newton's method has some well-known problems at times:
  // https://en.wikipedia.org/wiki/Newton%27s_method#Failure_analysis
  /*
  let x = 1 // Initial guess
  let xPrev = 1
  let i = 0
  const iMax = 10000
  do {
    const delta = (a / Math.pow(x, root - 1) - x) / root
    xPrev = x
    x = x + delta
    i++
  }
  while (xPrev !== x && i < iMax)
   if (xPrev !== x) {
    throw new Error('Function nthRoot failed to converge')
  }
   return inv ? 1 / x : x
  */
}
function signNumber(x) {
  return sign$1(x);
}
signNumber.signature = n1$4;
function squareNumber(x) {
  return x * x;
}
squareNumber.signature = n1$4;

/**
 * Calculate xgcd for two numbers
 * @param {number} a
 * @param {number} b
 * @return {number} result
 * @private
 */
function xgcdNumber(a, b) {
  // source: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
  var t; // used to swap two variables
  var q; // quotient
  var r; // remainder
  var x = 0;
  var lastx = 1;
  var y = 1;
  var lasty = 0;
  if (!isInteger(a) || !isInteger(b)) {
    throw new Error('Parameters in function xgcd must be integer numbers');
  }
  while (b) {
    q = Math.floor(a / b);
    r = a - q * b;
    t = x;
    x = lastx - q * x;
    lastx = t;
    t = y;
    y = lasty - q * y;
    lasty = t;
    a = b;
    b = r;
  }
  var res;
  if (a < 0) {
    res = [-a, -lastx, -lasty];
  } else {
    res = [a, a ? lastx : 0, lasty];
  }
  return res;
}
xgcdNumber.signature = n2$2;

/**
 * Calculates the power of x to y, x^y, for two numbers.
 * @param {number} x
 * @param {number} y
 * @return {number} res
 */
function powNumber(x, y) {
  // x^Infinity === 0 if -1 < x < 1
  // A real number 0 is returned instead of complex(0)
  if (x * x < 1 && y === Infinity || x * x > 1 && y === -Infinity) {
    return 0;
  }
  return Math.pow(x, y);
}
powNumber.signature = n2$2;

/**
 * round a number to the given number of decimals, or to zero if decimals is
 * not provided
 * @param {number} value
 * @param {number} decimals       number of decimals, between 0 and 15 (0 by default)
 * @return {number} roundedValue
 */
function roundNumber(value) {
  var decimals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  if (!isInteger(decimals) || decimals < 0 || decimals > 15) {
    throw new Error('Number of decimals in function round must be an integer from 0 to 15 inclusive');
  }
  return parseFloat(toFixed$1(value, decimals));
}

var n1$3 = 'number';
var n2$1 = 'number, number';
function bitAndNumber(x, y) {
  if (!isInteger(x) || !isInteger(y)) {
    throw new Error('Integers expected in function bitAnd');
  }
  return x & y;
}
bitAndNumber.signature = n2$1;
function bitNotNumber(x) {
  if (!isInteger(x)) {
    throw new Error('Integer expected in function bitNot');
  }
  return ~x;
}
bitNotNumber.signature = n1$3;
function bitOrNumber(x, y) {
  if (!isInteger(x) || !isInteger(y)) {
    throw new Error('Integers expected in function bitOr');
  }
  return x | y;
}
bitOrNumber.signature = n2$1;
function bitXorNumber(x, y) {
  if (!isInteger(x) || !isInteger(y)) {
    throw new Error('Integers expected in function bitXor');
  }
  return x ^ y;
}
bitXorNumber.signature = n2$1;
function leftShiftNumber(x, y) {
  if (!isInteger(x) || !isInteger(y)) {
    throw new Error('Integers expected in function leftShift');
  }
  return x << y;
}
leftShiftNumber.signature = n2$1;
function rightArithShiftNumber(x, y) {
  if (!isInteger(x) || !isInteger(y)) {
    throw new Error('Integers expected in function rightArithShift');
  }
  return x >> y;
}
rightArithShiftNumber.signature = n2$1;
function rightLogShiftNumber(x, y) {
  if (!isInteger(x) || !isInteger(y)) {
    throw new Error('Integers expected in function rightLogShift');
  }
  return x >>> y;
}
rightLogShiftNumber.signature = n2$1;

/** @param {number} i
 *  @param {number} n
 *  @returns {number} product of i to n
 */
function product(i, n) {
  if (n < i) {
    return 1;
  }
  if (n === i) {
    return n;
  }
  var half = n + i >> 1; // divide (n + i) by 2 and truncate to integer
  return product(i, half) * product(half + 1, n);
}

function combinationsNumber(n, k) {
  if (!isInteger(n) || n < 0) {
    throw new TypeError('Positive integer value expected in function combinations');
  }
  if (!isInteger(k) || k < 0) {
    throw new TypeError('Positive integer value expected in function combinations');
  }
  if (k > n) {
    throw new TypeError('k must be less than or equal to n');
  }
  var nMinusk = n - k;
  var answer = 1;
  var firstnumerator = k < nMinusk ? nMinusk + 1 : k + 1;
  var nextdivisor = 2;
  var lastdivisor = k < nMinusk ? k : nMinusk;
  // balance multiplications and divisions to try to keep intermediate values
  // in exact-integer range as long as possible
  for (var nextnumerator = firstnumerator; nextnumerator <= n; ++nextnumerator) {
    answer *= nextnumerator;
    while (nextdivisor <= lastdivisor && answer % nextdivisor === 0) {
      answer /= nextdivisor;
      ++nextdivisor;
    }
  }
  // for big n, k, floating point may have caused weirdness in remainder
  if (nextdivisor <= lastdivisor) {
    answer /= product(nextdivisor, lastdivisor);
  }
  return answer;
}
combinationsNumber.signature = 'number, number';

var pi = Math.PI;
var tau = 2 * Math.PI;
var e = Math.E;
var phi = 1.6180339887498948; // eslint-disable-line no-loss-of-precision

var n1$2 = 'number';
var n2 = 'number, number';
function notNumber(x) {
  return !x;
}
notNumber.signature = n1$2;
function orNumber(x, y) {
  return !!(x || y);
}
orNumber.signature = n2;
function xorNumber(x, y) {
  return !!x !== !!y;
}
xorNumber.signature = n2;
function andNumber(x, y) {
  return !!(x && y);
}
andNumber.signature = n2;

/* eslint-disable no-loss-of-precision */
function gammaNumber(n) {
  var x;
  if (isInteger(n)) {
    if (n <= 0) {
      return isFinite(n) ? Infinity : NaN;
    }
    if (n > 171) {
      return Infinity; // Will overflow
    }
    return product(1, n - 1);
  }
  if (n < 0.5) {
    return Math.PI / (Math.sin(Math.PI * n) * gammaNumber(1 - n));
  }
  if (n >= 171.35) {
    return Infinity; // will overflow
  }
  if (n > 85.0) {
    // Extended Stirling Approx
    var twoN = n * n;
    var threeN = twoN * n;
    var fourN = threeN * n;
    var fiveN = fourN * n;
    return Math.sqrt(2 * Math.PI / n) * Math.pow(n / Math.E, n) * (1 + 1 / (12 * n) + 1 / (288 * twoN) - 139 / (51840 * threeN) - 571 / (2488320 * fourN) + 163879 / (209018880 * fiveN) + 5246819 / (75246796800 * fiveN * n));
  }
  --n;
  x = gammaP[0];
  for (var i = 1; i < gammaP.length; ++i) {
    x += gammaP[i] / (n + i);
  }
  var t = n + gammaG + 0.5;
  return Math.sqrt(2 * Math.PI) * Math.pow(t, n + 0.5) * Math.exp(-t) * x;
}
gammaNumber.signature = 'number';

// TODO: comment on the variables g and p

var gammaG = 4.7421875;
var gammaP = [0.99999999999999709182, 57.156235665862923517, -59.597960355475491248, 14.136097974741747174, -0.49191381609762019978, 0.33994649984811888699e-4, 0.46523628927048575665e-4, -0.98374475304879564677e-4, 0.15808870322491248884e-3, -0.21026444172410488319e-3, 0.21743961811521264320e-3, -0.16431810653676389022e-3, 0.84418223983852743293e-4, -0.26190838401581408670e-4, 0.36899182659531622704e-5];

// lgamma implementation ref: https://mrob.com/pub/ries/lanczos-gamma.html#code

// log(2 * pi) / 2
var lnSqrt2PI = 0.91893853320467274178;
var lgammaG = 5; // Lanczos parameter "g"
var lgammaN = 7; // Range of coefficients "n"

var lgammaSeries = [1.000000000190015, 76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5];
function lgammaNumber(n) {
  if (n < 0) return NaN;
  if (n === 0) return Infinity;
  if (!isFinite(n)) return n;
  if (n < 0.5) {
    // Use Euler's reflection formula:
    // gamma(z) = PI / (sin(PI * z) * gamma(1 - z))
    return Math.log(Math.PI / Math.sin(Math.PI * n)) - lgammaNumber(1 - n);
  }

  // Compute the logarithm of the Gamma function using the Lanczos method

  n = n - 1;
  var base = n + lgammaG + 0.5; // Base of the Lanczos exponential
  var sum = lgammaSeries[0];

  // We start with the terms that have the smallest coefficients and largest denominator
  for (var i = lgammaN - 1; i >= 1; i--) {
    sum += lgammaSeries[i] / (n + i);
  }
  return lnSqrt2PI + (n + 0.5) * Math.log(base) - base + Math.log(sum);
}
lgammaNumber.signature = 'number';

var n1$1 = 'number';
function acoshNumber(x) {
  return acosh$1(x);
}
acoshNumber.signature = n1$1;
function acotNumber(x) {
  return Math.atan(1 / x);
}
acotNumber.signature = n1$1;
function acothNumber(x) {
  return isFinite(x) ? (Math.log((x + 1) / x) + Math.log(x / (x - 1))) / 2 : 0;
}
acothNumber.signature = n1$1;
function acscNumber(x) {
  return Math.asin(1 / x);
}
acscNumber.signature = n1$1;
function acschNumber(x) {
  var xInv = 1 / x;
  return Math.log(xInv + Math.sqrt(xInv * xInv + 1));
}
acschNumber.signature = n1$1;
function asecNumber(x) {
  return Math.acos(1 / x);
}
asecNumber.signature = n1$1;
function asechNumber(x) {
  var xInv = 1 / x;
  var ret = Math.sqrt(xInv * xInv - 1);
  return Math.log(ret + xInv);
}
asechNumber.signature = n1$1;
function asinhNumber(x) {
  return asinh$1(x);
}
asinhNumber.signature = n1$1;
function atanhNumber(x) {
  return atanh$1(x);
}
atanhNumber.signature = n1$1;
function cotNumber(x) {
  return 1 / Math.tan(x);
}
cotNumber.signature = n1$1;
function cothNumber(x) {
  var e = Math.exp(2 * x);
  return (e + 1) / (e - 1);
}
cothNumber.signature = n1$1;
function cscNumber(x) {
  return 1 / Math.sin(x);
}
cscNumber.signature = n1$1;
function cschNumber(x) {
  // consider values close to zero (+/-)
  if (x === 0) {
    return Number.POSITIVE_INFINITY;
  } else {
    return Math.abs(2 / (Math.exp(x) - Math.exp(-x))) * sign$1(x);
  }
}
cschNumber.signature = n1$1;
function secNumber(x) {
  return 1 / Math.cos(x);
}
secNumber.signature = n1$1;
function sechNumber(x) {
  return 2 / (Math.exp(x) + Math.exp(-x));
}
sechNumber.signature = n1$1;
function sinhNumber(x) {
  return sinh$1(x);
}
sinhNumber.signature = n1$1;

var n1 = 'number';
function isNegativeNumber(x) {
  return x < 0;
}
isNegativeNumber.signature = n1;
function isPositiveNumber(x) {
  return x > 0;
}
isPositiveNumber.signature = n1;
function isNaNNumber(x) {
  return Number.isNaN(x);
}
isNaNNumber.signature = n1;

/**
 * Compares two BigNumbers.
 * @param {BigNumber} a - First value to compare
 * @param {BigNumber} b - Second value to compare
 * @param {number} [relTol=1e-09] - The relative tolerance, indicating the maximum allowed difference relative to the larger absolute value. Must be greater than 0.
 * @param {number} [absTol=0] - The minimum absolute tolerance, useful for comparisons near zero. Must be at least 0.
 * @returns {boolean} whether the two numbers are nearly equal
 * @throws {Error} If `relTol` is less than or equal to 0.
 * @throws {Error} If `absTol` is less than 0.
 *
 * @example
 * nearlyEqual(1.000000001, 1.0, 1e-9);            // true
 * nearlyEqual(1.000000002, 1.0, 0);            // false
 * nearlyEqual(1.0, 1.009, undefined, 0.02);       // true
 * nearlyEqual(0.000000001, 0.0, undefined, 1e-8); // true
 */
function nearlyEqual(a, b) {
  var relTol = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1e-9;
  var absTol = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  if (relTol <= 0) {
    throw new Error('Relative tolerance must be greater than 0');
  }
  if (absTol < 0) {
    throw new Error('Absolute tolerance must be at least 0');
  }
  // NaN
  if (a.isNaN() || b.isNaN()) {
    return false;
  }
  if (!a.isFinite() || !b.isFinite()) {
    return a.eq(b);
  }
  // use "==" operator, handles infinities
  if (a.eq(b)) {
    return true;
  }
  // abs(a-b) <= max(relTol * max(abs(a), abs(b)), absTol)
  return a.minus(b).abs().lte(a.constructor.max(a.constructor.max(a.abs(), b.abs()).mul(relTol), absTol));
}

var name$4M = 'isNegative';
var dependencies$4L = ['typed', 'config'];
var createIsNegative = /* #__PURE__ */factory(name$4M, dependencies$4L, _ref => {
  var {
    typed,
    config
  } = _ref;
  /**
   * Test whether a value is negative: smaller than zero.
   * The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`.
   *
   * The function is evaluated element-wise in case of Array or Matrix input.
   *
   * Syntax:
   *
   *     math.isNegative(x)
   *
   * Examples:
   *
   *    math.isNegative(3)                     // returns false
   *    math.isNegative(-2)                    // returns true
   *    math.isNegative(0)                     // returns false
   *    math.isNegative(-0)                    // returns false
   *    math.isNegative(math.bignumber(2))     // returns false
   *    math.isNegative(math.fraction(-2, 5))  // returns true
   *    math.isNegative('-2')                  // returns true
   *    math.isNegative([2, 0, -3])            // returns [false, false, true]
   *
   * See also:
   *
   *    isNumeric, isPositive, isZero, isInteger
   *
   * @param {number | BigNumber | bigint | Fraction | Unit | Array | Matrix} x  Value to be tested
   * @return {boolean}  Returns true when `x` is larger than zero.
   *                    Throws an error in case of an unknown data type.
   */
  return typed(name$4M, {
    number: x => nearlyEqual$1(x, 0, config.relTol, config.absTol) ? false : isNegativeNumber(x),
    BigNumber: x => nearlyEqual(x, new x.constructor(0), config.relTol, config.absTol) ? false : x.isNeg() && !x.isZero() && !x.isNaN(),
    bigint: x => x < 0n,
    Fraction: x => x.s < 0,
    // It's enough to decide on the sign

    Unit: typed.referToSelf(self => x => typed.find(self, x.valueType())(x.value)),
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$4L = 'isNumeric';
var dependencies$4K = ['typed'];
var createIsNumeric = /* #__PURE__ */factory(name$4L, dependencies$4K, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Test whether a value is an numeric value.
   *
   * The function is evaluated element-wise in case of Array or Matrix input.
   *
   * Syntax:
   *
   *     math.isNumeric(x)
   *
   * Examples:
   *
   *    math.isNumeric(2)                     // returns true
   *    math.isNumeric('2')                   // returns false
   *    math.hasNumericValue('2')             // returns true
   *    math.isNumeric(0)                     // returns true
   *    math.isNumeric(math.bignumber('42'))  // returns true
   *    math.isNumeric(math.bigint('42'))     // returns true
   *    math.isNumeric(math.fraction(4))      // returns true
   *    math.isNumeric(math.complex('2-4i'))  // returns false
   *    math.isNumeric([2.3, 'foo', false])   // returns [true, false, true]
   *
   * See also:
   *
   *    isZero, isPositive, isNegative, isInteger, hasNumericValue
   *
   * @param {*} x       Value to be tested
   * @return {boolean}  Returns true when `x` is a `number`, `BigNumber`,
   *                    `Fraction`, or `boolean`. Returns false for other types.
   *                    Throws an error in case of unknown types.
   */
  return typed(name$4L, {
    'number | BigNumber | bigint | Fraction | boolean': () => true,
    'Complex | Unit | string | null | undefined | Node': () => false,
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$4K = 'hasNumericValue';
var dependencies$4J = ['typed', 'isNumeric'];
var createHasNumericValue = /* #__PURE__ */factory(name$4K, dependencies$4J, _ref => {
  var {
    typed,
    isNumeric
  } = _ref;
  /**
   * Test whether a value is an numeric value.
   *
   * In case of a string, true is returned if the string contains a numeric value.
   *
   * Syntax:
   *
   *     math.hasNumericValue(x)
   *
   * Examples:
   *
   *    math.hasNumericValue(2)                     // returns true
   *    math.hasNumericValue('2')                   // returns true
   *    math.isNumeric('2')                         // returns false
   *    math.hasNumericValue(0)                     // returns true
   *    math.hasNumericValue(math.bignumber('500')) // returns true
   *    math.hasNumericValue(math.bigint('42'))     // returns true
   *    math.hasNumericValue(42n)                   // returns true
   *    math.hasNumericValue(math.fraction(4))      // returns true
   *    math.hasNumericValue(math.complex('2-4i'))  // returns false
   *    math.hasNumericValue(false)                 // returns true
   *    math.hasNumericValue([2.3, 'foo', false])   // returns [true, false, true]
   *
   * See also:
   *
   *    isZero, isPositive, isNegative, isInteger, isNumeric
   *
   * @param {*} x       Value to be tested
   * @return {boolean}  Returns true when `x` is a `number`, `BigNumber`,
   *                    `Fraction`, `Boolean`, or a `String` containing number. Returns false for other types.
   *                    Throws an error in case of unknown types.
   */
  return typed(name$4K, {
    boolean: () => true,
    string: function string(x) {
      return x.trim().length > 0 && !isNaN(Number(x));
    },
    any: function any(x) {
      return isNumeric(x);
    }
  });
});

var name$4J = 'isPositive';
var dependencies$4I = ['typed', 'config'];
var createIsPositive = /* #__PURE__ */factory(name$4J, dependencies$4I, _ref => {
  var {
    typed,
    config
  } = _ref;
  /**
   * Test whether a value is positive: larger than zero.
   * The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`.
   *
   * The function is evaluated element-wise in case of Array or Matrix input.
   *
   * Syntax:
   *
   *     math.isPositive(x)
   *
   * Examples:
   *
   *    math.isPositive(3)                     // returns true
   *    math.isPositive(-2)                    // returns false
   *    math.isPositive(0)                     // returns false
   *    math.isPositive(-0)                    // returns false
   *    math.isPositive(0.5)                   // returns true
   *    math.isPositive(math.bignumber(2))     // returns true
   *    math.isPositive(math.fraction(-2, 5))  // returns false
   *    math.isPositive(math.fraction(1, 3))   // returns true
   *    math.isPositive('2')                   // returns true
   *    math.isPositive([2, 0, -3])            // returns [true, false, false]
   *
   * See also:
   *
   *    isNumeric, isZero, isNegative, isInteger
   *
   * @param {number | BigNumber | bigint | Fraction | Unit | Array | Matrix} x  Value to be tested
   * @return {boolean}  Returns true when `x` is larger than zero.
   *                    Throws an error in case of an unknown data type.
   */
  return typed(name$4J, {
    number: x => nearlyEqual$1(x, 0, config.relTol, config.absTol) ? false : isPositiveNumber(x),
    BigNumber: x => nearlyEqual(x, new x.constructor(0), config.relTol, config.absTol) ? false : !x.isNeg() && !x.isZero() && !x.isNaN(),
    bigint: x => x > 0n,
    Fraction: x => x.s > 0 && x.n > 0,
    Unit: typed.referToSelf(self => x => typed.find(self, x.valueType())(x.value)),
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$4I = 'isZero';
var dependencies$4H = ['typed', 'equalScalar'];
var createIsZero = /* #__PURE__ */factory(name$4I, dependencies$4H, _ref => {
  var {
    typed,
    equalScalar
  } = _ref;
  /**
   * Test whether a value is zero.
   * The function can check for zero for types `number`, `BigNumber`, `Fraction`,
   * `Complex`, and `Unit`.
   *
   * The function is evaluated element-wise in case of Array or Matrix input.
   *
   * Syntax:
   *
   *     math.isZero(x)
   *
   * Examples:
   *
   *    math.isZero(0)                      // returns true
   *    math.isZero(2)                      // returns false
   *    math.isZero(0.5)                    // returns false
   *    math.isZero(math.bignumber(0))      // returns true
   *    math.isZero(math.fraction(0))       // returns true
   *    math.isZero(math.fraction(1,3))     // returns false
   *    math.isZero(math.complex('2 - 4i')) // returns false
   *    math.isZero(math.complex('0i'))     // returns true
   *    math.isZero('0')                    // returns true
   *    math.isZero('2')                    // returns false
   *    math.isZero([2, 0, -3])             // returns [false, true, false]
   *
   * See also:
   *
   *    isNumeric, isPositive, isNegative, isInteger
   *
   * @param {number | BigNumber | bigint | Complex | Fraction | Unit | Array | Matrix} x       Value to be tested
   * @return {boolean}  Returns true when `x` is zero.
   *                    Throws an error in case of an unknown data type.
   */
  return typed(name$4I, {
    'number | BigNumber | Complex | Fraction': x => equalScalar(x, 0),
    bigint: x => x === 0n,
    Unit: typed.referToSelf(self => x => typed.find(self, x.valueType())(x.value)),
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$4H = 'isNaN';
var dependencies$4G = ['typed'];
var createIsNaN = /* #__PURE__ */factory(name$4H, dependencies$4G, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Test whether a value is NaN (not a number).
   * The function supports types `number`, `BigNumber`, `Fraction`, `Unit` and `Complex`.
   *
   * The function is evaluated element-wise in case of Array or Matrix input.
   *
   * Syntax:
   *
   *     math.isNaN(x)
   *
   * Examples:
   *
   *    math.isNaN(3)                     // returns false
   *    math.isNaN(NaN)                   // returns true
   *    math.isNaN(0)                     // returns false
   *    math.isNaN(math.bignumber(NaN))   // returns true
   *    math.isNaN(math.bignumber(0))     // returns false
   *    math.isNaN(math.fraction(-2, 5))  // returns false
   *    math.isNaN('-2')                  // returns false
   *    math.isNaN([2, 0, -3, NaN])       // returns [false, false, false, true]
   *
   * See also:
   *
   *    isNumeric, isNegative, isPositive, isZero, isInteger
   *
   * @param {number | BigNumber | bigint | Fraction | Unit | Array | Matrix} x  Value to be tested
   * @return {boolean}  Returns true when `x` is NaN.
   *                    Throws an error in case of an unknown data type.
   */
  return typed(name$4H, {
    number: isNaNNumber,
    BigNumber: function BigNumber(x) {
      return x.isNaN();
    },
    bigint: function bigint(x) {
      return false;
    },
    Fraction: function Fraction(x) {
      return false;
    },
    Complex: function Complex(x) {
      return x.isNaN();
    },
    Unit: function Unit(x) {
      return Number.isNaN(x.value);
    },
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$4G = 'typeOf';
var dependencies$4F = ['typed'];
var createTypeOf = /* #__PURE__ */factory(name$4G, dependencies$4F, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Determine the type of an entity.
   *
   * Syntax:
   *
   *    math.typeOf(x)
   *
   * Examples:
   *
   *    // This list is intended to include all relevant types, for testing
   *    // purposes:
   *    math.typeOf(3.5)                      // returns 'number'
   *    math.typeOf(42n)                      // returns 'bigint'
   *    math.typeOf(math.complex('2-4i'))     // returns 'Complex'
   *    math.typeOf(math.unit('45 deg'))      // returns 'Unit'
   *    math.typeOf('hello world')            // returns 'string'
   *    math.typeOf(null)                     // returns 'null'
   *    math.typeOf(true)                     // returns 'boolean'
   *    math.typeOf([1, 2, 3])                // returns 'Array'
   *    math.typeOf(new Date())               // returns 'Date'
   *    math.typeOf(function () {})           // returns 'function'
   *    math.typeOf({a: 2, b: 3})             // returns 'Object'
   *    math.typeOf(/a regexp/)               // returns 'RegExp'
   *    math.typeOf(undefined)                // returns 'undefined'
   *    math.typeOf(math.bignumber('23e99'))  // returns 'BigNumber'
   *    math.typeOf(math.chain(2))            // returns 'Chain'
   *    math.typeOf(math.fraction(1, 3))      // returns 'Fraction'
   *    math.typeOf(math.help('sqrt'))        // returns 'Help'
   *    math.typeOf(math.index(1, 3))         // returns 'Index'
   *    math.typeOf(math.matrix([[1],[3]]))   // returns 'DenseMatrix'
   *    math.typeOf(math.matrix([],'sparse')) // returns 'SparseMatrix'
   *    math.typeOf(new math.Range(0, 10))    // returns 'Range'
   *    math.typeOf(math.evaluate('a=2\na'))  // returns 'ResultSet'
   *    math.typeOf(math.parse('A[2]'))       // returns 'AccessorNode'
   *    math.typeOf(math.parse('[1,2,3]'))    // returns 'ArrayNode'
   *    math.typeOf(math.parse('x=2'))        // returns 'AssignmentNode'
   *    math.typeOf(math.parse('a=2; b=3'))   // returns 'BlockNode'
   *    math.typeOf(math.parse('x<0?-1:1'))   // returns 'ConditionalNode'
   *    math.typeOf(math.parse('2.3'))        // returns 'ConstantNode'
   *    math.typeOf(math.parse('f(x)=x^2'))   // returns 'FunctionAssignmentNode'
   *    math.typeOf(math.parse('sqrt(4)'))    // returns 'FunctionNode'
   *    math.typeOf(math.parse('A[2]').index) // returns 'IndexNode'
   *    math.typeOf(math.parse('{a:2}'))      // returns 'ObjectNode'
   *    math.typeOf(math.parse('(2+3)'))      // returns 'ParenthesisNode'
   *    math.typeOf(math.parse('1:10'))       // returns 'RangeNode'
   *    math.typeOf(math.parse('a<b<c'))      // returns 'RelationalNode'
   *    math.typeOf(math.parse('x'))          // returns 'SymbolNode'
   *
   * @param {*} x     The variable for which to test the type.
   * @return {string} Returns the name of the type. Primitive types are lower case,
   *                  non-primitive types are upper-camel-case.
   *                  For example 'number', 'string', 'Array', 'Date'.
   */
  return typed(name$4G, {
    any: typeOf
  });
});

/**
 * Test whether two complex values are equal provided a given relTol and absTol.
 * Does not use or change the global Complex.EPSILON setting
 * @param {Complex} x - The first complex number for comparison.
 * @param {Complex} y - The second complex number for comparison.
 * @param {number} relTol - The relative tolerance for comparison.
 * @param {number} absTol - The absolute tolerance for comparison.
 * @returns {boolean} - Returns true if the two complex numbers are equal within the given tolerances, otherwise returns false.
 */
function complexEquals(x, y, relTol, absTol) {
  return nearlyEqual$1(x.re, y.re, relTol, absTol) && nearlyEqual$1(x.im, y.im, relTol, absTol);
}

var createCompareUnits = /* #__PURE__ */factory('compareUnits', ['typed'], _ref => {
  var {
    typed
  } = _ref;
  return {
    'Unit, Unit': typed.referToSelf(self => (x, y) => {
      if (!x.equalBase(y)) {
        throw new Error('Cannot compare units with different base');
      }
      return typed.find(self, [x.valueType(), y.valueType()])(x.value, y.value);
    })
  };
});

var name$4F = 'equalScalar';
var dependencies$4E = ['typed', 'config'];
var createEqualScalar = /* #__PURE__ */factory(name$4F, dependencies$4E, _ref => {
  var {
    typed,
    config
  } = _ref;
  var compareUnits = createCompareUnits({
    typed
  });

  /**
   * Test whether two scalar values are nearly equal.
   *
   * @param  {number | BigNumber | bigint | Fraction | boolean | Complex | Unit} x   First value to compare
   * @param  {number | BigNumber | bigint | Fraction | boolean | Complex} y          Second value to compare
   * @return {boolean}                                                  Returns true when the compared values are equal, else returns false
   * @private
   */
  return typed(name$4F, {
    'boolean, boolean': function booleanBoolean(x, y) {
      return x === y;
    },
    'number, number': function numberNumber(x, y) {
      return nearlyEqual$1(x, y, config.relTol, config.absTol);
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      return x.eq(y) || nearlyEqual(x, y, config.relTol, config.absTol);
    },
    'bigint, bigint': function bigintBigint(x, y) {
      return x === y;
    },
    'Fraction, Fraction': function FractionFraction(x, y) {
      return x.equals(y);
    },
    'Complex, Complex': function ComplexComplex(x, y) {
      return complexEquals(x, y, config.relTol, config.absTol);
    }
  }, compareUnits);
});
factory(name$4F, ['typed', 'config'], _ref2 => {
  var {
    typed,
    config
  } = _ref2;
  return typed(name$4F, {
    'number, number': function numberNumber(x, y) {
      return nearlyEqual$1(x, y, config.relTol, config.absTol);
    }
  });
});

var name$4E = 'SparseMatrix';
var dependencies$4D = ['typed', 'equalScalar', 'Matrix'];
var createSparseMatrixClass = /* #__PURE__ */factory(name$4E, dependencies$4D, _ref => {
  var {
    typed,
    equalScalar,
    Matrix
  } = _ref;
  /**
   * Sparse Matrix implementation. This type implements
   * a [Compressed Column Storage](https://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_column_(CSC_or_CCS))
   * format for two-dimensional sparse matrices.
   * @class SparseMatrix
   */
  function SparseMatrix(data, datatype) {
    if (!(this instanceof SparseMatrix)) {
      throw new SyntaxError('Constructor must be called with the new operator');
    }
    if (datatype && !isString(datatype)) {
      throw new Error('Invalid datatype: ' + datatype);
    }
    if (isMatrix(data)) {
      // create from matrix
      _createFromMatrix(this, data, datatype);
    } else if (data && isArray(data.index) && isArray(data.ptr) && isArray(data.size)) {
      // initialize fields
      this._values = data.values;
      this._index = data.index;
      this._ptr = data.ptr;
      this._size = data.size;
      this._datatype = datatype || data.datatype;
    } else if (isArray(data)) {
      // create from array
      _createFromArray(this, data, datatype);
    } else if (data) {
      // unsupported type
      throw new TypeError('Unsupported type of data (' + typeOf(data) + ')');
    } else {
      // nothing provided
      this._values = [];
      this._index = [];
      this._ptr = [0];
      this._size = [0, 0];
      this._datatype = datatype;
    }
  }
  function _createFromMatrix(matrix, source, datatype) {
    // check matrix type
    if (source.type === 'SparseMatrix') {
      // clone arrays
      matrix._values = source._values ? clone$2(source._values) : undefined;
      matrix._index = clone$2(source._index);
      matrix._ptr = clone$2(source._ptr);
      matrix._size = clone$2(source._size);
      matrix._datatype = datatype || source._datatype;
    } else {
      // build from matrix data
      _createFromArray(matrix, source.valueOf(), datatype || source._datatype);
    }
  }
  function _createFromArray(matrix, data, datatype) {
    // initialize fields
    matrix._values = [];
    matrix._index = [];
    matrix._ptr = [];
    matrix._datatype = datatype;
    // discover rows & columns, do not use math.size() to avoid looping array twice
    var rows = data.length;
    var columns = 0;

    // equal signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;
    if (isString(datatype)) {
      // find signature that matches (datatype, datatype)
      eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar;
      // convert 0 to the same datatype
      zero = typed.convert(0, datatype);
    }

    // check we have rows (empty array)
    if (rows > 0) {
      // column index
      var j = 0;
      do {
        // store pointer to values index
        matrix._ptr.push(matrix._index.length);
        // loop rows
        for (var i = 0; i < rows; i++) {
          // current row
          var row = data[i];
          // check row is an array
          if (isArray(row)) {
            // update columns if needed (only on first column)
            if (j === 0 && columns < row.length) {
              columns = row.length;
            }
            // check row has column
            if (j < row.length) {
              // value
              var v = row[j];
              // check value != 0
              if (!eq(v, zero)) {
                // store value
                matrix._values.push(v);
                // index
                matrix._index.push(i);
              }
            }
          } else {
            // update columns if needed (only on first column)
            if (j === 0 && columns < 1) {
              columns = 1;
            }
            // check value != 0 (row is a scalar)
            if (!eq(row, zero)) {
              // store value
              matrix._values.push(row);
              // index
              matrix._index.push(i);
            }
          }
        }
        // increment index
        j++;
      } while (j < columns);
    }
    // store number of values in ptr
    matrix._ptr.push(matrix._index.length);
    // size
    matrix._size = [rows, columns];
  }
  SparseMatrix.prototype = new Matrix();

  /**
   * Create a new SparseMatrix
   */
  SparseMatrix.prototype.createSparseMatrix = function (data, datatype) {
    return new SparseMatrix(data, datatype);
  };

  /**
   * Attach type information
   */
  Object.defineProperty(SparseMatrix, 'name', {
    value: 'SparseMatrix'
  });
  SparseMatrix.prototype.constructor = SparseMatrix;
  SparseMatrix.prototype.type = 'SparseMatrix';
  SparseMatrix.prototype.isSparseMatrix = true;

  /**
   * Get the matrix type
   *
   * Usage:
   *    const matrixType = matrix.getDataType()  // retrieves the matrix type
   *
   * @memberOf SparseMatrix
   * @return {string}   type information; if multiple types are found from the Matrix, it will return "mixed"
   */
  SparseMatrix.prototype.getDataType = function () {
    return getArrayDataType(this._values, typeOf);
  };

  /**
   * Get the storage format used by the matrix.
   *
   * Usage:
   *     const format = matrix.storage()   // retrieve storage format
   *
   * @memberof SparseMatrix
   * @return {string}           The storage format.
   */
  SparseMatrix.prototype.storage = function () {
    return 'sparse';
  };

  /**
   * Get the datatype of the data stored in the matrix.
   *
   * Usage:
   *     const format = matrix.datatype()    // retrieve matrix datatype
   *
   * @memberof SparseMatrix
   * @return {string}           The datatype.
   */
  SparseMatrix.prototype.datatype = function () {
    return this._datatype;
  };

  /**
   * Create a new SparseMatrix
   * @memberof SparseMatrix
   * @param {Array} data
   * @param {string} [datatype]
   */
  SparseMatrix.prototype.create = function (data, datatype) {
    return new SparseMatrix(data, datatype);
  };

  /**
   * Get the matrix density.
   *
   * Usage:
   *     const density = matrix.density()                   // retrieve matrix density
   *
   * @memberof SparseMatrix
   * @return {number}           The matrix density.
   */
  SparseMatrix.prototype.density = function () {
    // rows & columns
    var rows = this._size[0];
    var columns = this._size[1];
    // calculate density
    return rows !== 0 && columns !== 0 ? this._index.length / (rows * columns) : 0;
  };

  /**
   * Get a subset of the matrix, or replace a subset of the matrix.
   *
   * Usage:
   *     const subset = matrix.subset(index)               // retrieve subset
   *     const value = matrix.subset(index, replacement)   // replace subset
   *
   * @memberof SparseMatrix
   * @param {Index} index
   * @param {Array | Matrix | *} [replacement]
   * @param {*} [defaultValue=0]      Default value, filled in on new entries when
   *                                  the matrix is resized. If not provided,
   *                                  new matrix elements will be filled with zeros.
   */
  SparseMatrix.prototype.subset = function (index, replacement, defaultValue) {
    // check it is a pattern matrix
    if (!this._values) {
      throw new Error('Cannot invoke subset on a Pattern only matrix');
    }

    // check arguments
    switch (arguments.length) {
      case 1:
        return _getsubset(this, index);

      // intentional fall through
      case 2:
      case 3:
        return _setsubset(this, index, replacement, defaultValue);
      default:
        throw new SyntaxError('Wrong number of arguments');
    }
  };
  function _getsubset(matrix, idx) {
    // check idx
    if (!isIndex(idx)) {
      throw new TypeError('Invalid index');
    }
    var isScalar = idx.isScalar();
    if (isScalar) {
      // return a scalar
      return matrix.get(idx.min());
    }
    // validate dimensions
    var size = idx.size();
    if (size.length !== matrix._size.length) {
      throw new DimensionError(size.length, matrix._size.length);
    }

    // vars
    var i, ii, k, kk;

    // validate if any of the ranges in the index is out of range
    var min = idx.min();
    var max = idx.max();
    for (i = 0, ii = matrix._size.length; i < ii; i++) {
      validateIndex(min[i], matrix._size[i]);
      validateIndex(max[i], matrix._size[i]);
    }

    // matrix arrays
    var mvalues = matrix._values;
    var mindex = matrix._index;
    var mptr = matrix._ptr;

    // rows & columns dimensions for result matrix
    var rows = idx.dimension(0);
    var columns = idx.dimension(1);

    // workspace & permutation vector
    var w = [];
    var pv = [];

    // loop rows in resulting matrix
    rows.forEach(function (i, r) {
      // update permutation vector
      pv[i] = r[0];
      // mark i in workspace
      w[i] = true;
    });

    // result matrix arrays
    var values = mvalues ? [] : undefined;
    var index = [];
    var ptr = [];

    // loop columns in result matrix
    columns.forEach(function (j) {
      // update ptr
      ptr.push(index.length);
      // loop values in column j
      for (k = mptr[j], kk = mptr[j + 1]; k < kk; k++) {
        // row
        i = mindex[k];
        // check row is in result matrix
        if (w[i] === true) {
          // push index
          index.push(pv[i]);
          // check we need to process values
          if (values) {
            values.push(mvalues[k]);
          }
        }
      }
    });
    // update ptr
    ptr.push(index.length);

    // return matrix
    return new SparseMatrix({
      values,
      index,
      ptr,
      size,
      datatype: matrix._datatype
    });
  }
  function _setsubset(matrix, index, submatrix, defaultValue) {
    // check index
    if (!index || index.isIndex !== true) {
      throw new TypeError('Invalid index');
    }

    // get index size and check whether the index contains a single value
    var iSize = index.size();
    var isScalar = index.isScalar();

    // calculate the size of the submatrix, and convert it into an Array if needed
    var sSize;
    if (isMatrix(submatrix)) {
      // submatrix size
      sSize = submatrix.size();
      // use array representation
      submatrix = submatrix.toArray();
    } else {
      // get submatrix size (array, scalar)
      sSize = arraySize(submatrix);
    }

    // check index is a scalar
    if (isScalar) {
      // verify submatrix is a scalar
      if (sSize.length !== 0) {
        throw new TypeError('Scalar expected');
      }
      // set value
      matrix.set(index.min(), submatrix, defaultValue);
    } else {
      // validate dimensions, index size must be one or two dimensions
      if (iSize.length !== 1 && iSize.length !== 2) {
        throw new DimensionError(iSize.length, matrix._size.length, '<');
      }

      // check submatrix and index have the same dimensions
      if (sSize.length < iSize.length) {
        // calculate number of missing outer dimensions
        var i = 0;
        var outer = 0;
        while (iSize[i] === 1 && sSize[i] === 1) {
          i++;
        }
        while (iSize[i] === 1) {
          outer++;
          i++;
        }
        // unsqueeze both outer and inner dimensions
        submatrix = unsqueeze(submatrix, iSize.length, outer, sSize);
      }

      // check whether the size of the submatrix matches the index size
      if (!deepStrictEqual(iSize, sSize)) {
        throw new DimensionError(iSize, sSize, '>');
      }

      // insert the sub matrix
      if (iSize.length === 1) {
        // if the replacement index only has 1 dimension, go trough each one and set its value
        var range = index.dimension(0);
        range.forEach(function (dataIndex, subIndex) {
          validateIndex(dataIndex);
          matrix.set([dataIndex, 0], submatrix[subIndex[0]], defaultValue);
        });
      } else {
        // if the replacement index has 2 dimensions, go through each one and set the value in the correct index
        var firstDimensionRange = index.dimension(0);
        var secondDimensionRange = index.dimension(1);
        firstDimensionRange.forEach(function (firstDataIndex, firstSubIndex) {
          validateIndex(firstDataIndex);
          secondDimensionRange.forEach(function (secondDataIndex, secondSubIndex) {
            validateIndex(secondDataIndex);
            matrix.set([firstDataIndex, secondDataIndex], submatrix[firstSubIndex[0]][secondSubIndex[0]], defaultValue);
          });
        });
      }
    }
    return matrix;
  }

  /**
   * Get a single element from the matrix.
   * @memberof SparseMatrix
   * @param {number[]} index   Zero-based index
   * @return {*} value
   */
  SparseMatrix.prototype.get = function (index) {
    if (!isArray(index)) {
      throw new TypeError('Array expected');
    }
    if (index.length !== this._size.length) {
      throw new DimensionError(index.length, this._size.length);
    }

    // check it is a pattern matrix
    if (!this._values) {
      throw new Error('Cannot invoke get on a Pattern only matrix');
    }

    // row and column
    var i = index[0];
    var j = index[1];

    // check i, j are valid
    validateIndex(i, this._size[0]);
    validateIndex(j, this._size[1]);

    // find value index
    var k = _getValueIndex(i, this._ptr[j], this._ptr[j + 1], this._index);
    // check k is prior to next column k and it is in the correct row
    if (k < this._ptr[j + 1] && this._index[k] === i) {
      return this._values[k];
    }
    return 0;
  };

  /**
   * Replace a single element in the matrix.
   * @memberof SparseMatrix
   * @param {number[]} index   Zero-based index
   * @param {*} v
   * @param {*} [defaultValue]        Default value, filled in on new entries when
   *                                  the matrix is resized. If not provided,
   *                                  new matrix elements will be set to zero.
   * @return {SparseMatrix} self
   */
  SparseMatrix.prototype.set = function (index, v, defaultValue) {
    if (!isArray(index)) {
      throw new TypeError('Array expected');
    }
    if (index.length !== this._size.length) {
      throw new DimensionError(index.length, this._size.length);
    }

    // check it is a pattern matrix
    if (!this._values) {
      throw new Error('Cannot invoke set on a Pattern only matrix');
    }

    // row and column
    var i = index[0];
    var j = index[1];

    // rows & columns
    var rows = this._size[0];
    var columns = this._size[1];

    // equal signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;
    if (isString(this._datatype)) {
      // find signature that matches (datatype, datatype)
      eq = typed.find(equalScalar, [this._datatype, this._datatype]) || equalScalar;
      // convert 0 to the same datatype
      zero = typed.convert(0, this._datatype);
    }

    // check we need to resize matrix
    if (i > rows - 1 || j > columns - 1) {
      // resize matrix
      _resize(this, Math.max(i + 1, rows), Math.max(j + 1, columns), defaultValue);
      // update rows & columns
      rows = this._size[0];
      columns = this._size[1];
    }

    // check i, j are valid
    validateIndex(i, rows);
    validateIndex(j, columns);

    // find value index
    var k = _getValueIndex(i, this._ptr[j], this._ptr[j + 1], this._index);
    // check k is prior to next column k and it is in the correct row
    if (k < this._ptr[j + 1] && this._index[k] === i) {
      // check value != 0
      if (!eq(v, zero)) {
        // update value
        this._values[k] = v;
      } else {
        // remove value from matrix
        _remove(k, j, this._values, this._index, this._ptr);
      }
    } else {
      if (!eq(v, zero)) {
        // insert value @ (i, j)
        _insert(k, i, j, v, this._values, this._index, this._ptr);
      }
    }
    return this;
  };
  function _getValueIndex(i, top, bottom, index) {
    // check row is on the bottom side
    if (bottom - top === 0) {
      return bottom;
    }
    // loop rows [top, bottom[
    for (var r = top; r < bottom; r++) {
      // check we found value index
      if (index[r] === i) {
        return r;
      }
    }
    // we did not find row
    return top;
  }
  function _remove(k, j, values, index, ptr) {
    // remove value @ k
    values.splice(k, 1);
    index.splice(k, 1);
    // update pointers
    for (var x = j + 1; x < ptr.length; x++) {
      ptr[x]--;
    }
  }
  function _insert(k, i, j, v, values, index, ptr) {
    // insert value
    values.splice(k, 0, v);
    // update row for k
    index.splice(k, 0, i);
    // update column pointers
    for (var x = j + 1; x < ptr.length; x++) {
      ptr[x]++;
    }
  }

  /**
   * Resize the matrix to the given size. Returns a copy of the matrix when
   * `copy=true`, otherwise return the matrix itself (resize in place).
   *
   * @memberof SparseMatrix
   * @param {number[] | Matrix} size  The new size the matrix should have.
   *                                  Since sparse matrices are always two-dimensional,
   *                                  size must be two numbers in either an array or a matrix
   * @param {*} [defaultValue=0]      Default value, filled in on new entries.
   *                                  If not provided, the matrix elements will
   *                                  be filled with zeros.
   * @param {boolean} [copy]          Return a resized copy of the matrix
   *
   * @return {Matrix}                 The resized matrix
   */
  SparseMatrix.prototype.resize = function (size, defaultValue, copy) {
    // validate arguments
    if (!isCollection(size)) {
      throw new TypeError('Array or Matrix expected');
    }

    // SparseMatrix input is always 2d, flatten this into 1d if it's indeed a vector
    var sizeArray = size.valueOf().map(value => {
      return Array.isArray(value) && value.length === 1 ? value[0] : value;
    });
    if (sizeArray.length !== 2) {
      throw new Error('Only two dimensions matrix are supported');
    }

    // check sizes
    sizeArray.forEach(function (value) {
      if (!isNumber(value) || !isInteger(value) || value < 0) {
        throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + format(sizeArray) + ')');
      }
    });

    // matrix to resize
    var m = copy ? this.clone() : this;
    // resize matrix
    return _resize(m, sizeArray[0], sizeArray[1], defaultValue);
  };
  function _resize(matrix, rows, columns, defaultValue) {
    // value to insert at the time of growing matrix
    var value = defaultValue || 0;

    // equal signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;
    if (isString(matrix._datatype)) {
      // find signature that matches (datatype, datatype)
      eq = typed.find(equalScalar, [matrix._datatype, matrix._datatype]) || equalScalar;
      // convert 0 to the same datatype
      zero = typed.convert(0, matrix._datatype);
      // convert value to the same datatype
      value = typed.convert(value, matrix._datatype);
    }

    // should we insert the value?
    var ins = !eq(value, zero);

    // old columns and rows
    var r = matrix._size[0];
    var c = matrix._size[1];
    var i, j, k;

    // check we need to increase columns
    if (columns > c) {
      // loop new columns
      for (j = c; j < columns; j++) {
        // update matrix._ptr for current column
        matrix._ptr[j] = matrix._values.length;
        // check we need to insert matrix._values
        if (ins) {
          // loop rows
          for (i = 0; i < r; i++) {
            // add new matrix._values
            matrix._values.push(value);
            // update matrix._index
            matrix._index.push(i);
          }
        }
      }
      // store number of matrix._values in matrix._ptr
      matrix._ptr[columns] = matrix._values.length;
    } else if (columns < c) {
      // truncate matrix._ptr
      matrix._ptr.splice(columns + 1, c - columns);
      // truncate matrix._values and matrix._index
      matrix._values.splice(matrix._ptr[columns], matrix._values.length);
      matrix._index.splice(matrix._ptr[columns], matrix._index.length);
    }
    // update columns
    c = columns;

    // check we need to increase rows
    if (rows > r) {
      // check we have to insert values
      if (ins) {
        // inserts
        var n = 0;
        // loop columns
        for (j = 0; j < c; j++) {
          // update matrix._ptr for current column
          matrix._ptr[j] = matrix._ptr[j] + n;
          // where to insert matrix._values
          k = matrix._ptr[j + 1] + n;
          // pointer
          var p = 0;
          // loop new rows, initialize pointer
          for (i = r; i < rows; i++, p++) {
            // add value
            matrix._values.splice(k + p, 0, value);
            // update matrix._index
            matrix._index.splice(k + p, 0, i);
            // increment inserts
            n++;
          }
        }
        // store number of matrix._values in matrix._ptr
        matrix._ptr[c] = matrix._values.length;
      }
    } else if (rows < r) {
      // deletes
      var d = 0;
      // loop columns
      for (j = 0; j < c; j++) {
        // update matrix._ptr for current column
        matrix._ptr[j] = matrix._ptr[j] - d;
        // where matrix._values start for next column
        var k0 = matrix._ptr[j];
        var k1 = matrix._ptr[j + 1] - d;
        // loop matrix._index
        for (k = k0; k < k1; k++) {
          // row
          i = matrix._index[k];
          // check we need to delete value and matrix._index
          if (i > rows - 1) {
            // remove value
            matrix._values.splice(k, 1);
            // remove item from matrix._index
            matrix._index.splice(k, 1);
            // increase deletes
            d++;
          }
        }
      }
      // update matrix._ptr for current column
      matrix._ptr[j] = matrix._values.length;
    }
    // update matrix._size
    matrix._size[0] = rows;
    matrix._size[1] = columns;
    // return matrix
    return matrix;
  }

  /**
   * Reshape the matrix to the given size. Returns a copy of the matrix when
   * `copy=true`, otherwise return the matrix itself (reshape in place).
   *
   * NOTE: This might be better suited to copy by default, instead of modifying
   *       in place. For now, it operates in place to remain consistent with
   *       resize().
   *
   * @memberof SparseMatrix
   * @param {number[]} sizes          The new size the matrix should have.
   *                                  Since sparse matrices are always two-dimensional,
   *                                  size must be two numbers in either an array or a matrix
   * @param {boolean} [copy]          Return a reshaped copy of the matrix
   *
   * @return {Matrix}                 The reshaped matrix
   */
  SparseMatrix.prototype.reshape = function (sizes, copy) {
    // validate arguments
    if (!isArray(sizes)) {
      throw new TypeError('Array expected');
    }
    if (sizes.length !== 2) {
      throw new Error('Sparse matrices can only be reshaped in two dimensions');
    }

    // check sizes
    sizes.forEach(function (value) {
      if (!isNumber(value) || !isInteger(value) || value <= -2 || value === 0) {
        throw new TypeError('Invalid size, must contain positive integers or -1 ' + '(size: ' + format(sizes) + ')');
      }
    });
    var currentLength = this._size[0] * this._size[1];
    sizes = processSizesWildcard(sizes, currentLength);
    var newLength = sizes[0] * sizes[1];

    // m * n must not change
    if (currentLength !== newLength) {
      throw new Error('Reshaping sparse matrix will result in the wrong number of elements');
    }

    // matrix to reshape
    var m = copy ? this.clone() : this;

    // return unchanged if the same shape
    if (this._size[0] === sizes[0] && this._size[1] === sizes[1]) {
      return m;
    }

    // Convert to COO format (generate a column index)
    var colIndex = [];
    for (var i = 0; i < m._ptr.length; i++) {
      for (var j = 0; j < m._ptr[i + 1] - m._ptr[i]; j++) {
        colIndex.push(i);
      }
    }

    // Clone the values array
    var values = m._values.slice();

    // Clone the row index array
    var rowIndex = m._index.slice();

    // Transform the (row, column) indices
    for (var _i = 0; _i < m._index.length; _i++) {
      var r1 = rowIndex[_i];
      var c1 = colIndex[_i];
      var flat = r1 * m._size[1] + c1;
      colIndex[_i] = flat % sizes[1];
      rowIndex[_i] = Math.floor(flat / sizes[1]);
    }

    // Now reshaping is supposed to preserve the row-major order, BUT these sparse matrices are stored
    // in column-major order, so we have to reorder the value array now. One option is to use a multisort,
    // sorting several arrays based on some other array.

    // OR, we could easily just:

    // 1. Remove all values from the matrix
    m._values.length = 0;
    m._index.length = 0;
    m._ptr.length = sizes[1] + 1;
    m._size = sizes.slice();
    for (var _i2 = 0; _i2 < m._ptr.length; _i2++) {
      m._ptr[_i2] = 0;
    }

    // 2. Re-insert all elements in the proper order (simplified code from SparseMatrix.prototype.set)
    // This step is probably the most time-consuming
    for (var h = 0; h < values.length; h++) {
      var _i3 = rowIndex[h];
      var _j = colIndex[h];
      var v = values[h];
      var k = _getValueIndex(_i3, m._ptr[_j], m._ptr[_j + 1], m._index);
      _insert(k, _i3, _j, v, m._values, m._index, m._ptr);
    }

    // The value indices are inserted out of order, but apparently that's... still OK?

    return m;
  };

  /**
   * Create a clone of the matrix
   * @memberof SparseMatrix
   * @return {SparseMatrix} clone
   */
  SparseMatrix.prototype.clone = function () {
    var m = new SparseMatrix({
      values: this._values ? clone$2(this._values) : undefined,
      index: clone$2(this._index),
      ptr: clone$2(this._ptr),
      size: clone$2(this._size),
      datatype: this._datatype
    });
    return m;
  };

  /**
   * Retrieve the size of the matrix.
   * @memberof SparseMatrix
   * @returns {number[]} size
   */
  SparseMatrix.prototype.size = function () {
    return this._size.slice(0); // copy the Array
  };

  /**
   * Create a new matrix with the results of the callback function executed on
   * each entry of the matrix.
   * @memberof SparseMatrix
   * @param {Function} callback   The callback function is invoked with three
   *                              parameters: the value of the element, the index
   *                              of the element, and the Matrix being traversed.
   * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.
   *
   * @return {SparseMatrix} matrix
   */
  SparseMatrix.prototype.map = function (callback, skipZeros) {
    // check it is a pattern matrix
    if (!this._values) {
      throw new Error('Cannot invoke map on a Pattern only matrix');
    }
    // matrix instance
    var me = this;
    // rows and columns
    var rows = this._size[0];
    var columns = this._size[1];
    // invoke callback
    var args = maxArgumentCount(callback);
    var invoke = function invoke(v, i, j) {
      // invoke callback
      if (args === 1) return callback(v);
      if (args === 2) return callback(v, [i, j]);
      return callback(v, [i, j], me);
    };
    // invoke _map
    return _map(this, 0, rows - 1, 0, columns - 1, invoke, skipZeros);
  };

  /**
   * Create a new matrix with the results of the callback function executed on the interval
   * [minRow..maxRow, minColumn..maxColumn].
   */
  function _map(matrix, minRow, maxRow, minColumn, maxColumn, callback, skipZeros) {
    // result arrays
    var values = [];
    var index = [];
    var ptr = [];

    // equal signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;
    if (isString(matrix._datatype)) {
      // find signature that matches (datatype, datatype)
      eq = typed.find(equalScalar, [matrix._datatype, matrix._datatype]) || equalScalar;
      // convert 0 to the same datatype
      zero = typed.convert(0, matrix._datatype);
    }

    // invoke callback
    var invoke = function invoke(v, x, y) {
      // invoke callback
      v = callback(v, x, y);
      // check value != 0
      if (!eq(v, zero)) {
        // store value
        values.push(v);
        // index
        index.push(x);
      }
    };
    // loop columns
    for (var j = minColumn; j <= maxColumn; j++) {
      // store pointer to values index
      ptr.push(values.length);
      // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
      var k0 = matrix._ptr[j];
      var k1 = matrix._ptr[j + 1];
      if (skipZeros) {
        // loop k within [k0, k1[
        for (var k = k0; k < k1; k++) {
          // row index
          var i = matrix._index[k];
          // check i is in range
          if (i >= minRow && i <= maxRow) {
            // value @ k
            invoke(matrix._values[k], i - minRow, j - minColumn);
          }
        }
      } else {
        // create a cache holding all defined values
        var _values = {};
        for (var _k = k0; _k < k1; _k++) {
          var _i4 = matrix._index[_k];
          _values[_i4] = matrix._values[_k];
        }

        // loop over all rows (indexes can be unordered so we can't use that),
        // and either read the value or zero
        for (var _i5 = minRow; _i5 <= maxRow; _i5++) {
          var value = _i5 in _values ? _values[_i5] : 0;
          invoke(value, _i5 - minRow, j - minColumn);
        }
      }
    }

    // store number of values in ptr
    ptr.push(values.length);
    // return sparse matrix
    return new SparseMatrix({
      values,
      index,
      ptr,
      size: [maxRow - minRow + 1, maxColumn - minColumn + 1]
    });
  }

  /**
   * Execute a callback function on each entry of the matrix.
   * @memberof SparseMatrix
   * @param {Function} callback   The callback function is invoked with three
   *                              parameters: the value of the element, the index
   *                              of the element, and the Matrix being traversed.
   * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.
   *                              If false, the indices are guaranteed to be in order,
   *                              if true, the indices can be unordered.
   */
  SparseMatrix.prototype.forEach = function (callback, skipZeros) {
    // check it is a pattern matrix
    if (!this._values) {
      throw new Error('Cannot invoke forEach on a Pattern only matrix');
    }
    // matrix instance
    var me = this;
    // rows and columns
    var rows = this._size[0];
    var columns = this._size[1];
    // loop columns
    for (var j = 0; j < columns; j++) {
      // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
      var k0 = this._ptr[j];
      var k1 = this._ptr[j + 1];
      if (skipZeros) {
        // loop k within [k0, k1[
        for (var k = k0; k < k1; k++) {
          // row index
          var i = this._index[k];

          // value @ k
          callback(this._values[k], [i, j], me);
        }
      } else {
        // create a cache holding all defined values
        var values = {};
        for (var _k2 = k0; _k2 < k1; _k2++) {
          var _i6 = this._index[_k2];
          values[_i6] = this._values[_k2];
        }

        // loop over all rows (indexes can be unordered so we can't use that),
        // and either read the value or zero
        for (var _i7 = 0; _i7 < rows; _i7++) {
          var value = _i7 in values ? values[_i7] : 0;
          callback(value, [_i7, j], me);
        }
      }
    }
  };

  /**
   * Iterate over the matrix elements, skipping zeros
   * @return {Iterable<{ value, index: number[] }>}
   */
  SparseMatrix.prototype[Symbol.iterator] = function* () {
    if (!this._values) {
      throw new Error('Cannot iterate a Pattern only matrix');
    }
    var columns = this._size[1];
    for (var j = 0; j < columns; j++) {
      var k0 = this._ptr[j];
      var k1 = this._ptr[j + 1];
      for (var k = k0; k < k1; k++) {
        // row index
        var i = this._index[k];
        yield {
          value: this._values[k],
          index: [i, j]
        };
      }
    }
  };

  /**
   * Create an Array with a copy of the data of the SparseMatrix
   * @memberof SparseMatrix
   * @returns {Array} array
   */
  SparseMatrix.prototype.toArray = function () {
    return _toArray(this._values, this._index, this._ptr, this._size, true);
  };

  /**
   * Get the primitive value of the SparseMatrix: a two dimensions array
   * @memberof SparseMatrix
   * @returns {Array} array
   */
  SparseMatrix.prototype.valueOf = function () {
    return _toArray(this._values, this._index, this._ptr, this._size, false);
  };
  function _toArray(values, index, ptr, size, copy) {
    // rows and columns
    var rows = size[0];
    var columns = size[1];
    // result
    var a = [];
    // vars
    var i, j;
    // initialize array
    for (i = 0; i < rows; i++) {
      a[i] = [];
      for (j = 0; j < columns; j++) {
        a[i][j] = 0;
      }
    }

    // loop columns
    for (j = 0; j < columns; j++) {
      // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
      var k0 = ptr[j];
      var k1 = ptr[j + 1];
      // loop k within [k0, k1[
      for (var k = k0; k < k1; k++) {
        // row index
        i = index[k];
        // set value (use one for pattern matrix)
        a[i][j] = values ? copy ? clone$2(values[k]) : values[k] : 1;
      }
    }
    return a;
  }

  /**
   * Get a string representation of the matrix, with optional formatting options.
   * @memberof SparseMatrix
   * @param {Object | number | Function} [options]  Formatting options. See
   *                                                lib/utils/number:format for a
   *                                                description of the available
   *                                                options.
   * @returns {string} str
   */
  SparseMatrix.prototype.format = function (options) {
    // rows and columns
    var rows = this._size[0];
    var columns = this._size[1];
    // density
    var density = this.density();
    // rows & columns
    var str = 'Sparse Matrix [' + format(rows, options) + ' x ' + format(columns, options) + '] density: ' + format(density, options) + '\n';
    // loop columns
    for (var j = 0; j < columns; j++) {
      // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
      var k0 = this._ptr[j];
      var k1 = this._ptr[j + 1];
      // loop k within [k0, k1[
      for (var k = k0; k < k1; k++) {
        // row index
        var i = this._index[k];
        // append value
        str += '\n    (' + format(i, options) + ', ' + format(j, options) + ') ==> ' + (this._values ? format(this._values[k], options) : 'X');
      }
    }
    return str;
  };

  /**
   * Get a string representation of the matrix
   * @memberof SparseMatrix
   * @returns {string} str
   */
  SparseMatrix.prototype.toString = function () {
    return format(this.toArray());
  };

  /**
   * Get a JSON representation of the matrix
   * @memberof SparseMatrix
   * @returns {Object}
   */
  SparseMatrix.prototype.toJSON = function () {
    return {
      mathjs: 'SparseMatrix',
      values: this._values,
      index: this._index,
      ptr: this._ptr,
      size: this._size,
      datatype: this._datatype
    };
  };

  /**
   * Get the kth Matrix diagonal.
   *
   * @memberof SparseMatrix
   * @param {number | BigNumber} [k=0]     The kth diagonal where the vector will retrieved.
   *
   * @returns {Matrix}                     The matrix vector with the diagonal values.
   */
  SparseMatrix.prototype.diagonal = function (k) {
    // validate k if any
    if (k) {
      // convert BigNumber to a number
      if (isBigNumber(k)) {
        k = k.toNumber();
      }
      // is must be an integer
      if (!isNumber(k) || !isInteger(k)) {
        throw new TypeError('The parameter k must be an integer number');
      }
    } else {
      // default value
      k = 0;
    }
    var kSuper = k > 0 ? k : 0;
    var kSub = k < 0 ? -k : 0;

    // rows & columns
    var rows = this._size[0];
    var columns = this._size[1];

    // number diagonal values
    var n = Math.min(rows - kSub, columns - kSuper);

    // diagonal arrays
    var values = [];
    var index = [];
    var ptr = [];
    // initial ptr value
    ptr[0] = 0;
    // loop columns
    for (var j = kSuper; j < columns && values.length < n; j++) {
      // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
      var k0 = this._ptr[j];
      var k1 = this._ptr[j + 1];
      // loop x within [k0, k1[
      for (var x = k0; x < k1; x++) {
        // row index
        var i = this._index[x];
        // check row
        if (i === j - kSuper + kSub) {
          // value on this column
          values.push(this._values[x]);
          // store row
          index[values.length - 1] = i - kSub;
          // exit loop
          break;
        }
      }
    }
    // close ptr
    ptr.push(values.length);
    // return matrix
    return new SparseMatrix({
      values,
      index,
      ptr,
      size: [n, 1]
    });
  };

  /**
   * Generate a matrix from a JSON object
   * @memberof SparseMatrix
   * @param {Object} json  An object structured like
   *                       `{"mathjs": "SparseMatrix", "values": [], "index": [], "ptr": [], "size": []}`,
   *                       where mathjs is optional
   * @returns {SparseMatrix}
   */
  SparseMatrix.fromJSON = function (json) {
    return new SparseMatrix(json);
  };

  /**
   * Create a diagonal matrix.
   *
   * @memberof SparseMatrix
   * @param {Array} size                       The matrix size.
   * @param {number | Array | Matrix } value   The values for the diagonal.
   * @param {number | BigNumber} [k=0]         The kth diagonal where the vector will be filled in.
   * @param {number} [defaultValue]            The default value for non-diagonal
   * @param {string} [datatype]                The Matrix datatype, values must be of this datatype.
   *
   * @returns {SparseMatrix}
   */
  SparseMatrix.diagonal = function (size, value, k, defaultValue, datatype) {
    if (!isArray(size)) {
      throw new TypeError('Array expected, size parameter');
    }
    if (size.length !== 2) {
      throw new Error('Only two dimensions matrix are supported');
    }

    // map size & validate
    size = size.map(function (s) {
      // check it is a big number
      if (isBigNumber(s)) {
        // convert it
        s = s.toNumber();
      }
      // validate arguments
      if (!isNumber(s) || !isInteger(s) || s < 1) {
        throw new Error('Size values must be positive integers');
      }
      return s;
    });

    // validate k if any
    if (k) {
      // convert BigNumber to a number
      if (isBigNumber(k)) {
        k = k.toNumber();
      }
      // is must be an integer
      if (!isNumber(k) || !isInteger(k)) {
        throw new TypeError('The parameter k must be an integer number');
      }
    } else {
      // default value
      k = 0;
    }

    // equal signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;
    if (isString(datatype)) {
      // find signature that matches (datatype, datatype)
      eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar;
      // convert 0 to the same datatype
      zero = typed.convert(0, datatype);
    }
    var kSuper = k > 0 ? k : 0;
    var kSub = k < 0 ? -k : 0;

    // rows and columns
    var rows = size[0];
    var columns = size[1];

    // number of non-zero items
    var n = Math.min(rows - kSub, columns - kSuper);

    // value extraction function
    var _value;

    // check value
    if (isArray(value)) {
      // validate array
      if (value.length !== n) {
        // number of values in array must be n
        throw new Error('Invalid value array length');
      }
      // define function
      _value = function _value(i) {
        // return value @ i
        return value[i];
      };
    } else if (isMatrix(value)) {
      // matrix size
      var ms = value.size();
      // validate matrix
      if (ms.length !== 1 || ms[0] !== n) {
        // number of values in array must be n
        throw new Error('Invalid matrix length');
      }
      // define function
      _value = function _value(i) {
        // return value @ i
        return value.get([i]);
      };
    } else {
      // define function
      _value = function _value() {
        // return value
        return value;
      };
    }

    // create arrays
    var values = [];
    var index = [];
    var ptr = [];

    // loop items
    for (var j = 0; j < columns; j++) {
      // number of rows with value
      ptr.push(values.length);
      // diagonal index
      var i = j - kSuper;
      // check we need to set diagonal value
      if (i >= 0 && i < n) {
        // get value @ i
        var v = _value(i);
        // check for zero
        if (!eq(v, zero)) {
          // column
          index.push(i + kSub);
          // add value
          values.push(v);
        }
      }
    }
    // last value should be number of values
    ptr.push(values.length);
    // create SparseMatrix
    return new SparseMatrix({
      values,
      index,
      ptr,
      size: [rows, columns]
    });
  };

  /**
   * Swap rows i and j in Matrix.
   *
   * @memberof SparseMatrix
   * @param {number} i       Matrix row index 1
   * @param {number} j       Matrix row index 2
   *
   * @return {Matrix}        The matrix reference
   */
  SparseMatrix.prototype.swapRows = function (i, j) {
    // check index
    if (!isNumber(i) || !isInteger(i) || !isNumber(j) || !isInteger(j)) {
      throw new Error('Row index must be positive integers');
    }
    // check dimensions
    if (this._size.length !== 2) {
      throw new Error('Only two dimensional matrix is supported');
    }
    // validate index
    validateIndex(i, this._size[0]);
    validateIndex(j, this._size[0]);

    // swap rows
    SparseMatrix._swapRows(i, j, this._size[1], this._values, this._index, this._ptr);
    // return current instance
    return this;
  };

  /**
   * Loop rows with data in column j.
   *
   * @param {number} j            Column
   * @param {Array} values        Matrix values
   * @param {Array} index         Matrix row indeces
   * @param {Array} ptr           Matrix column pointers
   * @param {Function} callback   Callback function invoked for every row in column j
   */
  SparseMatrix._forEachRow = function (j, values, index, ptr, callback) {
    // indeces for column j
    var k0 = ptr[j];
    var k1 = ptr[j + 1];
    // loop
    for (var k = k0; k < k1; k++) {
      // invoke callback
      callback(index[k], values[k]);
    }
  };

  /**
   * Swap rows x and y in Sparse Matrix data structures.
   *
   * @param {number} x         Matrix row index 1
   * @param {number} y         Matrix row index 2
   * @param {number} columns   Number of columns in matrix
   * @param {Array} values     Matrix values
   * @param {Array} index      Matrix row indeces
   * @param {Array} ptr        Matrix column pointers
   */
  SparseMatrix._swapRows = function (x, y, columns, values, index, ptr) {
    // loop columns
    for (var j = 0; j < columns; j++) {
      // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
      var k0 = ptr[j];
      var k1 = ptr[j + 1];
      // find value index @ x
      var kx = _getValueIndex(x, k0, k1, index);
      // find value index @ x
      var ky = _getValueIndex(y, k0, k1, index);
      // check both rows exist in matrix
      if (kx < k1 && ky < k1 && index[kx] === x && index[ky] === y) {
        // swap values (check for pattern matrix)
        if (values) {
          var v = values[kx];
          values[kx] = values[ky];
          values[ky] = v;
        }
        // next column
        continue;
      }
      // check x row exist & no y row
      if (kx < k1 && index[kx] === x && (ky >= k1 || index[ky] !== y)) {
        // value @ x (check for pattern matrix)
        var vx = values ? values[kx] : undefined;
        // insert value @ y
        index.splice(ky, 0, y);
        if (values) {
          values.splice(ky, 0, vx);
        }
        // remove value @ x (adjust array index if needed)
        index.splice(ky <= kx ? kx + 1 : kx, 1);
        if (values) {
          values.splice(ky <= kx ? kx + 1 : kx, 1);
        }
        // next column
        continue;
      }
      // check y row exist & no x row
      if (ky < k1 && index[ky] === y && (kx >= k1 || index[kx] !== x)) {
        // value @ y (check for pattern matrix)
        var vy = values ? values[ky] : undefined;
        // insert value @ x
        index.splice(kx, 0, x);
        if (values) {
          values.splice(kx, 0, vy);
        }
        // remove value @ y (adjust array index if needed)
        index.splice(kx <= ky ? ky + 1 : ky, 1);
        if (values) {
          values.splice(kx <= ky ? ky + 1 : ky, 1);
        }
      }
    }
  };
  return SparseMatrix;
}, {
  isClass: true
});

var name$4D = 'number';
var dependencies$4C = ['typed'];

/**
 * Separates the radix, integer part, and fractional part of a non decimal number string
 * @param {string} input string to parse
 * @returns {object} the parts of the string or null if not a valid input
 */
function getNonDecimalNumberParts(input) {
  var nonDecimalWithRadixMatch = input.match(/(0[box])([0-9a-fA-F]*)\.([0-9a-fA-F]*)/);
  if (nonDecimalWithRadixMatch) {
    var radix = {
      '0b': 2,
      '0o': 8,
      '0x': 16
    }[nonDecimalWithRadixMatch[1]];
    var integerPart = nonDecimalWithRadixMatch[2];
    var fractionalPart = nonDecimalWithRadixMatch[3];
    return {
      input,
      radix,
      integerPart,
      fractionalPart
    };
  } else {
    return null;
  }
}

/**
 * Makes a number from a radix, and integer part, and a fractional part
 * @param {parts} [x] parts of the number string (from getNonDecimalNumberParts)
 * @returns {number} the number
 */
function makeNumberFromNonDecimalParts(parts) {
  var n = parseInt(parts.integerPart, parts.radix);
  var f = 0;
  for (var i = 0; i < parts.fractionalPart.length; i++) {
    var digitValue = parseInt(parts.fractionalPart[i], parts.radix);
    f += digitValue / Math.pow(parts.radix, i + 1);
  }
  var result = n + f;
  if (isNaN(result)) {
    throw new SyntaxError('String "' + parts.input + '" is not a valid number');
  }
  return result;
}
var createNumber = /* #__PURE__ */factory(name$4D, dependencies$4C, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Create a number or convert a string, boolean, or unit to a number.
   * When value is a matrix, all elements will be converted to number.
   *
   * Syntax:
   *
   *    math.number(value)
   *    math.number(unit, valuelessUnit)
   *
   * Examples:
   *
   *    math.number(2)                         // returns number 2
   *    math.number('7.2')                     // returns number 7.2
   *    math.number(true)                      // returns number 1
   *    math.number([true, false, true, true]) // returns [1, 0, 1, 1]
   *    math.number(math.unit('52cm'), 'm')    // returns 0.52
   *
   * See also:
   *
   *    bignumber, bigint, boolean, numeric, complex, index, matrix, string, unit
   *
   * @param {string | number | BigNumber | Fraction | boolean | Array | Matrix | Unit | null} [value]  Value to be converted
   * @param {Unit | string} [valuelessUnit] A valueless unit, used to convert a unit to a number
   * @return {number | Array | Matrix} The created number
   */
  var number = typed('number', {
    '': function _() {
      return 0;
    },
    number: function number(x) {
      return x;
    },
    string: function string(x) {
      if (x === 'NaN') return NaN;
      var nonDecimalNumberParts = getNonDecimalNumberParts(x);
      if (nonDecimalNumberParts) {
        return makeNumberFromNonDecimalParts(nonDecimalNumberParts);
      }
      var size = 0;
      var wordSizeSuffixMatch = x.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);
      if (wordSizeSuffixMatch) {
        // x includes a size suffix like 0xffffi32, so we extract
        // the suffix and remove it from x
        size = Number(wordSizeSuffixMatch[2]);
        x = wordSizeSuffixMatch[1];
      }
      var num = Number(x);
      if (isNaN(num)) {
        throw new SyntaxError('String "' + x + '" is not a valid number');
      }
      if (wordSizeSuffixMatch) {
        // x is a signed bin, oct, or hex literal
        // num is the value of string x if x is interpreted as unsigned
        if (num > 2 ** size - 1) {
          // literal is too large for size suffix
          throw new SyntaxError("String \"".concat(x, "\" is out of range"));
        }
        // check if the bit at index size - 1 is set and if so do the twos complement
        if (num >= 2 ** (size - 1)) {
          num = num - 2 ** size;
        }
      }
      return num;
    },
    BigNumber: function BigNumber(x) {
      return x.toNumber();
    },
    bigint: function bigint(x) {
      return Number(x);
    },
    Fraction: function Fraction(x) {
      return x.valueOf();
    },
    Unit: typed.referToSelf(self => x => {
      var clone = x.clone();
      clone.value = self(x.value);
      return clone;
    }),
    null: function _null(x) {
      return 0;
    },
    'Unit, string | Unit': function UnitStringUnit(unit, valuelessUnit) {
      return unit.toNumber(valuelessUnit);
    },
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });

  // reviver function to parse a JSON object like:
  //
  //     {"mathjs":"number","value":"2.3"}
  //
  // into a number 2.3
  number.fromJSON = function (json) {
    return parseFloat(json.value);
  };
  return number;
});

var name$4C = 'bigint';
var dependencies$4B = ['typed'];
var createBigint = /* #__PURE__ */factory(name$4C, dependencies$4B, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Create a bigint or convert a string, boolean, or unit to a bigint.
   * When value is a matrix, all elements will be converted to bigint.
   *
   * Syntax:
   *
   *    math.bigint(value)
   *
   * Examples:
   *
   *    math.bigint(2)                         // returns 2n
   *    math.bigint('123')                     // returns 123n
   *    math.bigint(true)                      // returns 1n
   *    math.bigint([true, false, true, true]) // returns [1n, 0n, 1n, 1n]
   *
   * See also:
   *
   *    number, bignumber, boolean, complex, index, matrix, string, unit
   *
   * @param {string | number | BigNumber | bigint | Fraction | boolean | Array | Matrix | null} [value]  Value to be converted
   * @return {bigint | Array | Matrix} The created bigint
   */
  var bigint = typed('bigint', {
    '': function _() {
      return 0n;
    },
    bigint: function bigint(x) {
      return x;
    },
    number: function number(x) {
      return BigInt(x.toFixed());
    },
    BigNumber: function BigNumber(x) {
      return BigInt(x.round().toString());
    },
    Fraction: function Fraction(x) {
      return BigInt(x.valueOf().toFixed());
    },
    'string | boolean': function stringBoolean(x) {
      return BigInt(x);
    },
    null: function _null(x) {
      return 0n;
    },
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });

  // reviver function to parse a JSON object like:
  //
  //     {"mathjs":"bigint","value":"123"}
  //
  // into a bigint 123n
  bigint.fromJSON = function (json) {
    return BigInt(json.value);
  };
  return bigint;
});

var name$4B = 'string';
var dependencies$4A = ['typed'];
var createString = /* #__PURE__ */factory(name$4B, dependencies$4A, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Create a string or convert any object into a string.
   * Elements of Arrays and Matrices are processed element wise.
   *
   * Syntax:
   *
   *    math.string(value)
   *
   * Examples:
   *
   *    math.string(4.2)               // returns string '4.2'
   *    math.string(math.complex(3, 2) // returns string '3 + 2i'
   *
   *    const u = math.unit(5, 'km')
   *    math.string(u.to('m'))         // returns string '5000 m'
   *
   *    math.string([true, false])     // returns ['true', 'false']
   *
   * See also:
   *
   *    bignumber, boolean, complex, index, matrix, number, unit
   *
   * @param {* | Array | Matrix | null} [value]  A value to convert to a string
   * @return {string | Array | Matrix} The created string
   */
  return typed(name$4B, {
    '': function _() {
      return '';
    },
    number: format$2,
    null: function _null(x) {
      return 'null';
    },
    boolean: function boolean(x) {
      return x + '';
    },
    string: function string(x) {
      return x;
    },
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self)),
    any: function any(x) {
      return String(x);
    }
  });
});

var name$4A = 'boolean';
var dependencies$4z = ['typed'];
var createBoolean = /* #__PURE__ */factory(name$4A, dependencies$4z, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Create a boolean or convert a string or number to a boolean.
   * In case of a number, `true` is returned for non-zero numbers, and `false` in
   * case of zero.
   * Strings can be `'true'` or `'false'`, or can contain a number.
   * When value is a matrix, all elements will be converted to boolean.
   *
   * Syntax:
   *
   *    math.boolean(x)
   *
   * Examples:
   *
   *    math.boolean(0)     // returns false
   *    math.boolean(1)     // returns true
   *    math.boolean(-3)     // returns true
   *    math.boolean('true')     // returns true
   *    math.boolean('false')     // returns false
   *    math.boolean([1, 0, 1, 1])     // returns [true, false, true, true]
   *
   * See also:
   *
   *    bignumber, complex, index, matrix, string, unit
   *
   * @param {string | number | boolean | Array | Matrix | null} value  A value of any type
   * @return {boolean | Array | Matrix} The boolean value
   */
  return typed(name$4A, {
    '': function _() {
      return false;
    },
    boolean: function boolean(x) {
      return x;
    },
    number: function number(x) {
      return !!x;
    },
    null: function _null(x) {
      return false;
    },
    BigNumber: function BigNumber(x) {
      return !x.isZero();
    },
    string: function string(x) {
      // try case insensitive
      var lcase = x.toLowerCase();
      if (lcase === 'true') {
        return true;
      } else if (lcase === 'false') {
        return false;
      }

      // test whether value is a valid number
      var num = Number(x);
      if (x !== '' && !isNaN(num)) {
        return !!num;
      }
      throw new Error('Cannot convert "' + x + '" to a boolean');
    },
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$4z = 'bignumber';
var dependencies$4y = ['typed', 'BigNumber'];
var createBignumber = /* #__PURE__ */factory(name$4z, dependencies$4y, _ref => {
  var {
    typed,
    BigNumber
  } = _ref;
  /**
   * Create a BigNumber, which can store numbers with arbitrary precision.
   * When a matrix is provided, all elements will be converted to BigNumber.
   *
   * Syntax:
   *
   *    math.bignumber(x)
   *
   * Examples:
   *
   *    0.1 + 0.2                                  // returns number 0.30000000000000004
   *    math.bignumber(0.1) + math.bignumber(0.2)  // returns BigNumber 0.3
   *
   *
   *    7.2e500                                    // returns number Infinity
   *    math.bignumber('7.2e500')                  // returns BigNumber 7.2e500
   *
   * See also:
   *
   *    number, bigint, boolean, complex, index, matrix, string, unit
   *
   * @param {number | string | Fraction | BigNumber | bigint | Array | Matrix | boolean | null} [value]  Value for the big number,
   *                                                    0 by default.
   * @returns {BigNumber} The created bignumber
   */
  return typed('bignumber', {
    '': function _() {
      return new BigNumber(0);
    },
    number: function number(x) {
      // convert to string to prevent errors in case of >15 digits
      return new BigNumber(x + '');
    },
    string: function string(x) {
      var wordSizeSuffixMatch = x.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);
      if (wordSizeSuffixMatch) {
        // x has a word size suffix
        var size = wordSizeSuffixMatch[2];
        var n = BigNumber(wordSizeSuffixMatch[1]);
        var twoPowSize = new BigNumber(2).pow(Number(size));
        if (n.gt(twoPowSize.sub(1))) {
          throw new SyntaxError("String \"".concat(x, "\" is out of range"));
        }
        var twoPowSizeSubOne = new BigNumber(2).pow(Number(size) - 1);
        if (n.gte(twoPowSizeSubOne)) {
          return n.sub(twoPowSize);
        } else {
          return n;
        }
      }
      return new BigNumber(x);
    },
    BigNumber: function BigNumber(x) {
      // we assume a BigNumber is immutable
      return x;
    },
    bigint: function bigint(x) {
      return new BigNumber(x.toString());
    },
    Unit: typed.referToSelf(self => x => {
      var clone = x.clone();
      clone.value = self(x.value);
      return clone;
    }),
    Fraction: function Fraction(x) {
      return new BigNumber(x.n).div(x.d).times(x.s);
    },
    null: function _null(x) {
      return new BigNumber(0);
    },
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$4y = 'complex';
var dependencies$4x = ['typed', 'Complex'];
var createComplex = /* #__PURE__ */factory(name$4y, dependencies$4x, _ref => {
  var {
    typed,
    Complex
  } = _ref;
  /**
   * Create a complex value or convert a value to a complex value.
   *
   * Syntax:
   *
   *     math.complex()                           // creates a complex value with zero
   *                                              // as real and imaginary part.
   *     math.complex(re : number, im : string)   // creates a complex value with provided
   *                                              // values for real and imaginary part.
   *     math.complex(re : number)                // creates a complex value with provided
   *                                              // real value and zero imaginary part.
   *     math.complex(complex : Complex)          // clones the provided complex value.
   *     math.complex(arg : string)               // parses a string into a complex value.
   *     math.complex(array : Array)              // converts the elements of the array
   *                                              // or matrix element wise into a
   *                                              // complex value.
   *     math.complex({re: number, im: number})   // creates a complex value with provided
   *                                              // values for real an imaginary part.
   *     math.complex({r: number, phi: number})   // creates a complex value with provided
   *                                              // polar coordinates
   *
   * Examples:
   *
   *    const a = math.complex(3, -4)     // a = Complex 3 - 4i
   *    a.re = 5                          // a = Complex 5 - 4i
   *    const i = a.im                    // Number -4
   *    const b = math.complex('2 + 6i')  // Complex 2 + 6i
   *    const c = math.complex()          // Complex 0 + 0i
   *    const d = math.add(a, b)          // Complex 5 + 2i
   *
   * See also:
   *
   *    bignumber, boolean, index, matrix, number, string, unit
   *
   * @param {* | Array | Matrix} [args]
   *            Arguments specifying the real and imaginary part of the complex number
   * @return {Complex | Array | Matrix} Returns a complex value
   */
  return typed('complex', {
    '': function _() {
      return Complex.ZERO;
    },
    number: function number(x) {
      return new Complex(x, 0);
    },
    'number, number': function numberNumber(re, im) {
      return new Complex(re, im);
    },
    // TODO: this signature should be redundant
    'BigNumber, BigNumber': function BigNumberBigNumber(re, im) {
      return new Complex(re.toNumber(), im.toNumber());
    },
    Fraction: function Fraction(x) {
      return new Complex(x.valueOf(), 0);
    },
    Complex: function Complex(x) {
      return x.clone();
    },
    string: function string(x) {
      return Complex(x); // for example '2 + 3i'
    },
    null: function _null(x) {
      return Complex(0);
    },
    Object: function Object(x) {
      if ('re' in x && 'im' in x) {
        return new Complex(x.re, x.im);
      }
      if ('r' in x && 'phi' in x || 'abs' in x && 'arg' in x) {
        return new Complex(x);
      }
      throw new Error('Expected object with properties (re and im) or (r and phi) or (abs and arg)');
    },
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$4x = 'fraction';
var dependencies$4w = ['typed', 'Fraction'];
var createFraction = /* #__PURE__ */factory(name$4x, dependencies$4w, _ref => {
  var {
    typed,
    Fraction
  } = _ref;
  /**
   * Create a fraction or convert a value to a fraction.
   *
   * With one numeric argument, produces the closest rational approximation to the
   * input.
   * With two arguments, the first is the numerator and the second is the denominator,
   * and creates the corresponding fraction. Both numerator and denominator must be
   * integers.
   * With one object argument, looks for the integer numerator as the value of property
   * 'n' and the integer denominator as the value of property 'd'.
   * With a matrix argument, creates a matrix of the same shape with entries
   * converted into fractions.
   *
   * Syntax:
   *     math.fraction(value)
   *     math.fraction(numerator, denominator)
   *     math.fraction({n: numerator, d: denominator})
   *     math.fraction(matrix: Array | Matrix)
   *
   * Examples:
   *
   *     math.fraction(6.283)             // returns Fraction 6283/1000
   *     math.fraction(1, 3)              // returns Fraction 1/3
   *     math.fraction('2/3')             // returns Fraction 2/3
   *     math.fraction({n: 2, d: 3})      // returns Fraction 2/3
   *     math.fraction([0.2, 0.25, 1.25]) // returns Array [1/5, 1/4, 5/4]
   *     math.fraction(4, 5.1)            // throws Error: Parameters must be integer
   *
   * See also:
   *
   *    bignumber, number, string, unit
   *
   * @param {number | string | Fraction | BigNumber | bigint | Unit | Array | Matrix} [args]
   *            Arguments specifying the value, or numerator and denominator of
   *            the fraction
   * @return {Fraction | Array | Matrix} Returns a fraction
   */
  return typed('fraction', {
    number: function number(x) {
      if (!isFinite(x) || isNaN(x)) {
        throw new Error(x + ' cannot be represented as a fraction');
      }
      return new Fraction(x);
    },
    string: function string(x) {
      return new Fraction(x);
    },
    'number, number': function numberNumber(numerator, denominator) {
      return new Fraction(numerator, denominator);
    },
    null: function _null(x) {
      return new Fraction(0);
    },
    BigNumber: function BigNumber(x) {
      return new Fraction(x.toString());
    },
    bigint: function bigint(x) {
      return new Fraction(x.toString());
    },
    Fraction: function Fraction(x) {
      return x; // fractions are immutable
    },
    Unit: typed.referToSelf(self => x => {
      var clone = x.clone();
      clone.value = self(x.value);
      return clone;
    }),
    Object: function Object(x) {
      return new Fraction(x);
    },
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$4w = 'matrix';
var dependencies$4v = ['typed', 'Matrix', 'DenseMatrix', 'SparseMatrix'];
var createMatrix = /* #__PURE__ */factory(name$4w, dependencies$4v, _ref => {
  var {
    typed,
    Matrix,
    DenseMatrix,
    SparseMatrix
  } = _ref;
  /**
   * Create a Matrix. The function creates a new `math.Matrix` object from
   * an `Array`. A Matrix has utility functions to manipulate the data in the
   * matrix, like getting the size and getting or setting values in the matrix.
   * Supported storage formats are 'dense' and 'sparse'.
   *
   * Syntax:
   *
   *    math.matrix()                         // creates an empty matrix using default storage format (dense).
   *    math.matrix(data)                     // creates a matrix with initial data using default storage format (dense).
   *    math.matrix('dense')                  // creates an empty matrix using the given storage format.
   *    math.matrix(data, 'dense')            // creates a matrix with initial data using the given storage format.
   *    math.matrix(data, 'sparse')           // creates a sparse matrix with initial data.
   *    math.matrix(data, 'sparse', 'number') // creates a sparse matrix with initial data, number data type.
   *
   * Examples:
   *
   *    let m = math.matrix([[1, 2], [3, 4]])
   *    m.size()                        // Array [2, 2]
   *    m.resize([3, 2], 5)
   *    m.valueOf()                     // Array [[1, 2], [3, 4], [5, 5]]
   *    m.get([1, 0])                    // number 3
   *
   * See also:
   *
   *    bignumber, boolean, complex, index, number, string, unit, sparse
   *
   * @param {Array | Matrix} [data]    A multi dimensional array
   * @param {string} [format]          The Matrix storage format, either `'dense'` or `'sparse'`
   * @param {string} [datatype]        Type of the values
   *
   * @return {Matrix} The created matrix
   */
  return typed(name$4w, {
    '': function _() {
      return _create([]);
    },
    string: function string(format) {
      return _create([], format);
    },
    'string, string': function stringString(format, datatype) {
      return _create([], format, datatype);
    },
    Array: function Array(data) {
      return _create(data);
    },
    Matrix: function Matrix(data) {
      return _create(data, data.storage());
    },
    'Array | Matrix, string': _create,
    'Array | Matrix, string, string': _create
  });

  /**
   * Create a new Matrix with given storage format
   * @param {Array} data
   * @param {string} [format]
   * @param {string} [datatype]
   * @returns {Matrix} Returns a new Matrix
   * @private
   */
  function _create(data, format, datatype) {
    // get storage format constructor
    if (format === 'dense' || format === 'default' || format === undefined) {
      return new DenseMatrix(data, datatype);
    }
    if (format === 'sparse') {
      return new SparseMatrix(data, datatype);
    }
    throw new TypeError('Unknown matrix type ' + JSON.stringify(format) + '.');
  }
});

var name$4v = 'matrixFromFunction';
var dependencies$4u = ['typed', 'matrix', 'isZero'];
var createMatrixFromFunction = /* #__PURE__ */factory(name$4v, dependencies$4u, _ref => {
  var {
    typed,
    matrix,
    isZero
  } = _ref;
  /**
   * Create a matrix by evaluating a generating function at each index.
   * The simplest overload returns a multi-dimensional array as long as `size` is an array.
   * Passing `size` as a Matrix or specifying a `format` will result in returning a Matrix.
   *
   * Syntax:
   *
   *    math.matrixFromFunction(size, fn)
   *    math.matrixFromFunction(size, fn, format)
   *    math.matrixFromFunction(size, fn, format, datatype)
   *    math.matrixFromFunction(size, format, fn)
   *    math.matrixFromFunction(size, format, datatype, fn)
   *
   * Examples:
   *
   *    math.matrixFromFunction([3,3], i => i[0] - i[1]) // an antisymmetric matrix
   *    math.matrixFromFunction([100, 100], 'sparse', i => i[0] - i[1] === 1 ? 4 : 0) // a sparse subdiagonal matrix
   *    math.matrixFromFunction([5], i => math.random()) // a random vector
   *
   * See also:
   *
   *    matrix, zeros
   *
   * @param {Array | Matrix} size   The size of the matrix to be created
   * @param {function} fn           Callback function invoked for every entry in the matrix
   * @param {string} [format]       The Matrix storage format, either `'dense'` or `'sparse'`
   * @param {string} [datatype]     Type of the values
   * @return {Array | Matrix} Returns the created matrix
   */
  return typed(name$4v, {
    'Array | Matrix, function, string, string': function ArrayMatrixFunctionStringString(size, fn, format, datatype) {
      return _create(size, fn, format, datatype);
    },
    'Array | Matrix, function, string': function ArrayMatrixFunctionString(size, fn, format) {
      return _create(size, fn, format);
    },
    'Matrix, function': function MatrixFunction(size, fn) {
      return _create(size, fn, 'dense');
    },
    'Array, function': function ArrayFunction(size, fn) {
      return _create(size, fn, 'dense').toArray();
    },
    'Array | Matrix, string, function': function ArrayMatrixStringFunction(size, format, fn) {
      return _create(size, fn, format);
    },
    'Array | Matrix, string, string, function': function ArrayMatrixStringStringFunction(size, format, datatype, fn) {
      return _create(size, fn, format, datatype);
    }
  });
  function _create(size, fn, format, datatype) {
    var m;
    if (datatype !== undefined) {
      m = matrix(format, datatype);
    } else {
      m = matrix(format);
    }
    m.resize(size);
    m.forEach(function (_, index) {
      var val = fn(index);
      if (isZero(val)) return;
      m.set(index, val);
    });
    return m;
  }
});

var name$4u = 'matrixFromRows';
var dependencies$4t = ['typed', 'matrix', 'flatten', 'size'];
var createMatrixFromRows = /* #__PURE__ */factory(name$4u, dependencies$4t, _ref => {
  var {
    typed,
    matrix,
    flatten,
    size
  } = _ref;
  /**
   * Create a dense matrix from vectors as individual rows.
   * If you pass column vectors, they will be transposed (but not conjugated!)
   *
   * Syntax:
   *
   *    math.matrixFromRows(...arr)
   *    math.matrixFromRows(row1, row2)
   *    math.matrixFromRows(row1, row2, row3)
   *
   * Examples:
   *
   *    math.matrixFromRows([1, 2, 3], [[4],[5],[6]])
   *    math.matrixFromRows(...vectors)
   *
   * See also:
   *
   *    matrix, matrixFromColumns, matrixFromFunction, zeros
   *
   * @param {... Array | Matrix} rows  Multiple rows
   * @return { number[][] | Matrix } if at least one of the arguments is an array, an array will be returned
   */
  return typed(name$4u, {
    '...Array': function Array(arr) {
      return _createArray(arr);
    },
    '...Matrix': function Matrix(arr) {
      return matrix(_createArray(arr.map(m => m.toArray())));
    }

    // TODO implement this properly for SparseMatrix
  });
  function _createArray(arr) {
    if (arr.length === 0) throw new TypeError('At least one row is needed to construct a matrix.');
    var N = checkVectorTypeAndReturnLength(arr[0]);
    var result = [];
    for (var row of arr) {
      var rowLength = checkVectorTypeAndReturnLength(row);
      if (rowLength !== N) {
        throw new TypeError('The vectors had different length: ' + (N | 0) + ' ≠ ' + (rowLength | 0));
      }
      result.push(flatten(row));
    }
    return result;
  }
  function checkVectorTypeAndReturnLength(vec) {
    var s = size(vec);
    if (s.length === 1) {
      // 1D vector
      return s[0];
    } else if (s.length === 2) {
      // 2D vector
      if (s[0] === 1) {
        // row vector
        return s[1];
      } else if (s[1] === 1) {
        // col vector
        return s[0];
      } else {
        throw new TypeError('At least one of the arguments is not a vector.');
      }
    } else {
      throw new TypeError('Only one- or two-dimensional vectors are supported.');
    }
  }
});

var name$4t = 'matrixFromColumns';
var dependencies$4s = ['typed', 'matrix', 'flatten', 'size'];
var createMatrixFromColumns = /* #__PURE__ */factory(name$4t, dependencies$4s, _ref => {
  var {
    typed,
    matrix,
    flatten,
    size
  } = _ref;
  /**
   * Create a dense matrix from vectors as individual columns.
   * If you pass row vectors, they will be transposed (but not conjugated!)
   *
   * Syntax:
   *
   *    math.matrixFromColumns(...arr)
   *    math.matrixFromColumns(col1, col2)
   *    math.matrixFromColumns(col1, col2, col3)
   *
   * Examples:
   *
   *    math.matrixFromColumns([1, 2, 3], [[4],[5],[6]])
   *    math.matrixFromColumns(...vectors)
   *
   * See also:
   *
   *    matrix, matrixFromRows, matrixFromFunction, zeros
   *
   * @param {... Array | Matrix} cols Multiple columns
   * @return { number[][] | Matrix } if at least one of the arguments is an array, an array will be returned
   */
  return typed(name$4t, {
    '...Array': function Array(arr) {
      return _createArray(arr);
    },
    '...Matrix': function Matrix(arr) {
      return matrix(_createArray(arr.map(m => m.toArray())));
    }

    // TODO implement this properly for SparseMatrix
  });
  function _createArray(arr) {
    if (arr.length === 0) throw new TypeError('At least one column is needed to construct a matrix.');
    var N = checkVectorTypeAndReturnLength(arr[0]);

    // create an array with empty rows
    var result = [];
    for (var i = 0; i < N; i++) {
      result[i] = [];
    }

    // loop columns
    for (var col of arr) {
      var colLength = checkVectorTypeAndReturnLength(col);
      if (colLength !== N) {
        throw new TypeError('The vectors had different length: ' + (N | 0) + ' ≠ ' + (colLength | 0));
      }
      var f = flatten(col);

      // push a value to each row
      for (var _i = 0; _i < N; _i++) {
        result[_i].push(f[_i]);
      }
    }
    return result;
  }
  function checkVectorTypeAndReturnLength(vec) {
    var s = size(vec);
    if (s.length === 1) {
      // 1D vector
      return s[0];
    } else if (s.length === 2) {
      // 2D vector
      if (s[0] === 1) {
        // row vector
        return s[1];
      } else if (s[1] === 1) {
        // col vector
        return s[0];
      } else {
        throw new TypeError('At least one of the arguments is not a vector.');
      }
    } else {
      throw new TypeError('Only one- or two-dimensional vectors are supported.');
    }
  }
});

var name$4s = 'splitUnit';
var dependencies$4r = ['typed'];
var createSplitUnit = /* #__PURE__ */factory(name$4s, dependencies$4r, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Split a unit in an array of units whose sum is equal to the original unit.
   *
   * Syntax:
   *
   *     math.splitUnit(unit: Unit, parts: Array.<Unit>)
   *
   * Example:
   *
   *     math.splitUnit(new Unit(1, 'm'), ['feet', 'inch'])
   *     // [ 3 feet, 3.3700787401575 inch ]
   *
   * See also:
   *
   *     unit
   *
   * @param {Array} [parts] An array of strings or valueless units.
   * @return {Array} An array of units.
   */
  return typed(name$4s, {
    'Unit, Array': function UnitArray(unit, parts) {
      return unit.splitUnit(parts);
    }
  });
});

var name$4r = 'unaryMinus';
var dependencies$4q = ['typed'];
var createUnaryMinus = /* #__PURE__ */factory(name$4r, dependencies$4q, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Inverse the sign of a value, apply a unary minus operation.
   *
   * For matrices, the function is evaluated element wise. Boolean values and
   * strings will be converted to a number. For complex numbers, both real and
   * complex value are inverted.
   *
   * Syntax:
   *
   *    math.unaryMinus(x)
   *
   * Examples:
   *
   *    math.unaryMinus(3.5)      // returns -3.5
   *    math.unaryMinus(-4.2)     // returns 4.2
   *
   * See also:
   *
   *    add, subtract, unaryPlus
   *
   * @param  {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} x Number to be inverted.
   * @return {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} Returns the value with inverted sign.
   */
  return typed(name$4r, {
    number: unaryMinusNumber,
    'Complex | BigNumber | Fraction': x => x.neg(),
    bigint: x => -x,
    Unit: typed.referToSelf(self => x => {
      var res = x.clone();
      res.value = typed.find(self, res.valueType())(x.value);
      return res;
    }),
    // deep map collection, skip zeros since unaryMinus(0) = 0
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))

    // TODO: add support for string
  });
});

var name$4q = 'unaryPlus';
var dependencies$4p = ['typed', 'config', 'numeric'];
var createUnaryPlus = /* #__PURE__ */factory(name$4q, dependencies$4p, _ref => {
  var {
    typed,
    config,
    numeric
  } = _ref;
  /**
   * Unary plus operation.
   * Boolean values and strings will be converted to a number, numeric values will be returned as is.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.unaryPlus(x)
   *
   * Examples:
   *
   *    math.unaryPlus(3.5)      // returns 3.5
   *    math.unaryPlus(1)     // returns 1
   *
   * See also:
   *
   *    unaryMinus, add, subtract
   *
   * @param  {number | BigNumber | bigint | Fraction | string | Complex | Unit | Array | Matrix} x
   *            Input value
   * @return {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix}
   *            Returns the input value when numeric, converts to a number when input is non-numeric.
   */
  return typed(name$4q, {
    number: unaryPlusNumber,
    Complex: function Complex(x) {
      return x; // complex numbers are immutable
    },
    BigNumber: function BigNumber(x) {
      return x; // bignumbers are immutable
    },
    bigint: function bigint(x) {
      return x;
    },
    Fraction: function Fraction(x) {
      return x; // fractions are immutable
    },
    Unit: function Unit(x) {
      return x.clone();
    },
    // deep map collection, skip zeros since unaryPlus(0) = 0
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self)),
    boolean: function boolean(x) {
      return numeric(x ? 1 : 0, config.number);
    },
    string: function string(x) {
      return numeric(x, safeNumberType(x, config));
    }
  });
});

var name$4p = 'abs';
var dependencies$4o = ['typed'];
var createAbs = /* #__PURE__ */factory(name$4p, dependencies$4o, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Calculate the absolute value of a number. For matrices, the function is
   * evaluated element wise.
   *
   * Syntax:
   *
   *    math.abs(x)
   *
   * Examples:
   *
   *    math.abs(3.5)                // returns number 3.5
   *    math.abs(-4.2)               // returns number 4.2
   *
   *    math.abs([3, -5, -1, 0, 2])  // returns Array [3, 5, 1, 0, 2]
   *
   * See also:
   *
   *    sign
   *
   * @param  {number | BigNumber | bigint | Fraction | Complex | Array | Matrix | Unit} x
   *            A number or matrix for which to get the absolute value
   * @return {number | BigNumber | bigint | Fraction | Complex | Array | Matrix | Unit}
   *            Absolute value of `x`
   */
  return typed(name$4p, {
    number: absNumber,
    'Complex | BigNumber | Fraction | Unit': x => x.abs(),
    bigint: x => x < 0n ? -x : x,
    // deep map collection, skip zeros since abs(0) = 0
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$4o = 'apply';
var dependencies$4n = ['typed', 'isInteger'];
var createApply = /* #__PURE__ */factory(name$4o, dependencies$4n, _ref => {
  var {
    typed,
    isInteger
  } = _ref;
  /**
   * Apply a function that maps an array to a scalar
   * along a given axis of a matrix or array.
   * Returns a new matrix or array with one less dimension than the input.
   *
   * Syntax:
   *
   *     math.apply(A, dim, callback)
   *
   * Where:
   *
   * - `dim: number` is a zero-based dimension over which to concatenate the matrices.
   *
   * Examples:
   *
   *    const A = [[1, 2], [3, 4]]
   *    const sum = math.sum
   *
   *    math.apply(A, 0, sum)             // returns [4, 6]
   *    math.apply(A, 1, sum)             // returns [3, 7]
   *
   * See also:
   *
   *    map, filter, forEach
   *
   * @param {Array | Matrix} array   The input Matrix
   * @param {number} dim             The dimension along which the callback is applied
   * @param {Function} callback      The callback function that is applied. This Function
   *                                 should take an array or 1-d matrix as an input and
   *                                 return a number.
   * @return {Array | Matrix} res    The residual matrix with the function applied over some dimension.
   */
  return typed(name$4o, {
    'Array | Matrix, number | BigNumber, function': function ArrayMatrixNumberBigNumberFunction(mat, dim, callback) {
      if (!isInteger(dim)) {
        throw new TypeError('Integer number expected for dimension');
      }
      var size = Array.isArray(mat) ? arraySize(mat) : mat.size();
      if (dim < 0 || dim >= size.length) {
        throw new IndexError(dim, size.length);
      }
      if (isMatrix(mat)) {
        return mat.create(_apply(mat.valueOf(), dim, callback));
      } else {
        return _apply(mat, dim, callback);
      }
    }
  });
});

/**
 * Recursively reduce a matrix
 * @param {Array} mat
 * @param {number} dim
 * @param {Function} callback
 * @returns {Array} ret
 * @private
 */
function _apply(mat, dim, callback) {
  var i, ret, tran;
  if (dim <= 0) {
    if (!Array.isArray(mat[0])) {
      return callback(mat);
    } else {
      tran = _switch(mat);
      ret = [];
      for (i = 0; i < tran.length; i++) {
        ret[i] = _apply(tran[i], dim - 1, callback);
      }
      return ret;
    }
  } else {
    ret = [];
    for (i = 0; i < mat.length; i++) {
      ret[i] = _apply(mat[i], dim - 1, callback);
    }
    return ret;
  }
}

/**
 * Transpose a matrix
 * @param {Array} mat
 * @returns {Array} ret
 * @private
 */
function _switch(mat) {
  var I = mat.length;
  var J = mat[0].length;
  var i, j;
  var ret = [];
  for (j = 0; j < J; j++) {
    var tmp = [];
    for (i = 0; i < I; i++) {
      tmp.push(mat[i][j]);
    }
    ret.push(tmp);
  }
  return ret;
}

var name$4n = 'addScalar';
var dependencies$4m = ['typed'];
var createAddScalar = /* #__PURE__ */factory(name$4n, dependencies$4m, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Add two scalar values, `x + y`.
   * This function is meant for internal use: it is used by the public function
   * `add`
   *
   * This function does not support collections (Array or Matrix).
   *
   * @param  {number | BigNumber | bigint | Fraction | Complex | Unit} x   First value to add
   * @param  {number | BigNumber | bigint | Fraction | Complex} y          Second value to add
   * @return {number | BigNumber | bigint | Fraction | Complex | Unit}     Sum of `x` and `y`
   * @private
   */
  return typed(name$4n, {
    'number, number': addNumber,
    'Complex, Complex': function ComplexComplex(x, y) {
      return x.add(y);
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      return x.plus(y);
    },
    'bigint, bigint': function bigintBigint(x, y) {
      return x + y;
    },
    'Fraction, Fraction': function FractionFraction(x, y) {
      return x.add(y);
    },
    'Unit, Unit': typed.referToSelf(self => (x, y) => {
      if (x.value === null || x.value === undefined) {
        throw new Error('Parameter x contains a unit with undefined value');
      }
      if (y.value === null || y.value === undefined) {
        throw new Error('Parameter y contains a unit with undefined value');
      }
      if (!x.equalBase(y)) throw new Error('Units do not match');
      var res = x.clone();
      res.value = typed.find(self, [res.valueType(), y.valueType()])(res.value, y.value);
      res.fixPrefix = false;
      return res;
    })
  });
});

var name$4m = 'subtractScalar';
var dependencies$4l = ['typed'];
var createSubtractScalar = /* #__PURE__ */factory(name$4m, dependencies$4l, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Subtract two scalar values, `x - y`.
   * This function is meant for internal use: it is used by the public function
   * `subtract`
   *
   * This function does not support collections (Array or Matrix).
   *
   * @param  {number | BigNumber | bigint | Fraction | Complex | Unit} x   First value
   * @param  {number | BigNumber | bigint | Fraction | Complex} y          Second value to be subtracted from `x`
   * @return {number | BigNumber | bigint | Fraction | Complex | Unit}     Difference of `x` and `y`
   * @private
   */
  return typed(name$4m, {
    'number, number': subtractNumber,
    'Complex, Complex': function ComplexComplex(x, y) {
      return x.sub(y);
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      return x.minus(y);
    },
    'bigint, bigint': function bigintBigint(x, y) {
      return x - y;
    },
    'Fraction, Fraction': function FractionFraction(x, y) {
      return x.sub(y);
    },
    'Unit, Unit': typed.referToSelf(self => (x, y) => {
      if (x.value === null || x.value === undefined) {
        throw new Error('Parameter x contains a unit with undefined value');
      }
      if (y.value === null || y.value === undefined) {
        throw new Error('Parameter y contains a unit with undefined value');
      }
      if (!x.equalBase(y)) throw new Error('Units do not match');
      var res = x.clone();
      res.value = typed.find(self, [res.valueType(), y.valueType()])(res.value, y.value);
      res.fixPrefix = false;
      return res;
    })
  });
});

var name$4l = 'cbrt';
var dependencies$4k = ['config', 'typed', 'isNegative', 'unaryMinus', 'matrix', 'Complex', 'BigNumber', 'Fraction'];
var createCbrt = /* #__PURE__ */factory(name$4l, dependencies$4k, _ref => {
  var {
    config,
    typed,
    isNegative,
    unaryMinus,
    matrix,
    Complex,
    BigNumber,
    Fraction
  } = _ref;
  /**
   * Calculate the cubic root of a value.
   *
   * To avoid confusion with the matrix cube root, this function does not
   * apply to matrices. For a matrix, to take the cube root elementwise,
   * see the examples.
   *
   * Syntax:
   *
   *    math.cbrt(x)
   *    math.cbrt(x, allRoots)
   *
   * Examples:
   *
   *    math.cbrt(27)                  // returns 3
   *    math.cube(3)                   // returns 27
   *    math.cbrt(-64)                 // returns -4
   *    math.cbrt(math.unit('27 m^3')) // returns Unit 3 m
   *    math.map([27, 64, 125], x => math.cbrt(x))       // returns [3, 4, 5]
   *
   *    const x = math.complex('8i')
   *    math.cbrt(x)                   // returns Complex 1.7320508075689 + i
   *    math.cbrt(x, true)             // returns Matrix [
   *                                    //    1.7320508075689 + i
   *                                    //   -1.7320508075689 + i
   *                                    //   -2i
   *                                    // ]
   *
   * See also:
   *
   *    square, sqrt, cube
   *
   * @param {number | BigNumber | Complex | Unit} x
   *            Value for which to calculate the cubic root.
   * @param {boolean} [allRoots]  Optional, false by default. Only applicable
   *            when `x` is a number or complex number. If true, all complex
   *            roots are returned, if false (default) the principal root is
   *            returned.
   * @return {number | BigNumber | Complex | Unit}
   *            Returns the cubic root of `x`
   */
  return typed(name$4l, {
    number: cbrtNumber,
    // note: signature 'number, boolean' is also supported,
    //       created by typed as it knows how to convert number to Complex

    Complex: _cbrtComplex,
    'Complex, boolean': _cbrtComplex,
    BigNumber: function BigNumber(x) {
      return x.cbrt();
    },
    Unit: _cbrtUnit
  });

  /**
   * Calculate the cubic root for a complex number
   * @param {Complex} x
   * @param {boolean} [allRoots]   If true, the function will return an array
   *                               with all three roots. If false or undefined,
   *                               the principal root is returned.
   * @returns {Complex | Array.<Complex> | Matrix.<Complex>} Returns the cubic root(s) of x
   * @private
   */
  function _cbrtComplex(x, allRoots) {
    // https://www.wikiwand.com/en/Cube_root#/Complex_numbers

    var arg3 = x.arg() / 3;
    var abs = x.abs();

    // principal root:
    var principal = new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3).exp());
    if (allRoots) {
      var all = [principal, new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3 + Math.PI * 2 / 3).exp()), new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3 - Math.PI * 2 / 3).exp())];
      return config.matrix === 'Array' ? all : matrix(all);
    } else {
      return principal;
    }
  }

  /**
   * Calculate the cubic root for a Unit
   * @param {Unit} x
   * @return {Unit} Returns the cubic root of x
   * @private
   */
  function _cbrtUnit(x) {
    if (x.value && isComplex(x.value)) {
      var result = x.clone();
      result.value = 1.0;
      result = result.pow(1.0 / 3); // Compute the units
      result.value = _cbrtComplex(x.value); // Compute the value
      return result;
    } else {
      var negate = isNegative(x.value);
      if (negate) {
        x.value = unaryMinus(x.value);
      }

      // TODO: create a helper function for this
      var third;
      if (isBigNumber(x.value)) {
        third = new BigNumber(1).div(3);
      } else if (isFraction(x.value)) {
        third = new Fraction(1, 3);
      } else {
        third = 1 / 3;
      }
      var _result = x.pow(third);
      if (negate) {
        _result.value = unaryMinus(_result.value);
      }
      return _result;
    }
  }
});

var name$4k = 'matAlgo11xS0s';
var dependencies$4j = ['typed', 'equalScalar'];
var createMatAlgo11xS0s = /* #__PURE__ */factory(name$4k, dependencies$4j, _ref => {
  var {
    typed,
    equalScalar
  } = _ref;
  /**
   * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b).
   * Callback function invoked NZ times (number of nonzero items in S).
   *
   *
   *          ┌  f(Sij, b)  ; S(i,j) !== 0
   * C(i,j) = ┤
   *          └  0          ; otherwise
   *
   *
   * @param {Matrix}   s                 The SparseMatrix instance (S)
   * @param {Scalar}   b                 The Scalar value
   * @param {Function} callback          The f(Aij,b) operation to invoke
   * @param {boolean}  inverse           A true value indicates callback should be invoked f(b,Sij)
   *
   * @return {Matrix}                    SparseMatrix (C)
   *
   * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813
   */
  return function matAlgo11xS0s(s, b, callback, inverse) {
    // sparse matrix arrays
    var avalues = s._values;
    var aindex = s._index;
    var aptr = s._ptr;
    var asize = s._size;
    var adt = s._datatype;

    // sparse matrix cannot be a Pattern matrix
    if (!avalues) {
      throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value');
    }

    // rows & columns
    var rows = asize[0];
    var columns = asize[1];

    // datatype
    var dt;
    // equal signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;
    // callback signature to use
    var cf = callback;

    // process data types
    if (typeof adt === 'string') {
      // datatype
      dt = adt;
      // find signature that matches (dt, dt)
      eq = typed.find(equalScalar, [dt, dt]);
      // convert 0 to the same datatype
      zero = typed.convert(0, dt);
      // convert b to the same datatype
      b = typed.convert(b, dt);
      // callback
      cf = typed.find(callback, [dt, dt]);
    }

    // result arrays
    var cvalues = [];
    var cindex = [];
    var cptr = [];

    // loop columns
    for (var j = 0; j < columns; j++) {
      // initialize ptr
      cptr[j] = cindex.length;
      // values in j
      for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
        // row
        var i = aindex[k];
        // invoke callback
        var v = inverse ? cf(b, avalues[k]) : cf(avalues[k], b);
        // check value is zero
        if (!eq(v, zero)) {
          // push index & value
          cindex.push(i);
          cvalues.push(v);
        }
      }
    }
    // update ptr
    cptr[columns] = cindex.length;

    // return sparse matrix
    return s.createSparseMatrix({
      values: cvalues,
      index: cindex,
      ptr: cptr,
      size: [rows, columns],
      datatype: dt
    });
  };
});

var name$4j = 'matAlgo12xSfs';
var dependencies$4i = ['typed', 'DenseMatrix'];
var createMatAlgo12xSfs = /* #__PURE__ */factory(name$4j, dependencies$4i, _ref => {
  var {
    typed,
    DenseMatrix
  } = _ref;
  /**
   * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b).
   * Callback function invoked MxN times.
   *
   *
   *          ┌  f(Sij, b)  ; S(i,j) !== 0
   * C(i,j) = ┤
   *          └  f(0, b)    ; otherwise
   *
   *
   * @param {Matrix}   s                 The SparseMatrix instance (S)
   * @param {Scalar}   b                 The Scalar value
   * @param {Function} callback          The f(Aij,b) operation to invoke
   * @param {boolean}  inverse           A true value indicates callback should be invoked f(b,Sij)
   *
   * @return {Matrix}                    DenseMatrix (C)
   *
   * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813
   */
  return function matAlgo12xSfs(s, b, callback, inverse) {
    // sparse matrix arrays
    var avalues = s._values;
    var aindex = s._index;
    var aptr = s._ptr;
    var asize = s._size;
    var adt = s._datatype;

    // sparse matrix cannot be a Pattern matrix
    if (!avalues) {
      throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value');
    }

    // rows & columns
    var rows = asize[0];
    var columns = asize[1];

    // datatype
    var dt;
    // callback signature to use
    var cf = callback;

    // process data types
    if (typeof adt === 'string') {
      // datatype
      dt = adt;
      // convert b to the same datatype
      b = typed.convert(b, dt);
      // callback
      cf = typed.find(callback, [dt, dt]);
    }

    // result arrays
    var cdata = [];

    // workspaces
    var x = [];
    // marks indicating we have a value in x for a given column
    var w = [];

    // loop columns
    for (var j = 0; j < columns; j++) {
      // columns mark
      var mark = j + 1;
      // values in j
      for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
        // row
        var r = aindex[k];
        // update workspace
        x[r] = avalues[k];
        w[r] = mark;
      }
      // loop rows
      for (var i = 0; i < rows; i++) {
        // initialize C on first column
        if (j === 0) {
          // create row array
          cdata[i] = [];
        }
        // check sparse matrix has a value @ i,j
        if (w[i] === mark) {
          // invoke callback, update C
          cdata[i][j] = inverse ? cf(b, x[i]) : cf(x[i], b);
        } else {
          // dense matrix value @ i, j
          cdata[i][j] = inverse ? cf(b, 0) : cf(0, b);
        }
      }
    }

    // return dense matrix
    return new DenseMatrix({
      data: cdata,
      size: [rows, columns],
      datatype: dt
    });
  };
});

var name$4i = 'matAlgo14xDs';
var dependencies$4h = ['typed'];
var createMatAlgo14xDs = /* #__PURE__ */factory(name$4i, dependencies$4h, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, b).
   * Callback function invoked MxN times.
   *
   * C(i,j,...z) = f(Aij..z, b)
   *
   * @param {Matrix}   a                 The DenseMatrix instance (A)
   * @param {Scalar}   b                 The Scalar value
   * @param {Function} callback          The f(Aij..z,b) operation to invoke
   * @param {boolean}  inverse           A true value indicates callback should be invoked f(b,Aij..z)
   *
   * @return {Matrix}                    DenseMatrix (C)
   *
   * https://github.com/josdejong/mathjs/pull/346#issuecomment-97659042
   */
  return function matAlgo14xDs(a, b, callback, inverse) {
    // a arrays
    var adata = a._data;
    var asize = a._size;
    var adt = a._datatype;

    // datatype
    var dt;
    // callback signature to use
    var cf = callback;

    // process data types
    if (typeof adt === 'string') {
      // datatype
      dt = adt;
      // convert b to the same datatype
      b = typed.convert(b, dt);
      // callback
      cf = typed.find(callback, [dt, dt]);
    }

    // populate cdata, iterate through dimensions
    var cdata = asize.length > 0 ? _iterate(cf, 0, asize, asize[0], adata, b, inverse) : [];

    // c matrix
    return a.createDenseMatrix({
      data: cdata,
      size: clone$2(asize),
      datatype: dt
    });
  };

  // recursive function
  function _iterate(f, level, s, n, av, bv, inverse) {
    // initialize array for this level
    var cv = [];
    // check we reach the last level
    if (level === s.length - 1) {
      // loop arrays in last level
      for (var i = 0; i < n; i++) {
        // invoke callback and store value
        cv[i] = inverse ? f(bv, av[i]) : f(av[i], bv);
      }
    } else {
      // iterate current level
      for (var j = 0; j < n; j++) {
        // iterate next level
        cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv, inverse);
      }
    }
    return cv;
  }
});

var name$4h = 'ceil';
var dependencies$4g = ['typed', 'config', 'round', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix'];
var createCeilNumber = /* #__PURE__ */factory(name$4h, ['typed', 'config', 'round'], _ref => {
  var {
    typed,
    config,
    round
  } = _ref;
  return typed(name$4h, {
    number: function number(x) {
      if (nearlyEqual$1(x, round(x), config.relTol, config.absTol)) {
        return round(x);
      } else {
        return Math.ceil(x);
      }
    },
    'number, number': function numberNumber(x, n) {
      if (nearlyEqual$1(x, round(x, n), config.relTol, config.absTol)) {
        return round(x, n);
      } else {
        var [number, exponent] = "".concat(x, "e").split('e');
        var result = Math.ceil(Number("".concat(number, "e").concat(Number(exponent) + n)));
        [number, exponent] = "".concat(result, "e").split('e');
        return Number("".concat(number, "e").concat(Number(exponent) - n));
      }
    }
  });
});
var createCeil = /* #__PURE__ */factory(name$4h, dependencies$4g, _ref2 => {
  var {
    typed,
    config,
    round,
    matrix,
    equalScalar,
    zeros,
    DenseMatrix
  } = _ref2;
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matAlgo14xDs = createMatAlgo14xDs({
    typed
  });
  var ceilNumber = createCeilNumber({
    typed,
    config,
    round
  });
  /**
   * Round a value towards plus infinity
   * If `x` is complex, both real and imaginary part are rounded towards plus infinity.
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.ceil(x)
   *    math.ceil(x, n)
   *
   * Examples:
   *
   *    math.ceil(3.2)               // returns number 4
   *    math.ceil(3.8)               // returns number 4
   *    math.ceil(-4.2)              // returns number -4
   *    math.ceil(-4.7)              // returns number -4
   *
   *    math.ceil(3.212, 2)          // returns number 3.22
   *    math.ceil(3.288, 2)          // returns number 3.29
   *    math.ceil(-4.212, 2)         // returns number -4.21
   *    math.ceil(-4.782, 2)         // returns number -4.78
   *
   *    const c = math.complex(3.24, -2.71)
   *    math.ceil(c)                 // returns Complex 4 - 2i
   *    math.ceil(c, 1)              // returns Complex 3.3 - 2.7i
   *
   *    math.ceil([3.2, 3.8, -4.7])  // returns Array [4, 4, -4]
   *    math.ceil([3.21, 3.82, -4.71], 1)  // returns Array [3.3, 3.9, -4.7]
   *
   * See also:
   *
   *    floor, fix, round
   *
   * @param  {number | BigNumber | Fraction | Complex | Array | Matrix} x  Number to be rounded
   * @param  {number | BigNumber | Array} [n=0]                            Number of decimals
   * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
   */
  return typed('ceil', {
    number: ceilNumber.signatures.number,
    'number,number': ceilNumber.signatures['number,number'],
    Complex: function Complex(x) {
      return x.ceil();
    },
    'Complex, number': function ComplexNumber(x, n) {
      return x.ceil(n);
    },
    'Complex, BigNumber': function ComplexBigNumber(x, n) {
      return x.ceil(n.toNumber());
    },
    BigNumber: function BigNumber(x) {
      if (nearlyEqual(x, round(x), config.relTol, config.absTol)) {
        return round(x);
      } else {
        return x.ceil();
      }
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(x, n) {
      if (nearlyEqual(x, round(x, n), config.relTol, config.absTol)) {
        return round(x, n);
      } else {
        return x.toDecimalPlaces(n.toNumber(), Decimal.ROUND_CEIL);
      }
    },
    Fraction: function Fraction(x) {
      return x.ceil();
    },
    'Fraction, number': function FractionNumber(x, n) {
      return x.ceil(n);
    },
    'Fraction, BigNumber': function FractionBigNumber(x, n) {
      return x.ceil(n.toNumber());
    },
    'Array | Matrix': typed.referToSelf(self => x => {
      // deep map collection, skip zeros since ceil(0) = 0
      return deepMap(x, self);
    }),
    'Array, number | BigNumber': typed.referToSelf(self => (x, n) => {
      // deep map collection, skip zeros since ceil(0) = 0
      return deepMap(x, i => self(i, n));
    }),
    'SparseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
      return matAlgo11xS0s(x, y, self, false);
    }),
    'DenseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
      return matAlgo14xDs(x, y, self, false);
    }),
    'number | Complex | Fraction | BigNumber, Array': typed.referToSelf(self => (x, y) => {
      // use matrix implementation
      return matAlgo14xDs(matrix(y), x, self, true).valueOf();
    }),
    'number | Complex | Fraction | BigNumber, Matrix': typed.referToSelf(self => (x, y) => {
      if (equalScalar(x, 0)) return zeros(y.size(), y.storage());
      if (y.storage() === 'dense') {
        return matAlgo14xDs(y, x, self, true);
      }
      return matAlgo12xSfs(y, x, self, true);
    })
  });
});

var name$4g = 'cube';
var dependencies$4f = ['typed'];
var createCube = /* #__PURE__ */factory(name$4g, dependencies$4f, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Compute the cube of a value, `x * x * x`.
   * To avoid confusion with `pow(M,3)`, this function does not apply to matrices.
   * If you wish to cube every entry of a matrix, see the examples.
   *
   * Syntax:
   *
   *    math.cube(x)
   *
   * Examples:
   *
   *    math.cube(2)            // returns number 8
   *    math.pow(2, 3)          // returns number 8
   *    math.cube(4)            // returns number 64
   *    4 * 4 * 4               // returns number 64
   *
   *    math.map([1, 2, 3, 4], math.cube) // returns Array [1, 8, 27, 64]
   *
   * See also:
   *
   *    multiply, square, pow, cbrt
   *
   * @param  {number | BigNumber | bigint | Fraction | Complex | Unit} x  Number for which to calculate the cube
   * @return {number | BigNumber | bigint | Fraction | Complex | Unit} Cube of x
   */
  return typed(name$4g, {
    number: cubeNumber,
    Complex: function Complex(x) {
      return x.mul(x).mul(x); // Is faster than pow(x, 3)
    },
    BigNumber: function BigNumber(x) {
      return x.times(x).times(x);
    },
    bigint: function bigint(x) {
      return x * x * x;
    },
    Fraction: function Fraction(x) {
      return x.pow(3); // Is faster than mul()mul()mul()
    },
    Unit: function Unit(x) {
      return x.pow(3);
    }
  });
});

var name$4f = 'exp';
var dependencies$4e = ['typed'];
var createExp = /* #__PURE__ */factory(name$4f, dependencies$4e, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Calculate the exponential of a value.
   * For matrices, if you want the matrix exponential of square matrix, use
   * the `expm` function; if you want to take the exponential of each element,
   * see the examples.
   *
   * Syntax:
   *
   *    math.exp(x)
   *
   * Examples:
   *
   *    math.exp(2)                  // returns number 7.3890560989306495
   *    math.pow(math.e, 2)          // returns number 7.3890560989306495
   *    math.log(math.exp(2))        // returns number 2
   *
   *    math.map([1, 2, 3], math.exp)
   *    // returns Array [
   *    //   2.718281828459045,
   *    //   7.3890560989306495,
   *    //   20.085536923187668
   *    // ]
   *
   * See also:
   *
   *    expm1, expm, log, pow
   *
   * @param {number | BigNumber | Complex} x  A number to exponentiate
   * @return {number | BigNumber | Complex} Exponential of `x`
   */
  return typed(name$4f, {
    number: expNumber,
    Complex: function Complex(x) {
      return x.exp();
    },
    BigNumber: function BigNumber(x) {
      return x.exp();
    }
  });
});

var name$4e = 'expm1';
var dependencies$4d = ['typed', 'Complex'];
var createExpm1 = /* #__PURE__ */factory(name$4e, dependencies$4d, _ref => {
  var {
    typed,
    Complex: _Complex
  } = _ref;
  /**
   * Calculate the value of subtracting 1 from the exponential value.
   * This function is more accurate than `math.exp(x)-1` when `x` is near 0
   * To avoid ambiguity with the matrix exponential `expm`, this function
   * does not operate on matrices; if you wish to apply it elementwise, see
   * the examples.
   *
   * Syntax:
   *
   *    math.expm1(x)
   *
   * Examples:
   *
   *    math.expm1(2)                      // returns number 6.38905609893065
   *    math.pow(math.e, 2) - 1            // returns number 6.3890560989306495
   *    math.expm1(1e-8)                   // returns number 1.0000000050000001e-8
   *    math.exp(1e-8) - 1                 // returns number 9.9999999392253e-9
   *    math.log(math.expm1(2) + 1)        // returns number 2
   *
   *    math.map([1, 2, 3], math.expm1)
   *    // returns Array [
   *    //   1.718281828459045,
   *    //   6.3890560989306495,
   *    //   19.085536923187668
   *    // ]
   *
   * See also:
   *
   *    exp, expm, log, pow
   *
   * @param {number | BigNumber | Complex} x  The number to exponentiate
   * @return {number | BigNumber | Complex} Exponential of `x`, minus one
   */
  return typed(name$4e, {
    number: expm1Number,
    Complex: function Complex(x) {
      var r = Math.exp(x.re);
      return new _Complex(r * Math.cos(x.im) - 1, r * Math.sin(x.im));
    },
    BigNumber: function BigNumber(x) {
      return x.exp().minus(1);
    }
  });
});

var name$4d = 'fix';
var dependencies$4c = ['typed', 'Complex', 'matrix', 'ceil', 'floor', 'equalScalar', 'zeros', 'DenseMatrix'];
var createFixNumber = /* #__PURE__ */factory(name$4d, ['typed', 'ceil', 'floor'], _ref => {
  var {
    typed,
    ceil,
    floor
  } = _ref;
  return typed(name$4d, {
    number: function number(x) {
      return x > 0 ? floor(x) : ceil(x);
    },
    'number, number': function numberNumber(x, n) {
      return x > 0 ? floor(x, n) : ceil(x, n);
    }
  });
});
var createFix = /* #__PURE__ */factory(name$4d, dependencies$4c, _ref2 => {
  var {
    typed,
    Complex: _Complex,
    matrix,
    ceil,
    floor,
    equalScalar,
    zeros,
    DenseMatrix
  } = _ref2;
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matAlgo14xDs = createMatAlgo14xDs({
    typed
  });
  var fixNumber = createFixNumber({
    typed,
    ceil,
    floor
  });
  /**
   * Round a value towards zero.
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.fix(x)
   *    math.fix(x,n)
   *
   * Examples:
   *
   *    math.fix(3.2)                // returns number 3
   *    math.fix(3.8)                // returns number 3
   *    math.fix(-4.2)               // returns number -4
   *    math.fix(-4.7)               // returns number -4
   *
   *    math.fix(3.12, 1)                // returns number 3.1
   *    math.fix(3.18, 1)                // returns number 3.1
   *    math.fix(-4.12, 1)               // returns number -4.1
   *    math.fix(-4.17, 1)               // returns number -4.1
   *
   *    const c = math.complex(3.22, -2.78)
   *    math.fix(c)                  // returns Complex 3 - 2i
   *    math.fix(c, 1)               // returns Complex 3.2 -2.7i
   *
   *    math.fix([3.2, 3.8, -4.7])      // returns Array [3, 3, -4]
   *    math.fix([3.2, 3.8, -4.7], 1)   // returns Array [3.2, 3.8, -4.7]
   *
   * See also:
   *
   *    ceil, floor, round
   *
   * @param  {number | BigNumber | Fraction | Complex | Array | Matrix} x    Number to be rounded
   * @param  {number | BigNumber | Array} [n=0]                             Number of decimals
   * @return {number | BigNumber | Fraction | Complex | Array | Matrix}     Rounded value
   */
  return typed('fix', {
    number: fixNumber.signatures.number,
    'number, number | BigNumber': fixNumber.signatures['number,number'],
    Complex: function Complex(x) {
      return new _Complex(x.re > 0 ? Math.floor(x.re) : Math.ceil(x.re), x.im > 0 ? Math.floor(x.im) : Math.ceil(x.im));
    },
    'Complex, number': function ComplexNumber(x, n) {
      return new _Complex(x.re > 0 ? floor(x.re, n) : ceil(x.re, n), x.im > 0 ? floor(x.im, n) : ceil(x.im, n));
    },
    'Complex, BigNumber': function ComplexBigNumber(x, bn) {
      var n = bn.toNumber();
      return new _Complex(x.re > 0 ? floor(x.re, n) : ceil(x.re, n), x.im > 0 ? floor(x.im, n) : ceil(x.im, n));
    },
    BigNumber: function BigNumber(x) {
      return x.isNegative() ? ceil(x) : floor(x);
    },
    'BigNumber, number | BigNumber': function BigNumberNumberBigNumber(x, n) {
      return x.isNegative() ? ceil(x, n) : floor(x, n);
    },
    Fraction: function Fraction(x) {
      return x.s < 0 ? x.ceil() : x.floor();
    },
    'Fraction, number | BigNumber': function FractionNumberBigNumber(x, n) {
      return x.s < 0 ? ceil(x, n) : floor(x, n);
    },
    'Array | Matrix': typed.referToSelf(self => x => {
      // deep map collection, skip zeros since fix(0) = 0
      return deepMap(x, self);
    }),
    'Array | Matrix, number | BigNumber': typed.referToSelf(self => (x, n) => {
      // deep map collection, skip zeros since fix(0) = 0
      return deepMap(x, i => self(i, n));
    }),
    'number | Complex | Fraction | BigNumber, Array': typed.referToSelf(self => (x, y) => {
      // use matrix implementation
      return matAlgo14xDs(matrix(y), x, self, true).valueOf();
    }),
    'number | Complex | Fraction | BigNumber, Matrix': typed.referToSelf(self => (x, y) => {
      if (equalScalar(x, 0)) return zeros(y.size(), y.storage());
      if (y.storage() === 'dense') {
        return matAlgo14xDs(y, x, self, true);
      }
      return matAlgo12xSfs(y, x, self, true);
    })
  });
});

var name$4c = 'floor';
var dependencies$4b = ['typed', 'config', 'round', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix'];
var createFloorNumber = /* #__PURE__ */factory(name$4c, ['typed', 'config', 'round'], _ref => {
  var {
    typed,
    config,
    round
  } = _ref;
  return typed(name$4c, {
    number: function number(x) {
      if (nearlyEqual$1(x, round(x), config.relTol, config.absTol)) {
        return round(x);
      } else {
        return Math.floor(x);
      }
    },
    'number, number': function numberNumber(x, n) {
      if (nearlyEqual$1(x, round(x, n), config.relTol, config.absTol)) {
        return round(x, n);
      } else {
        var [number, exponent] = "".concat(x, "e").split('e');
        var result = Math.floor(Number("".concat(number, "e").concat(Number(exponent) + n)));
        [number, exponent] = "".concat(result, "e").split('e');
        return Number("".concat(number, "e").concat(Number(exponent) - n));
      }
    }
  });
});
var createFloor = /* #__PURE__ */factory(name$4c, dependencies$4b, _ref2 => {
  var {
    typed,
    config,
    round,
    matrix,
    equalScalar,
    zeros,
    DenseMatrix
  } = _ref2;
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matAlgo14xDs = createMatAlgo14xDs({
    typed
  });
  var floorNumber = createFloorNumber({
    typed,
    config,
    round
  });
  /**
   * Round a value towards minus infinity.
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.floor(x)
   *    math.floor(x, n)
   *
   * Examples:
   *
   *    math.floor(3.2)              // returns number 3
   *    math.floor(3.8)              // returns number 3
   *    math.floor(-4.2)             // returns number -5
   *    math.floor(-4.7)             // returns number -5
   *
   *    math.floor(3.212, 2)          // returns number 3.21
   *    math.floor(3.288, 2)          // returns number 3.28
   *    math.floor(-4.212, 2)         // returns number -4.22
   *    math.floor(-4.782, 2)         // returns number -4.79
   *
   *    const c = math.complex(3.24, -2.71)
   *    math.floor(c)                 // returns Complex 3 - 3i
   *    math.floor(c, 1)              // returns Complex 3.2 -2.8i
   *
   *    math.floor([3.2, 3.8, -4.7])       // returns Array [3, 3, -5]
   *    math.floor([3.21, 3.82, -4.71], 1)  // returns Array [3.2, 3.8, -4.8]
   *
   *    math.floor(math.tau, [2, 3])  // returns Array [6.28, 6.283]
   *
   *    // Note that floor(array, array) currently not implemented.
   *
   * See also:
   *
   *    ceil, fix, round
   *
   * @param  {number | BigNumber | Fraction | Complex | Array | Matrix} x  Number to be rounded
   * @param  {number | BigNumber | Array} [n=0]                            Number of decimals
   * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
   */
  return typed('floor', {
    number: floorNumber.signatures.number,
    'number,number': floorNumber.signatures['number,number'],
    Complex: function Complex(x) {
      return x.floor();
    },
    'Complex, number': function ComplexNumber(x, n) {
      return x.floor(n);
    },
    'Complex, BigNumber': function ComplexBigNumber(x, n) {
      return x.floor(n.toNumber());
    },
    BigNumber: function BigNumber(x) {
      if (nearlyEqual(x, round(x), config.relTol, config.absTol)) {
        return round(x);
      } else {
        return x.floor();
      }
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(x, n) {
      if (nearlyEqual(x, round(x, n), config.relTol, config.absTol)) {
        return round(x, n);
      } else {
        return x.toDecimalPlaces(n.toNumber(), Decimal.ROUND_FLOOR);
      }
    },
    Fraction: function Fraction(x) {
      return x.floor();
    },
    'Fraction, number': function FractionNumber(x, n) {
      return x.floor(n);
    },
    'Fraction, BigNumber': function FractionBigNumber(x, n) {
      return x.floor(n.toNumber());
    },
    'Array | Matrix': typed.referToSelf(self => x => {
      // deep map collection, skip zeros since floor(0) = 0
      return deepMap(x, self);
    }),
    'Array, number | BigNumber': typed.referToSelf(self => (x, n) => {
      // deep map collection, skip zeros since ceil(0) = 0
      return deepMap(x, i => self(i, n));
    }),
    'SparseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
      return matAlgo11xS0s(x, y, self, false);
    }),
    'DenseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
      return matAlgo14xDs(x, y, self, false);
    }),
    'number | Complex | Fraction | BigNumber, Array': typed.referToSelf(self => (x, y) => {
      // use matrix implementation
      return matAlgo14xDs(matrix(y), x, self, true).valueOf();
    }),
    'number | Complex | Fraction | BigNumber, Matrix': typed.referToSelf(self => (x, y) => {
      if (equalScalar(x, 0)) return zeros(y.size(), y.storage());
      if (y.storage() === 'dense') {
        return matAlgo14xDs(y, x, self, true);
      }
      return matAlgo12xSfs(y, x, self, true);
    })
  });
});

var name$4b = 'matAlgo02xDS0';
var dependencies$4a = ['typed', 'equalScalar'];
var createMatAlgo02xDS0 = /* #__PURE__ */factory(name$4b, dependencies$4a, _ref => {
  var {
    typed,
    equalScalar
  } = _ref;
  /**
   * Iterates over SparseMatrix nonzero items and invokes the callback function f(Dij, Sij).
   * Callback function invoked NNZ times (number of nonzero items in SparseMatrix).
   *
   *
   *          ┌  f(Dij, Sij)  ; S(i,j) !== 0
   * C(i,j) = ┤
   *          └  0            ; otherwise
   *
   *
   * @param {Matrix}   denseMatrix       The DenseMatrix instance (D)
   * @param {Matrix}   sparseMatrix      The SparseMatrix instance (S)
   * @param {Function} callback          The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j)
   * @param {boolean}  inverse           A true value indicates callback should be invoked f(Sij,Dij)
   *
   * @return {Matrix}                    SparseMatrix (C)
   *
   * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571
   */
  return function matAlgo02xDS0(denseMatrix, sparseMatrix, callback, inverse) {
    // dense matrix arrays
    var adata = denseMatrix._data;
    var asize = denseMatrix._size;
    var adt = denseMatrix._datatype || denseMatrix.getDataType();
    // sparse matrix arrays
    var bvalues = sparseMatrix._values;
    var bindex = sparseMatrix._index;
    var bptr = sparseMatrix._ptr;
    var bsize = sparseMatrix._size;
    var bdt = sparseMatrix._datatype || sparseMatrix._data === undefined ? sparseMatrix._datatype : sparseMatrix.getDataType();

    // validate dimensions
    if (asize.length !== bsize.length) {
      throw new DimensionError(asize.length, bsize.length);
    }

    // check rows & columns
    if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
      throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
    }

    // sparse matrix cannot be a Pattern matrix
    if (!bvalues) {
      throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix');
    }

    // rows & columns
    var rows = asize[0];
    var columns = asize[1];

    // datatype
    var dt;
    // equal signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;
    // callback signature to use
    var cf = callback;

    // process data types
    if (typeof adt === 'string' && adt === bdt && adt !== 'mixed') {
      // datatype
      dt = adt;
      // find signature that matches (dt, dt)
      eq = typed.find(equalScalar, [dt, dt]);
      // convert 0 to the same datatype
      zero = typed.convert(0, dt);
      // callback
      cf = typed.find(callback, [dt, dt]);
    }

    // result (SparseMatrix)
    var cvalues = [];
    var cindex = [];
    var cptr = [];

    // loop columns in b
    for (var j = 0; j < columns; j++) {
      // update cptr
      cptr[j] = cindex.length;
      // values in column j
      for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
        // row
        var i = bindex[k];
        // update C(i,j)
        var cij = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]);
        // check for nonzero
        if (!eq(cij, zero)) {
          // push i & v
          cindex.push(i);
          cvalues.push(cij);
        }
      }
    }
    // update cptr
    cptr[columns] = cindex.length;

    // return sparse matrix
    return sparseMatrix.createSparseMatrix({
      values: cvalues,
      index: cindex,
      ptr: cptr,
      size: [rows, columns],
      datatype: adt === denseMatrix._datatype && bdt === sparseMatrix._datatype ? dt : undefined
    });
  };
});

var name$4a = 'matAlgo03xDSf';
var dependencies$49 = ['typed'];
var createMatAlgo03xDSf = /* #__PURE__ */factory(name$4a, dependencies$49, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Iterates over SparseMatrix items and invokes the callback function f(Dij, Sij).
   * Callback function invoked M*N times.
   *
   *
   *          ┌  f(Dij, Sij)  ; S(i,j) !== 0
   * C(i,j) = ┤
   *          └  f(Dij, 0)    ; otherwise
   *
   *
   * @param {Matrix}   denseMatrix       The DenseMatrix instance (D)
   * @param {Matrix}   sparseMatrix      The SparseMatrix instance (C)
   * @param {Function} callback          The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j)
   * @param {boolean}  inverse           A true value indicates callback should be invoked f(Sij,Dij)
   *
   * @return {Matrix}                    DenseMatrix (C)
   *
   * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571
   */
  return function matAlgo03xDSf(denseMatrix, sparseMatrix, callback, inverse) {
    // dense matrix arrays
    var adata = denseMatrix._data;
    var asize = denseMatrix._size;
    var adt = denseMatrix._datatype || denseMatrix.getDataType();
    // sparse matrix arrays
    var bvalues = sparseMatrix._values;
    var bindex = sparseMatrix._index;
    var bptr = sparseMatrix._ptr;
    var bsize = sparseMatrix._size;
    var bdt = sparseMatrix._datatype || sparseMatrix._data === undefined ? sparseMatrix._datatype : sparseMatrix.getDataType();

    // validate dimensions
    if (asize.length !== bsize.length) {
      throw new DimensionError(asize.length, bsize.length);
    }

    // check rows & columns
    if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
      throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
    }

    // sparse matrix cannot be a Pattern matrix
    if (!bvalues) {
      throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix');
    }

    // rows & columns
    var rows = asize[0];
    var columns = asize[1];

    // datatype
    var dt;
    // zero value
    var zero = 0;
    // callback signature to use
    var cf = callback;

    // process data types
    if (typeof adt === 'string' && adt === bdt && adt !== 'mixed') {
      // datatype
      dt = adt;
      // convert 0 to the same datatype
      zero = typed.convert(0, dt);
      // callback
      cf = typed.find(callback, [dt, dt]);
    }

    // result (DenseMatrix)
    var cdata = [];

    // initialize dense matrix
    for (var z = 0; z < rows; z++) {
      // initialize row
      cdata[z] = [];
    }

    // workspace
    var x = [];
    // marks indicating we have a value in x for a given column
    var w = [];

    // loop columns in b
    for (var j = 0; j < columns; j++) {
      // column mark
      var mark = j + 1;
      // values in column j
      for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
        // row
        var i = bindex[k];
        // update workspace
        x[i] = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]);
        w[i] = mark;
      }
      // process workspace
      for (var y = 0; y < rows; y++) {
        // check we have a calculated value for current row
        if (w[y] === mark) {
          // use calculated value
          cdata[y][j] = x[y];
        } else {
          // calculate value
          cdata[y][j] = inverse ? cf(zero, adata[y][j]) : cf(adata[y][j], zero);
        }
      }
    }

    // return dense matrix
    return denseMatrix.createDenseMatrix({
      data: cdata,
      size: [rows, columns],
      datatype: adt === denseMatrix._datatype && bdt === sparseMatrix._datatype ? dt : undefined
    });
  };
});

var name$49 = 'matAlgo05xSfSf';
var dependencies$48 = ['typed', 'equalScalar'];
var createMatAlgo05xSfSf = /* #__PURE__ */factory(name$49, dependencies$48, _ref => {
  var {
    typed,
    equalScalar
  } = _ref;
  /**
   * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij).
   * Callback function invoked MAX(NNZA, NNZB) times
   *
   *
   *          ┌  f(Aij, Bij)  ; A(i,j) !== 0 || B(i,j) !== 0
   * C(i,j) = ┤
   *          └  0            ; otherwise
   *
   *
   * @param {Matrix}   a                 The SparseMatrix instance (A)
   * @param {Matrix}   b                 The SparseMatrix instance (B)
   * @param {Function} callback          The f(Aij,Bij) operation to invoke
   *
   * @return {Matrix}                    SparseMatrix (C)
   *
   * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
   */
  return function matAlgo05xSfSf(a, b, callback) {
    // sparse matrix arrays
    var avalues = a._values;
    var aindex = a._index;
    var aptr = a._ptr;
    var asize = a._size;
    var adt = a._datatype || a._data === undefined ? a._datatype : a.getDataType();
    // sparse matrix arrays
    var bvalues = b._values;
    var bindex = b._index;
    var bptr = b._ptr;
    var bsize = b._size;
    var bdt = b._datatype || b._data === undefined ? b._datatype : b.getDataType();

    // validate dimensions
    if (asize.length !== bsize.length) {
      throw new DimensionError(asize.length, bsize.length);
    }

    // check rows & columns
    if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
      throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
    }

    // rows & columns
    var rows = asize[0];
    var columns = asize[1];

    // datatype
    var dt;
    // equal signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;
    // callback signature to use
    var cf = callback;

    // process data types
    if (typeof adt === 'string' && adt === bdt && adt !== 'mixed') {
      // datatype
      dt = adt;
      // find signature that matches (dt, dt)
      eq = typed.find(equalScalar, [dt, dt]);
      // convert 0 to the same datatype
      zero = typed.convert(0, dt);
      // callback
      cf = typed.find(callback, [dt, dt]);
    }

    // result arrays
    var cvalues = avalues && bvalues ? [] : undefined;
    var cindex = [];
    var cptr = [];

    // workspaces
    var xa = cvalues ? [] : undefined;
    var xb = cvalues ? [] : undefined;
    // marks indicating we have a value in x for a given column
    var wa = [];
    var wb = [];

    // vars
    var i, j, k, k1;

    // loop columns
    for (j = 0; j < columns; j++) {
      // update cptr
      cptr[j] = cindex.length;
      // columns mark
      var mark = j + 1;
      // loop values A(:,j)
      for (k = aptr[j], k1 = aptr[j + 1]; k < k1; k++) {
        // row
        i = aindex[k];
        // push index
        cindex.push(i);
        // update workspace
        wa[i] = mark;
        // check we need to process values
        if (xa) {
          xa[i] = avalues[k];
        }
      }
      // loop values B(:,j)
      for (k = bptr[j], k1 = bptr[j + 1]; k < k1; k++) {
        // row
        i = bindex[k];
        // check row existed in A
        if (wa[i] !== mark) {
          // push index
          cindex.push(i);
        }
        // update workspace
        wb[i] = mark;
        // check we need to process values
        if (xb) {
          xb[i] = bvalues[k];
        }
      }
      // check we need to process values (non pattern matrix)
      if (cvalues) {
        // initialize first index in j
        k = cptr[j];
        // loop index in j
        while (k < cindex.length) {
          // row
          i = cindex[k];
          // marks
          var wai = wa[i];
          var wbi = wb[i];
          // check Aij or Bij are nonzero
          if (wai === mark || wbi === mark) {
            // matrix values @ i,j
            var va = wai === mark ? xa[i] : zero;
            var vb = wbi === mark ? xb[i] : zero;
            // Cij
            var vc = cf(va, vb);
            // check for zero
            if (!eq(vc, zero)) {
              // push value
              cvalues.push(vc);
              // increment pointer
              k++;
            } else {
              // remove value @ i, do not increment pointer
              cindex.splice(k, 1);
            }
          }
        }
      }
    }
    // update cptr
    cptr[columns] = cindex.length;

    // return sparse matrix
    return a.createSparseMatrix({
      values: cvalues,
      index: cindex,
      ptr: cptr,
      size: [rows, columns],
      datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
    });
  };
});

var name$48 = 'matAlgo13xDD';
var dependencies$47 = ['typed'];
var createMatAlgo13xDD = /* #__PURE__ */factory(name$48, dependencies$47, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, Bij..z).
   * Callback function invoked MxN times.
   *
   * C(i,j,...z) = f(Aij..z, Bij..z)
   *
   * @param {Matrix}   a                 The DenseMatrix instance (A)
   * @param {Matrix}   b                 The DenseMatrix instance (B)
   * @param {Function} callback          The f(Aij..z,Bij..z) operation to invoke
   *
   * @return {Matrix}                    DenseMatrix (C)
   *
   * https://github.com/josdejong/mathjs/pull/346#issuecomment-97658658
   */
  return function matAlgo13xDD(a, b, callback) {
    // a arrays
    var adata = a._data;
    var asize = a._size;
    var adt = a._datatype;
    // b arrays
    var bdata = b._data;
    var bsize = b._size;
    var bdt = b._datatype;
    // c arrays
    var csize = [];

    // validate dimensions
    if (asize.length !== bsize.length) {
      throw new DimensionError(asize.length, bsize.length);
    }

    // validate each one of the dimension sizes
    for (var s = 0; s < asize.length; s++) {
      // must match
      if (asize[s] !== bsize[s]) {
        throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
      }
      // update dimension in c
      csize[s] = asize[s];
    }

    // datatype
    var dt;
    // callback signature to use
    var cf = callback;

    // process data types
    if (typeof adt === 'string' && adt === bdt) {
      // datatype
      dt = adt;
      // callback
      cf = typed.find(callback, [dt, dt]);
    }

    // populate cdata, iterate through dimensions
    var cdata = csize.length > 0 ? _iterate(cf, 0, csize, csize[0], adata, bdata) : [];

    // c matrix
    return a.createDenseMatrix({
      data: cdata,
      size: csize,
      datatype: dt
    });
  };

  // recursive function
  function _iterate(f, level, s, n, av, bv) {
    // initialize array for this level
    var cv = [];
    // check we reach the last level
    if (level === s.length - 1) {
      // loop arrays in last level
      for (var i = 0; i < n; i++) {
        // invoke callback and store value
        cv[i] = f(av[i], bv[i]);
      }
    } else {
      // iterate current level
      for (var j = 0; j < n; j++) {
        // iterate next level
        cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv[j]);
      }
    }
    return cv;
  }
});

var name$47 = 'broadcast';
var dependancies = ['concat'];
var createBroadcast = /* #__PURE__ */factory(name$47, dependancies, _ref => {
  var {
    concat
  } = _ref;
  /**
  * Broadcasts two matrices, and return both in an array
  * It checks if it's possible with broadcasting rules
  *
  * @param {Matrix}   A      First Matrix
  * @param {Matrix}   B      Second Matrix
  *
  * @return {Matrix[]}      [ broadcastedA, broadcastedB ]
  */
  return function (A, B) {
    var N = Math.max(A._size.length, B._size.length); // max number of dims
    if (A._size.length === B._size.length) {
      if (A._size.every((dim, i) => dim === B._size[i])) {
        // If matrices have the same size return them
        return [A, B];
      }
    }
    var sizeA = _padLeft(A._size, N, 0); // pad to the left to align dimensions to the right
    var sizeB = _padLeft(B._size, N, 0); // pad to the left to align dimensions to the right

    // calculate the max dimensions
    var sizeMax = [];
    for (var dim = 0; dim < N; dim++) {
      sizeMax[dim] = Math.max(sizeA[dim], sizeB[dim]);
    }

    // check if the broadcasting rules applyes for both matrices
    checkBroadcastingRules(sizeA, sizeMax);
    checkBroadcastingRules(sizeB, sizeMax);

    // reshape A or B if needed to make them ready for concat
    var AA = A.clone();
    var BB = B.clone();
    if (AA._size.length < N) {
      AA.reshape(_padLeft(AA._size, N, 1));
    } else if (BB._size.length < N) {
      BB.reshape(_padLeft(BB._size, N, 1));
    }

    // stretches the matrices on each dimension to make them the same size
    for (var _dim = 0; _dim < N; _dim++) {
      if (AA._size[_dim] < sizeMax[_dim]) {
        AA = _stretch(AA, sizeMax[_dim], _dim);
      }
      if (BB._size[_dim] < sizeMax[_dim]) {
        BB = _stretch(BB, sizeMax[_dim], _dim);
      }
    }

    // return the array with the two broadcasted matrices
    return [AA, BB];
  };
  function _padLeft(shape, N, filler) {
    // pads an array of dimensions with numbers to the left, unitl the number of dimensions is N
    return [...Array(N - shape.length).fill(filler), ...shape];
  }
  function _stretch(arrayToStretch, sizeToStretch, dimToStretch) {
    // stretches a matrix up to a certain size in a certain dimension
    return concat(...Array(sizeToStretch).fill(arrayToStretch), dimToStretch);
  }
});

var name$46 = 'matrixAlgorithmSuite';
var dependencies$46 = ['typed', 'matrix', 'concat'];
var createMatrixAlgorithmSuite = /* #__PURE__ */factory(name$46, dependencies$46, _ref => {
  var {
    typed,
    matrix,
    concat
  } = _ref;
  var matAlgo13xDD = createMatAlgo13xDD({
    typed
  });
  var matAlgo14xDs = createMatAlgo14xDs({
    typed
  });
  var broadcast = createBroadcast({
    concat
  });

  /**
   * Return a signatures object with the usual boilerplate of
   * matrix algorithms, based on a plain options object with the
   * following properties:
   *   elop: function -- the elementwise operation to use, defaults to self
   *   SS: function -- the algorithm to apply for two sparse matrices
   *   DS: function -- the algorithm to apply for a dense and a sparse matrix
   *   SD: function -- algo for a sparse and a dense; defaults to SD flipped
   *   Ss: function -- the algorithm to apply for a sparse matrix and scalar
   *   sS: function -- algo for scalar and sparse; defaults to Ss flipped
   *   scalar: string -- typed-function type for scalars, defaults to 'any'
   *
   * If Ss is not specified, no matrix-scalar signatures are generated.
   *
   * @param {object} options
   * @return {Object<string, function>} signatures
   */
  return function matrixAlgorithmSuite(options) {
    var elop = options.elop;
    var SD = options.SD || options.DS;
    var matrixSignatures;
    if (elop) {
      // First the dense ones
      matrixSignatures = {
        'DenseMatrix, DenseMatrix': (x, y) => matAlgo13xDD(...broadcast(x, y), elop),
        'Array, Array': (x, y) => matAlgo13xDD(...broadcast(matrix(x), matrix(y)), elop).valueOf(),
        'Array, DenseMatrix': (x, y) => matAlgo13xDD(...broadcast(matrix(x), y), elop),
        'DenseMatrix, Array': (x, y) => matAlgo13xDD(...broadcast(x, matrix(y)), elop)
      };
      // Now incorporate sparse matrices
      if (options.SS) {
        matrixSignatures['SparseMatrix, SparseMatrix'] = (x, y) => options.SS(...broadcast(x, y), elop, false);
      }
      if (options.DS) {
        matrixSignatures['DenseMatrix, SparseMatrix'] = (x, y) => options.DS(...broadcast(x, y), elop, false);
        matrixSignatures['Array, SparseMatrix'] = (x, y) => options.DS(...broadcast(matrix(x), y), elop, false);
      }
      if (SD) {
        matrixSignatures['SparseMatrix, DenseMatrix'] = (x, y) => SD(...broadcast(y, x), elop, true);
        matrixSignatures['SparseMatrix, Array'] = (x, y) => SD(...broadcast(matrix(y), x), elop, true);
      }
    } else {
      // No elop, use this
      // First the dense ones
      matrixSignatures = {
        'DenseMatrix, DenseMatrix': typed.referToSelf(self => (x, y) => {
          return matAlgo13xDD(...broadcast(x, y), self);
        }),
        'Array, Array': typed.referToSelf(self => (x, y) => {
          return matAlgo13xDD(...broadcast(matrix(x), matrix(y)), self).valueOf();
        }),
        'Array, DenseMatrix': typed.referToSelf(self => (x, y) => {
          return matAlgo13xDD(...broadcast(matrix(x), y), self);
        }),
        'DenseMatrix, Array': typed.referToSelf(self => (x, y) => {
          return matAlgo13xDD(...broadcast(x, matrix(y)), self);
        })
      };
      // Now incorporate sparse matrices
      if (options.SS) {
        matrixSignatures['SparseMatrix, SparseMatrix'] = typed.referToSelf(self => (x, y) => {
          return options.SS(...broadcast(x, y), self, false);
        });
      }
      if (options.DS) {
        matrixSignatures['DenseMatrix, SparseMatrix'] = typed.referToSelf(self => (x, y) => {
          return options.DS(...broadcast(x, y), self, false);
        });
        matrixSignatures['Array, SparseMatrix'] = typed.referToSelf(self => (x, y) => {
          return options.DS(...broadcast(matrix(x), y), self, false);
        });
      }
      if (SD) {
        matrixSignatures['SparseMatrix, DenseMatrix'] = typed.referToSelf(self => (x, y) => {
          return SD(...broadcast(y, x), self, true);
        });
        matrixSignatures['SparseMatrix, Array'] = typed.referToSelf(self => (x, y) => {
          return SD(...broadcast(matrix(y), x), self, true);
        });
      }
    }

    // Now add the scalars
    var scalar = options.scalar || 'any';
    var Ds = options.Ds || options.Ss;
    if (Ds) {
      if (elop) {
        matrixSignatures['DenseMatrix,' + scalar] = (x, y) => matAlgo14xDs(x, y, elop, false);
        matrixSignatures[scalar + ', DenseMatrix'] = (x, y) => matAlgo14xDs(y, x, elop, true);
        matrixSignatures['Array,' + scalar] = (x, y) => matAlgo14xDs(matrix(x), y, elop, false).valueOf();
        matrixSignatures[scalar + ', Array'] = (x, y) => matAlgo14xDs(matrix(y), x, elop, true).valueOf();
      } else {
        matrixSignatures['DenseMatrix,' + scalar] = typed.referToSelf(self => (x, y) => {
          return matAlgo14xDs(x, y, self, false);
        });
        matrixSignatures[scalar + ', DenseMatrix'] = typed.referToSelf(self => (x, y) => {
          return matAlgo14xDs(y, x, self, true);
        });
        matrixSignatures['Array,' + scalar] = typed.referToSelf(self => (x, y) => {
          return matAlgo14xDs(matrix(x), y, self, false).valueOf();
        });
        matrixSignatures[scalar + ', Array'] = typed.referToSelf(self => (x, y) => {
          return matAlgo14xDs(matrix(y), x, self, true).valueOf();
        });
      }
    }
    var sS = options.sS !== undefined ? options.sS : options.Ss;
    if (elop) {
      if (options.Ss) {
        matrixSignatures['SparseMatrix,' + scalar] = (x, y) => options.Ss(x, y, elop, false);
      }
      if (sS) {
        matrixSignatures[scalar + ', SparseMatrix'] = (x, y) => sS(y, x, elop, true);
      }
    } else {
      if (options.Ss) {
        matrixSignatures['SparseMatrix,' + scalar] = typed.referToSelf(self => (x, y) => {
          return options.Ss(x, y, self, false);
        });
      }
      if (sS) {
        matrixSignatures[scalar + ', SparseMatrix'] = typed.referToSelf(self => (x, y) => {
          return sS(y, x, self, true);
        });
      }
    }
    // Also pull in the scalar signatures if the operator is a typed function
    if (elop && elop.signatures) {
      extend(matrixSignatures, elop.signatures);
    }
    return matrixSignatures;
  };
});

var name$45 = 'mod';
var dependencies$45 = ['typed', 'config', 'round', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix', 'concat'];
var createMod = /* #__PURE__ */factory(name$45, dependencies$45, _ref => {
  var {
    typed,
    config,
    round,
    matrix,
    equalScalar,
    zeros,
    DenseMatrix,
    concat
  } = _ref;
  var floor = createFloor({
    typed,
    config,
    round,
    matrix,
    equalScalar,
    zeros,
    DenseMatrix
  });
  var matAlgo02xDS0 = createMatAlgo02xDS0({
    typed,
    equalScalar
  });
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo05xSfSf = createMatAlgo05xSfSf({
    typed,
    equalScalar
  });
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Calculates the modulus, the remainder of an integer division.
   *
   * For matrices, the function is evaluated element wise.
   *
   * The modulus is defined as:
   *
   *     x - y * floor(x / y)
   *
   * See https://en.wikipedia.org/wiki/Modulo_operation.
   *
   * Syntax:
   *
   *    math.mod(x, y)
   *
   * Examples:
   *
   *    math.mod(8, 3)                // returns 2
   *    math.mod(11, 2)               // returns 1
   *
   *    function isOdd(x) {
   *      return math.mod(x, 2) != 0
   *    }
   *
   *    isOdd(2)                      // returns false
   *    isOdd(3)                      // returns true
   *
   * See also:
   *
   *    divide
   *
   * @param  {number | BigNumber | bigint | Fraction | Array | Matrix} x Dividend
   * @param  {number | BigNumber | bigint | Fraction | Array | Matrix} y Divisor
   * @return {number | BigNumber | bigint | Fraction | Array | Matrix} Returns the remainder of `x` divided by `y`.
   */
  return typed(name$45, {
    'number, number': _modNumber,
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      return y.isZero() ? x : x.sub(y.mul(floor(x.div(y))));
    },
    'bigint, bigint': function bigintBigint(x, y) {
      if (y === 0n) {
        return x;
      }
      if (x < 0) {
        var m = x % y;
        return m === 0n ? m : m + y;
      }
      return x % y;
    },
    'Fraction, Fraction': function FractionFraction(x, y) {
      return y.equals(0) ? x : x.sub(y.mul(floor(x.div(y))));
    }
  }, matrixAlgorithmSuite({
    SS: matAlgo05xSfSf,
    DS: matAlgo03xDSf,
    SD: matAlgo02xDS0,
    Ss: matAlgo11xS0s,
    sS: matAlgo12xSfs
  }));

  /**
  * Calculate the modulus of two numbers
  * @param {number} x
  * @param {number} y
  * @returns {number} res
  * @private
  */
  function _modNumber(x, y) {
    // We don't use JavaScript's % operator here as this doesn't work
    // correctly for x < 0 and x === 0
    // see https://en.wikipedia.org/wiki/Modulo_operation

    // We use mathjs floor to handle errors associated with
    // precision float approximation
    return y === 0 ? x : x - y * floor(x / y);
  }
});

var name$44 = 'matAlgo01xDSid';
var dependencies$44 = ['typed'];
var createMatAlgo01xDSid = /* #__PURE__ */factory(name$44, dependencies$44, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Iterates over SparseMatrix nonzero items and invokes the callback function f(Dij, Sij).
   * Callback function invoked NNZ times (number of nonzero items in SparseMatrix).
   *
   *
   *          ┌  f(Dij, Sij)  ; S(i,j) !== 0
   * C(i,j) = ┤
   *          └  Dij          ; otherwise
   *
   *
   * @param {Matrix}   denseMatrix       The DenseMatrix instance (D)
   * @param {Matrix}   sparseMatrix      The SparseMatrix instance (S)
   * @param {Function} callback          The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j)
   * @param {boolean}  inverse           A true value indicates callback should be invoked f(Sij,Dij)
   *
   * @return {Matrix}                    DenseMatrix (C)
   *
   * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571
   */
  return function algorithm1(denseMatrix, sparseMatrix, callback, inverse) {
    // dense matrix arrays
    var adata = denseMatrix._data;
    var asize = denseMatrix._size;
    var adt = denseMatrix._datatype || denseMatrix.getDataType();
    // sparse matrix arrays
    var bvalues = sparseMatrix._values;
    var bindex = sparseMatrix._index;
    var bptr = sparseMatrix._ptr;
    var bsize = sparseMatrix._size;
    var bdt = sparseMatrix._datatype || sparseMatrix._data === undefined ? sparseMatrix._datatype : sparseMatrix.getDataType();

    // validate dimensions
    if (asize.length !== bsize.length) {
      throw new DimensionError(asize.length, bsize.length);
    }

    // check rows & columns
    if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
      throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
    }

    // sparse matrix cannot be a Pattern matrix
    if (!bvalues) {
      throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix');
    }

    // rows & columns
    var rows = asize[0];
    var columns = asize[1];

    // process data types
    var dt = typeof adt === 'string' && adt !== 'mixed' && adt === bdt ? adt : undefined;
    // callback function
    var cf = dt ? typed.find(callback, [dt, dt]) : callback;

    // vars
    var i, j;

    // result (DenseMatrix)
    var cdata = [];
    // initialize c
    for (i = 0; i < rows; i++) {
      cdata[i] = [];
    }

    // workspace
    var x = [];
    // marks indicating we have a value in x for a given column
    var w = [];

    // loop columns in b
    for (j = 0; j < columns; j++) {
      // column mark
      var mark = j + 1;
      // values in column j
      for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
        // row
        i = bindex[k];
        // update workspace
        x[i] = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]);
        // mark i as updated
        w[i] = mark;
      }
      // loop rows
      for (i = 0; i < rows; i++) {
        // check row is in workspace
        if (w[i] === mark) {
          // c[i][j] was already calculated
          cdata[i][j] = x[i];
        } else {
          // item does not exist in S
          cdata[i][j] = adata[i][j];
        }
      }
    }

    // return dense matrix
    return denseMatrix.createDenseMatrix({
      data: cdata,
      size: [rows, columns],
      datatype: adt === denseMatrix._datatype && bdt === sparseMatrix._datatype ? dt : undefined
    });
  };
});

var name$43 = 'matAlgo04xSidSid';
var dependencies$43 = ['typed', 'equalScalar'];
var createMatAlgo04xSidSid = /* #__PURE__ */factory(name$43, dependencies$43, _ref => {
  var {
    typed,
    equalScalar
  } = _ref;
  /**
   * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij).
   * Callback function invoked MAX(NNZA, NNZB) times
   *
   *
   *          ┌  f(Aij, Bij)  ; A(i,j) !== 0 && B(i,j) !== 0
   * C(i,j) = ┤  A(i,j)       ; A(i,j) !== 0 && B(i,j) === 0
   *          └  B(i,j)       ; A(i,j) === 0
   *
   *
   * @param {Matrix}   a                 The SparseMatrix instance (A)
   * @param {Matrix}   b                 The SparseMatrix instance (B)
   * @param {Function} callback          The f(Aij,Bij) operation to invoke
   *
   * @return {Matrix}                    SparseMatrix (C)
   *
   * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
   */
  return function matAlgo04xSidSid(a, b, callback) {
    // sparse matrix arrays
    var avalues = a._values;
    var aindex = a._index;
    var aptr = a._ptr;
    var asize = a._size;
    var adt = a._datatype || a._data === undefined ? a._datatype : a.getDataType();
    // sparse matrix arrays
    var bvalues = b._values;
    var bindex = b._index;
    var bptr = b._ptr;
    var bsize = b._size;
    var bdt = b._datatype || b._data === undefined ? b._datatype : b.getDataType();

    // validate dimensions
    if (asize.length !== bsize.length) {
      throw new DimensionError(asize.length, bsize.length);
    }

    // check rows & columns
    if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
      throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
    }

    // rows & columns
    var rows = asize[0];
    var columns = asize[1];

    // datatype
    var dt;
    // equal signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;
    // callback signature to use
    var cf = callback;

    // process data types
    if (typeof adt === 'string' && adt === bdt && adt !== 'mixed') {
      // datatype
      dt = adt;
      // find signature that matches (dt, dt)
      eq = typed.find(equalScalar, [dt, dt]);
      // convert 0 to the same datatype
      zero = typed.convert(0, dt);
      // callback
      cf = typed.find(callback, [dt, dt]);
    }

    // result arrays
    var cvalues = avalues && bvalues ? [] : undefined;
    var cindex = [];
    var cptr = [];

    // workspace
    var xa = avalues && bvalues ? [] : undefined;
    var xb = avalues && bvalues ? [] : undefined;
    // marks indicating we have a value in x for a given column
    var wa = [];
    var wb = [];

    // vars
    var i, j, k, k0, k1;

    // loop columns
    for (j = 0; j < columns; j++) {
      // update cptr
      cptr[j] = cindex.length;
      // columns mark
      var mark = j + 1;
      // loop A(:,j)
      for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
        // row
        i = aindex[k];
        // update c
        cindex.push(i);
        // update workspace
        wa[i] = mark;
        // check we need to process values
        if (xa) {
          xa[i] = avalues[k];
        }
      }
      // loop B(:,j)
      for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
        // row
        i = bindex[k];
        // check row exists in A
        if (wa[i] === mark) {
          // update record in xa @ i
          if (xa) {
            // invoke callback
            var v = cf(xa[i], bvalues[k]);
            // check for zero
            if (!eq(v, zero)) {
              // update workspace
              xa[i] = v;
            } else {
              // remove mark (index will be removed later)
              wa[i] = null;
            }
          }
        } else {
          // update c
          cindex.push(i);
          // update workspace
          wb[i] = mark;
          // check we need to process values
          if (xb) {
            xb[i] = bvalues[k];
          }
        }
      }
      // check we need to process values (non pattern matrix)
      if (xa && xb) {
        // initialize first index in j
        k = cptr[j];
        // loop index in j
        while (k < cindex.length) {
          // row
          i = cindex[k];
          // check workspace has value @ i
          if (wa[i] === mark) {
            // push value (Aij != 0 || (Aij != 0 && Bij != 0))
            cvalues[k] = xa[i];
            // increment pointer
            k++;
          } else if (wb[i] === mark) {
            // push value (bij != 0)
            cvalues[k] = xb[i];
            // increment pointer
            k++;
          } else {
            // remove index @ k
            cindex.splice(k, 1);
          }
        }
      }
    }
    // update cptr
    cptr[columns] = cindex.length;

    // return sparse matrix
    return a.createSparseMatrix({
      values: cvalues,
      index: cindex,
      ptr: cptr,
      size: [rows, columns],
      datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
    });
  };
});

var name$42 = 'matAlgo10xSids';
var dependencies$42 = ['typed', 'DenseMatrix'];
var createMatAlgo10xSids = /* #__PURE__ */factory(name$42, dependencies$42, _ref => {
  var {
    typed,
    DenseMatrix
  } = _ref;
  /**
   * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b).
   * Callback function invoked NZ times (number of nonzero items in S).
   *
   *
   *          ┌  f(Sij, b)  ; S(i,j) !== 0
   * C(i,j) = ┤
   *          └  b          ; otherwise
   *
   *
   * @param {Matrix}   s                 The SparseMatrix instance (S)
   * @param {Scalar}   b                 The Scalar value
   * @param {Function} callback          The f(Aij,b) operation to invoke
   * @param {boolean}  inverse           A true value indicates callback should be invoked f(b,Sij)
   *
   * @return {Matrix}                    DenseMatrix (C)
   *
   * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813
   */
  return function matAlgo10xSids(s, b, callback, inverse) {
    // sparse matrix arrays
    var avalues = s._values;
    var aindex = s._index;
    var aptr = s._ptr;
    var asize = s._size;
    var adt = s._datatype;

    // sparse matrix cannot be a Pattern matrix
    if (!avalues) {
      throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value');
    }

    // rows & columns
    var rows = asize[0];
    var columns = asize[1];

    // datatype
    var dt;
    // callback signature to use
    var cf = callback;

    // process data types
    if (typeof adt === 'string') {
      // datatype
      dt = adt;
      // convert b to the same datatype
      b = typed.convert(b, dt);
      // callback
      cf = typed.find(callback, [dt, dt]);
    }

    // result arrays
    var cdata = [];

    // workspaces
    var x = [];
    // marks indicating we have a value in x for a given column
    var w = [];

    // loop columns
    for (var j = 0; j < columns; j++) {
      // columns mark
      var mark = j + 1;
      // values in j
      for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
        // row
        var r = aindex[k];
        // update workspace
        x[r] = avalues[k];
        w[r] = mark;
      }
      // loop rows
      for (var i = 0; i < rows; i++) {
        // initialize C on first column
        if (j === 0) {
          // create row array
          cdata[i] = [];
        }
        // check sparse matrix has a value @ i,j
        if (w[i] === mark) {
          // invoke callback, update C
          cdata[i][j] = inverse ? cf(b, x[i]) : cf(x[i], b);
        } else {
          // dense matrix value @ i, j
          cdata[i][j] = b;
        }
      }
    }

    // return dense matrix
    return new DenseMatrix({
      data: cdata,
      size: [rows, columns],
      datatype: dt
    });
  };
});

/**
 * Create a syntax error with the message:
 *     'Wrong number of arguments in function <fn> (<count> provided, <min>-<max> expected)'
 * @param {string} fn     Function name
 * @param {number} count  Actual argument count
 * @param {number} min    Minimum required argument count
 * @param {number} [max]  Maximum required argument count
 * @extends Error
 */
function ArgumentsError(fn, count, min, max) {
  if (!(this instanceof ArgumentsError)) {
    throw new SyntaxError('Constructor must be called with the new operator');
  }
  this.fn = fn;
  this.count = count;
  this.min = min;
  this.max = max;
  this.message = 'Wrong number of arguments in function ' + fn + ' (' + count + ' provided, ' + min + (max !== undefined && max !== null ? '-' + max : '') + ' expected)';
  this.stack = new Error().stack;
}
ArgumentsError.prototype = new Error();
ArgumentsError.prototype.constructor = Error;
ArgumentsError.prototype.name = 'ArgumentsError';
ArgumentsError.prototype.isArgumentsError = true;

var name$41 = 'gcd';
var dependencies$41 = ['typed', 'config', 'round', 'matrix', 'equalScalar', 'zeros', 'BigNumber', 'DenseMatrix', 'concat'];
var gcdTypes = 'number | BigNumber | Fraction | Matrix | Array';
var gcdManyTypesSignature = "".concat(gcdTypes, ", ").concat(gcdTypes, ", ...").concat(gcdTypes);
function is1d(array) {
  return !array.some(element => Array.isArray(element));
}
var createGcd = /* #__PURE__ */factory(name$41, dependencies$41, _ref => {
  var {
    typed,
    matrix,
    config,
    round,
    equalScalar,
    zeros,
    BigNumber,
    DenseMatrix,
    concat
  } = _ref;
  var mod = createMod({
    typed,
    config,
    round,
    matrix,
    equalScalar,
    zeros,
    DenseMatrix,
    concat
  });
  var matAlgo01xDSid = createMatAlgo01xDSid({
    typed
  });
  var matAlgo04xSidSid = createMatAlgo04xSidSid({
    typed,
    equalScalar
  });
  var matAlgo10xSids = createMatAlgo10xSids({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Calculate the greatest common divisor for two or more values or arrays.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.gcd(a, b)
   *    math.gcd(a, b, c, ...)
   *
   * Examples:
   *
   *    math.gcd(8, 12)              // returns 4
   *    math.gcd(-4, 6)              // returns 2
   *    math.gcd(25, 15, -10)        // returns 5
   *
   *    math.gcd([8, -4], [12, 6])   // returns [4, 2]
   *
   * See also:
   *
   *    lcm, xgcd
   *
   * @param {... number | BigNumber | Fraction | Array | Matrix} args  Two or more integer numbers
   * @return {number | BigNumber | Fraction | Array | Matrix}                           The greatest common divisor
   */
  return typed(name$41, {
    'number, number': _gcdNumber,
    'BigNumber, BigNumber': _gcdBigNumber,
    'Fraction, Fraction': (x, y) => x.gcd(y)
  }, matrixAlgorithmSuite({
    SS: matAlgo04xSidSid,
    DS: matAlgo01xDSid,
    Ss: matAlgo10xSids
  }), {
    [gcdManyTypesSignature]: typed.referToSelf(self => (a, b, args) => {
      var res = self(a, b);
      for (var i = 0; i < args.length; i++) {
        res = self(res, args[i]);
      }
      return res;
    }),
    Array: typed.referToSelf(self => array => {
      if (array.length === 1 && Array.isArray(array[0]) && is1d(array[0])) {
        return self(...array[0]);
      }
      if (is1d(array)) {
        return self(...array);
      }
      throw new ArgumentsError('gcd() supports only 1d matrices!');
    }),
    Matrix: typed.referToSelf(self => matrix => {
      return self(matrix.toArray());
    })
  });

  /**
  * Calculate gcd for numbers
  * @param {number} a
  * @param {number} b
  * @returns {number} Returns the greatest common denominator of a and b
  * @private
  */
  function _gcdNumber(a, b) {
    if (!isInteger(a) || !isInteger(b)) {
      throw new Error('Parameters in function gcd must be integer numbers');
    }

    // https://en.wikipedia.org/wiki/Euclidean_algorithm
    var r;
    while (b !== 0) {
      r = mod(a, b);
      a = b;
      b = r;
    }
    return a < 0 ? -a : a;
  }

  /**
   * Calculate gcd for BigNumbers
   * @param {BigNumber} a
   * @param {BigNumber} b
   * @returns {BigNumber} Returns greatest common denominator of a and b
   * @private
   */
  function _gcdBigNumber(a, b) {
    if (!a.isInt() || !b.isInt()) {
      throw new Error('Parameters in function gcd must be integer numbers');
    }

    // https://en.wikipedia.org/wiki/Euclidean_algorithm
    var zero = new BigNumber(0);
    while (!b.isZero()) {
      var r = mod(a, b);
      a = b;
      b = r;
    }
    return a.lt(zero) ? a.neg() : a;
  }
});

var name$40 = 'matAlgo06xS0S0';
var dependencies$40 = ['typed', 'equalScalar'];
var createMatAlgo06xS0S0 = /* #__PURE__ */factory(name$40, dependencies$40, _ref => {
  var {
    typed,
    equalScalar
  } = _ref;
  /**
   * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij).
   * Callback function invoked (Anz U Bnz) times, where Anz and Bnz are the nonzero elements in both matrices.
   *
   *
   *          ┌  f(Aij, Bij)  ; A(i,j) !== 0 && B(i,j) !== 0
   * C(i,j) = ┤
   *          └  0            ; otherwise
   *
   *
   * @param {Matrix}   a                 The SparseMatrix instance (A)
   * @param {Matrix}   b                 The SparseMatrix instance (B)
   * @param {Function} callback          The f(Aij,Bij) operation to invoke
   *
   * @return {Matrix}                    SparseMatrix (C)
   *
   * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
   */
  return function matAlgo06xS0S0(a, b, callback) {
    // sparse matrix arrays
    var avalues = a._values;
    var asize = a._size;
    var adt = a._datatype || a._data === undefined ? a._datatype : a.getDataType();
    // sparse matrix arrays
    var bvalues = b._values;
    var bsize = b._size;
    var bdt = b._datatype || b._data === undefined ? b._datatype : b.getDataType();

    // validate dimensions
    if (asize.length !== bsize.length) {
      throw new DimensionError(asize.length, bsize.length);
    }

    // check rows & columns
    if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
      throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
    }

    // rows & columns
    var rows = asize[0];
    var columns = asize[1];

    // datatype
    var dt;
    // equal signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;
    // callback signature to use
    var cf = callback;

    // process data types
    if (typeof adt === 'string' && adt === bdt && adt !== 'mixed') {
      // datatype
      dt = adt;
      // find signature that matches (dt, dt)
      eq = typed.find(equalScalar, [dt, dt]);
      // convert 0 to the same datatype
      zero = typed.convert(0, dt);
      // callback
      cf = typed.find(callback, [dt, dt]);
    }

    // result arrays
    var cvalues = avalues && bvalues ? [] : undefined;
    var cindex = [];
    var cptr = [];

    // workspaces
    var x = cvalues ? [] : undefined;
    // marks indicating we have a value in x for a given column
    var w = [];
    // marks indicating value in a given row has been updated
    var u = [];

    // loop columns
    for (var j = 0; j < columns; j++) {
      // update cptr
      cptr[j] = cindex.length;
      // columns mark
      var mark = j + 1;
      // scatter the values of A(:,j) into workspace
      scatter(a, j, w, x, u, mark, cindex, cf);
      // scatter the values of B(:,j) into workspace
      scatter(b, j, w, x, u, mark, cindex, cf);
      // check we need to process values (non pattern matrix)
      if (x) {
        // initialize first index in j
        var k = cptr[j];
        // loop index in j
        while (k < cindex.length) {
          // row
          var i = cindex[k];
          // check function was invoked on current row (Aij !=0 && Bij != 0)
          if (u[i] === mark) {
            // value @ i
            var v = x[i];
            // check for zero value
            if (!eq(v, zero)) {
              // push value
              cvalues.push(v);
              // increment pointer
              k++;
            } else {
              // remove value @ i, do not increment pointer
              cindex.splice(k, 1);
            }
          } else {
            // remove value @ i, do not increment pointer
            cindex.splice(k, 1);
          }
        }
      } else {
        // initialize first index in j
        var p = cptr[j];
        // loop index in j
        while (p < cindex.length) {
          // row
          var r = cindex[p];
          // check function was invoked on current row (Aij !=0 && Bij != 0)
          if (u[r] !== mark) {
            // remove value @ i, do not increment pointer
            cindex.splice(p, 1);
          } else {
            // increment pointer
            p++;
          }
        }
      }
    }
    // update cptr
    cptr[columns] = cindex.length;

    // return sparse matrix
    return a.createSparseMatrix({
      values: cvalues,
      index: cindex,
      ptr: cptr,
      size: [rows, columns],
      datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
    });
  };
});

var name$3$ = 'lcm';
var dependencies$3$ = ['typed', 'matrix', 'equalScalar', 'concat'];
var createLcm = /* #__PURE__ */factory(name$3$, dependencies$3$, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    concat
  } = _ref;
  var matAlgo02xDS0 = createMatAlgo02xDS0({
    typed,
    equalScalar
  });
  var matAlgo06xS0S0 = createMatAlgo06xS0S0({
    typed,
    equalScalar
  });
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });
  var lcmTypes = 'number | BigNumber | Fraction | Matrix | Array';
  var lcmManySignature = {};
  lcmManySignature["".concat(lcmTypes, ", ").concat(lcmTypes, ", ...").concat(lcmTypes)] = typed.referToSelf(self => (a, b, args) => {
    var res = self(a, b);
    for (var i = 0; i < args.length; i++) {
      res = self(res, args[i]);
    }
    return res;
  });

  /**
   * Calculate the least common multiple for two or more values or arrays.
   *
   * lcm is defined as:
   *
   *     lcm(a, b) = abs(a * b) / gcd(a, b)
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.lcm(a, b)
   *    math.lcm(a, b, c, ...)
   *
   * Examples:
   *
   *    math.lcm(4, 6)               // returns 12
   *    math.lcm(6, 21)              // returns 42
   *    math.lcm(6, 21, 5)           // returns 210
   *
   *    math.lcm([4, 6], [6, 21])    // returns [12, 42]
   *
   * See also:
   *
   *    gcd, xgcd
   *
   * @param {... number | BigNumber | Array | Matrix} args  Two or more integer numbers
   * @return {number | BigNumber | Array | Matrix}                           The least common multiple
   */
  return typed(name$3$, {
    'number, number': lcmNumber,
    'BigNumber, BigNumber': _lcmBigNumber,
    'Fraction, Fraction': (x, y) => x.lcm(y)
  }, matrixAlgorithmSuite({
    SS: matAlgo06xS0S0,
    DS: matAlgo02xDS0,
    Ss: matAlgo11xS0s
  }), lcmManySignature);

  /**
   * Calculate lcm for two BigNumbers
   * @param {BigNumber} a
   * @param {BigNumber} b
   * @returns {BigNumber} Returns the least common multiple of a and b
   * @private
   */
  function _lcmBigNumber(a, b) {
    if (!a.isInt() || !b.isInt()) {
      throw new Error('Parameters in function lcm must be integer numbers');
    }
    if (a.isZero()) {
      return a;
    }
    if (b.isZero()) {
      return b;
    }

    // https://en.wikipedia.org/wiki/Euclidean_algorithm
    // evaluate lcm here inline to reduce overhead
    var prod = a.times(b);
    while (!b.isZero()) {
      var t = b;
      b = a.mod(t);
      a = t;
    }
    return prod.div(a).abs();
  }
});

var name$3_ = 'log10';
var dependencies$3_ = ['typed', 'config', 'Complex'];
var createLog10 = /* #__PURE__ */factory(name$3_, dependencies$3_, _ref => {
  var {
    typed,
    config,
    Complex: _Complex
  } = _ref;
  /**
   * Calculate the 10-base logarithm of a value. This is the same as calculating `log(x, 10)`.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.log10(x)
   *
   * Examples:
   *
   *    math.log10(0.00001)            // returns -5
   *    math.log10(10000)              // returns 4
   *    math.log(10000) / math.log(10) // returns 4
   *    math.pow(10, 4)                // returns 10000
   *
   * See also:
   *
   *    exp, log, log1p, log2
   *
   * @param {number | BigNumber | Complex | Array | Matrix} x
   *            Value for which to calculate the logarithm.
   * @return {number | BigNumber | Complex | Array | Matrix}
   *            Returns the 10-base logarithm of `x`
   */
  return typed(name$3_, {
    number: function number(x) {
      if (x >= 0 || config.predictable) {
        return log10Number(x);
      } else {
        // negative value -> complex value computation
        return new _Complex(x, 0).log().div(Math.LN10);
      }
    },
    Complex: function Complex(x) {
      return new _Complex(x).log().div(Math.LN10);
    },
    BigNumber: function BigNumber(x) {
      if (!x.isNegative() || config.predictable) {
        return x.log();
      } else {
        // downgrade to number, return Complex valued result
        return new _Complex(x.toNumber(), 0).log().div(Math.LN10);
      }
    },
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$3Z = 'log2';
var dependencies$3Z = ['typed', 'config', 'Complex'];
var createLog2 = /* #__PURE__ */factory(name$3Z, dependencies$3Z, _ref => {
  var {
    typed,
    config,
    Complex
  } = _ref;
  /**
   * Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.log2(x)
   *
   * Examples:
   *
   *    math.log2(0.03125)           // returns -5
   *    math.log2(16)                // returns 4
   *    math.log2(16) / math.log2(2) // returns 4
   *    math.pow(2, 4)               // returns 16
   *
   * See also:
   *
   *    exp, log, log1p, log10
   *
   * @param {number | BigNumber | Complex | Array | Matrix} x
   *            Value for which to calculate the logarithm.
   * @return {number | BigNumber | Complex | Array | Matrix}
   *            Returns the 2-base logarithm of `x`
   */
  return typed(name$3Z, {
    number: function number(x) {
      if (x >= 0 || config.predictable) {
        return log2Number(x);
      } else {
        // negative value -> complex value computation
        return _log2Complex(new Complex(x, 0));
      }
    },
    Complex: _log2Complex,
    BigNumber: function BigNumber(x) {
      if (!x.isNegative() || config.predictable) {
        return x.log(2);
      } else {
        // downgrade to number, return Complex valued result
        return _log2Complex(new Complex(x.toNumber(), 0));
      }
    },
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });

  /**
   * Calculate log2 for a complex value
   * @param {Complex} x
   * @returns {Complex}
   * @private
   */
  function _log2Complex(x) {
    var newX = Math.sqrt(x.re * x.re + x.im * x.im);
    return new Complex(Math.log2 ? Math.log2(newX) : Math.log(newX) / Math.LN2, Math.atan2(x.im, x.re) / Math.LN2);
  }
});

var name$3Y = 'multiplyScalar';
var dependencies$3Y = ['typed'];
var createMultiplyScalar = /* #__PURE__ */factory(name$3Y, dependencies$3Y, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Multiply two scalar values, `x * y`.
   * This function is meant for internal use: it is used by the public function
   * `multiply`
   *
   * This function does not support collections (Array or Matrix).
   *
   * @param  {number | BigNumber | bigint | Fraction | Complex | Unit} x   First value to multiply
   * @param  {number | BigNumber | bigint | Fraction | Complex} y          Second value to multiply
   * @return {number | BigNumber | bigint | Fraction | Complex | Unit}     Multiplication of `x` and `y`
   * @private
   */
  return typed('multiplyScalar', {
    'number, number': multiplyNumber,
    'Complex, Complex': function ComplexComplex(x, y) {
      return x.mul(y);
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      return x.times(y);
    },
    'bigint, bigint': function bigintBigint(x, y) {
      return x * y;
    },
    'Fraction, Fraction': function FractionFraction(x, y) {
      return x.mul(y);
    },
    'number | Fraction | BigNumber | Complex, Unit': (x, y) => y.multiply(x),
    'Unit, number | Fraction | BigNumber | Complex | Unit': (x, y) => x.multiply(y)
  });
});

var name$3X = 'multiply';
var dependencies$3X = ['typed', 'matrix', 'addScalar', 'multiplyScalar', 'equalScalar', 'dot'];
var createMultiply = /* #__PURE__ */factory(name$3X, dependencies$3X, _ref => {
  var {
    typed,
    matrix,
    addScalar,
    multiplyScalar,
    equalScalar,
    dot
  } = _ref;
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matAlgo14xDs = createMatAlgo14xDs({
    typed
  });
  function _validateMatrixDimensions(size1, size2) {
    // check left operand dimensions
    switch (size1.length) {
      case 1:
        // check size2
        switch (size2.length) {
          case 1:
            // Vector x Vector
            if (size1[0] !== size2[0]) {
              // throw error
              throw new RangeError('Dimension mismatch in multiplication. Vectors must have the same length');
            }
            break;
          case 2:
            // Vector x Matrix
            if (size1[0] !== size2[0]) {
              // throw error
              throw new RangeError('Dimension mismatch in multiplication. Vector length (' + size1[0] + ') must match Matrix rows (' + size2[0] + ')');
            }
            break;
          default:
            throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)');
        }
        break;
      case 2:
        // check size2
        switch (size2.length) {
          case 1:
            // Matrix x Vector
            if (size1[1] !== size2[0]) {
              // throw error
              throw new RangeError('Dimension mismatch in multiplication. Matrix columns (' + size1[1] + ') must match Vector length (' + size2[0] + ')');
            }
            break;
          case 2:
            // Matrix x Matrix
            if (size1[1] !== size2[0]) {
              // throw error
              throw new RangeError('Dimension mismatch in multiplication. Matrix A columns (' + size1[1] + ') must match Matrix B rows (' + size2[0] + ')');
            }
            break;
          default:
            throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)');
        }
        break;
      default:
        throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix A has ' + size1.length + ' dimensions)');
    }
  }

  /**
   * C = A * B
   *
   * @param {Matrix} a            Dense Vector   (N)
   * @param {Matrix} b            Dense Vector   (N)
   *
   * @return {number}             Scalar value
   */
  function _multiplyVectorVector(a, b, n) {
    // check empty vector
    if (n === 0) {
      throw new Error('Cannot multiply two empty vectors');
    }
    return dot(a, b);
  }

  /**
   * C = A * B
   *
   * @param {Matrix} a            Dense Vector   (M)
   * @param {Matrix} b            Matrix         (MxN)
   *
   * @return {Matrix}             Dense Vector   (N)
   */
  function _multiplyVectorMatrix(a, b) {
    // process storage
    if (b.storage() !== 'dense') {
      throw new Error('Support for SparseMatrix not implemented');
    }
    return _multiplyVectorDenseMatrix(a, b);
  }

  /**
   * C = A * B
   *
   * @param {Matrix} a            Dense Vector   (M)
   * @param {Matrix} b            Dense Matrix   (MxN)
   *
   * @return {Matrix}             Dense Vector   (N)
   */
  function _multiplyVectorDenseMatrix(a, b) {
    // a dense
    var adata = a._data;
    var asize = a._size;
    var adt = a._datatype || a.getDataType();
    // b dense
    var bdata = b._data;
    var bsize = b._size;
    var bdt = b._datatype || b.getDataType();
    // rows & columns
    var alength = asize[0];
    var bcolumns = bsize[1];

    // datatype
    var dt;
    // addScalar signature to use
    var af = addScalar;
    // multiplyScalar signature to use
    var mf = multiplyScalar;

    // process data types
    if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
      // datatype
      dt = adt;
      // find signatures that matches (dt, dt)
      af = typed.find(addScalar, [dt, dt]);
      mf = typed.find(multiplyScalar, [dt, dt]);
    }

    // result
    var c = [];

    // loop matrix columns
    for (var j = 0; j < bcolumns; j++) {
      // sum (do not initialize it with zero)
      var sum = mf(adata[0], bdata[0][j]);
      // loop vector
      for (var i = 1; i < alength; i++) {
        // multiply & accumulate
        sum = af(sum, mf(adata[i], bdata[i][j]));
      }
      c[j] = sum;
    }

    // return matrix
    return a.createDenseMatrix({
      data: c,
      size: [bcolumns],
      datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
    });
  }

  /**
   * C = A * B
   *
   * @param {Matrix} a            Matrix         (MxN)
   * @param {Matrix} b            Dense Vector   (N)
   *
   * @return {Matrix}             Dense Vector   (M)
   */
  var _multiplyMatrixVector = typed('_multiplyMatrixVector', {
    'DenseMatrix, any': _multiplyDenseMatrixVector,
    'SparseMatrix, any': _multiplySparseMatrixVector
  });

  /**
   * C = A * B
   *
   * @param {Matrix} a            Matrix         (MxN)
   * @param {Matrix} b            Matrix         (NxC)
   *
   * @return {Matrix}             Matrix         (MxC)
   */
  var _multiplyMatrixMatrix = typed('_multiplyMatrixMatrix', {
    'DenseMatrix, DenseMatrix': _multiplyDenseMatrixDenseMatrix,
    'DenseMatrix, SparseMatrix': _multiplyDenseMatrixSparseMatrix,
    'SparseMatrix, DenseMatrix': _multiplySparseMatrixDenseMatrix,
    'SparseMatrix, SparseMatrix': _multiplySparseMatrixSparseMatrix
  });

  /**
   * C = A * B
   *
   * @param {Matrix} a            DenseMatrix  (MxN)
   * @param {Matrix} b            Dense Vector (N)
   *
   * @return {Matrix}             Dense Vector (M)
   */
  function _multiplyDenseMatrixVector(a, b) {
    // a dense
    var adata = a._data;
    var asize = a._size;
    var adt = a._datatype || a.getDataType();
    // b dense
    var bdata = b._data;
    var bdt = b._datatype || b.getDataType();
    // rows & columns
    var arows = asize[0];
    var acolumns = asize[1];

    // datatype
    var dt;
    // addScalar signature to use
    var af = addScalar;
    // multiplyScalar signature to use
    var mf = multiplyScalar;

    // process data types
    if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
      // datatype
      dt = adt;
      // find signatures that matches (dt, dt)
      af = typed.find(addScalar, [dt, dt]);
      mf = typed.find(multiplyScalar, [dt, dt]);
    }

    // result
    var c = [];

    // loop matrix a rows
    for (var i = 0; i < arows; i++) {
      // current row
      var row = adata[i];
      // sum (do not initialize it with zero)
      var sum = mf(row[0], bdata[0]);
      // loop matrix a columns
      for (var j = 1; j < acolumns; j++) {
        // multiply & accumulate
        sum = af(sum, mf(row[j], bdata[j]));
      }
      c[i] = sum;
    }

    // return matrix
    return a.createDenseMatrix({
      data: c,
      size: [arows],
      datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
    });
  }

  /**
   * C = A * B
   *
   * @param {Matrix} a            DenseMatrix    (MxN)
   * @param {Matrix} b            DenseMatrix    (NxC)
   *
   * @return {Matrix}             DenseMatrix    (MxC)
   */
  function _multiplyDenseMatrixDenseMatrix(a, b) {
    // getDataType()
    // a dense
    var adata = a._data;
    var asize = a._size;
    var adt = a._datatype || a.getDataType();
    // b dense
    var bdata = b._data;
    var bsize = b._size;
    var bdt = b._datatype || b.getDataType();
    // rows & columns
    var arows = asize[0];
    var acolumns = asize[1];
    var bcolumns = bsize[1];

    // datatype
    var dt;
    // addScalar signature to use
    var af = addScalar;
    // multiplyScalar signature to use
    var mf = multiplyScalar;

    // process data types
    if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed' && adt !== 'mixed') {
      // datatype
      dt = adt;
      // find signatures that matches (dt, dt)
      af = typed.find(addScalar, [dt, dt]);
      mf = typed.find(multiplyScalar, [dt, dt]);
    }

    // result
    var c = [];

    // loop matrix a rows
    for (var i = 0; i < arows; i++) {
      // current row
      var row = adata[i];
      // initialize row array
      c[i] = [];
      // loop matrix b columns
      for (var j = 0; j < bcolumns; j++) {
        // sum (avoid initializing sum to zero)
        var sum = mf(row[0], bdata[0][j]);
        // loop matrix a columns
        for (var x = 1; x < acolumns; x++) {
          // multiply & accumulate
          sum = af(sum, mf(row[x], bdata[x][j]));
        }
        c[i][j] = sum;
      }
    }

    // return matrix
    return a.createDenseMatrix({
      data: c,
      size: [arows, bcolumns],
      datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
    });
  }

  /**
   * C = A * B
   *
   * @param {Matrix} a            DenseMatrix    (MxN)
   * @param {Matrix} b            SparseMatrix   (NxC)
   *
   * @return {Matrix}             SparseMatrix   (MxC)
   */
  function _multiplyDenseMatrixSparseMatrix(a, b) {
    // a dense
    var adata = a._data;
    var asize = a._size;
    var adt = a._datatype || a.getDataType();
    // b sparse
    var bvalues = b._values;
    var bindex = b._index;
    var bptr = b._ptr;
    var bsize = b._size;
    var bdt = b._datatype || b._data === undefined ? b._datatype : b.getDataType();
    // validate b matrix
    if (!bvalues) {
      throw new Error('Cannot multiply Dense Matrix times Pattern only Matrix');
    }
    // rows & columns
    var arows = asize[0];
    var bcolumns = bsize[1];

    // datatype
    var dt;
    // addScalar signature to use
    var af = addScalar;
    // multiplyScalar signature to use
    var mf = multiplyScalar;
    // equalScalar signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;

    // process data types
    if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
      // datatype
      dt = adt;
      // find signatures that matches (dt, dt)
      af = typed.find(addScalar, [dt, dt]);
      mf = typed.find(multiplyScalar, [dt, dt]);
      eq = typed.find(equalScalar, [dt, dt]);
      // convert 0 to the same datatype
      zero = typed.convert(0, dt);
    }

    // result
    var cvalues = [];
    var cindex = [];
    var cptr = [];
    // c matrix
    var c = b.createSparseMatrix({
      values: cvalues,
      index: cindex,
      ptr: cptr,
      size: [arows, bcolumns],
      datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
    });

    // loop b columns
    for (var jb = 0; jb < bcolumns; jb++) {
      // update ptr
      cptr[jb] = cindex.length;
      // indeces in column jb
      var kb0 = bptr[jb];
      var kb1 = bptr[jb + 1];
      // do not process column jb if no data exists
      if (kb1 > kb0) {
        // last row mark processed
        var last = 0;
        // loop a rows
        for (var i = 0; i < arows; i++) {
          // column mark
          var mark = i + 1;
          // C[i, jb]
          var cij = void 0;
          // values in b column j
          for (var kb = kb0; kb < kb1; kb++) {
            // row
            var ib = bindex[kb];
            // check value has been initialized
            if (last !== mark) {
              // first value in column jb
              cij = mf(adata[i][ib], bvalues[kb]);
              // update mark
              last = mark;
            } else {
              // accumulate value
              cij = af(cij, mf(adata[i][ib], bvalues[kb]));
            }
          }
          // check column has been processed and value != 0
          if (last === mark && !eq(cij, zero)) {
            // push row & value
            cindex.push(i);
            cvalues.push(cij);
          }
        }
      }
    }
    // update ptr
    cptr[bcolumns] = cindex.length;

    // return sparse matrix
    return c;
  }

  /**
   * C = A * B
   *
   * @param {Matrix} a            SparseMatrix    (MxN)
   * @param {Matrix} b            Dense Vector (N)
   *
   * @return {Matrix}             SparseMatrix    (M, 1)
   */
  function _multiplySparseMatrixVector(a, b) {
    // a sparse
    var avalues = a._values;
    var aindex = a._index;
    var aptr = a._ptr;
    var adt = a._datatype || a._data === undefined ? a._datatype : a.getDataType();
    // validate a matrix
    if (!avalues) {
      throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix');
    }
    // b dense
    var bdata = b._data;
    var bdt = b._datatype || b.getDataType();
    // rows & columns
    var arows = a._size[0];
    var brows = b._size[0];
    // result
    var cvalues = [];
    var cindex = [];
    var cptr = [];

    // datatype
    var dt;
    // addScalar signature to use
    var af = addScalar;
    // multiplyScalar signature to use
    var mf = multiplyScalar;
    // equalScalar signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;

    // process data types
    if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
      // datatype
      dt = adt;
      // find signatures that matches (dt, dt)
      af = typed.find(addScalar, [dt, dt]);
      mf = typed.find(multiplyScalar, [dt, dt]);
      eq = typed.find(equalScalar, [dt, dt]);
      // convert 0 to the same datatype
      zero = typed.convert(0, dt);
    }

    // workspace
    var x = [];
    // vector with marks indicating a value x[i] exists in a given column
    var w = [];

    // update ptr
    cptr[0] = 0;
    // rows in b
    for (var ib = 0; ib < brows; ib++) {
      // b[ib]
      var vbi = bdata[ib];
      // check b[ib] != 0, avoid loops
      if (!eq(vbi, zero)) {
        // A values & index in ib column
        for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
          // a row
          var ia = aindex[ka];
          // check value exists in current j
          if (!w[ia]) {
            // ia is new entry in j
            w[ia] = true;
            // add i to pattern of C
            cindex.push(ia);
            // x(ia) = A
            x[ia] = mf(vbi, avalues[ka]);
          } else {
            // i exists in C already
            x[ia] = af(x[ia], mf(vbi, avalues[ka]));
          }
        }
      }
    }
    // copy values from x to column jb of c
    for (var p1 = cindex.length, p = 0; p < p1; p++) {
      // row
      var ic = cindex[p];
      // copy value
      cvalues[p] = x[ic];
    }
    // update ptr
    cptr[1] = cindex.length;

    // matrix to return
    return a.createSparseMatrix({
      values: cvalues,
      index: cindex,
      ptr: cptr,
      size: [arows, 1],
      datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
    });
  }

  /**
   * C = A * B
   *
   * @param {Matrix} a            SparseMatrix      (MxN)
   * @param {Matrix} b            DenseMatrix       (NxC)
   *
   * @return {Matrix}             SparseMatrix      (MxC)
   */
  function _multiplySparseMatrixDenseMatrix(a, b) {
    // a sparse
    var avalues = a._values;
    var aindex = a._index;
    var aptr = a._ptr;
    var adt = a._datatype || a._data === undefined ? a._datatype : a.getDataType();
    // validate a matrix
    if (!avalues) {
      throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix');
    }
    // b dense
    var bdata = b._data;
    var bdt = b._datatype || b.getDataType();
    // rows & columns
    var arows = a._size[0];
    var brows = b._size[0];
    var bcolumns = b._size[1];

    // datatype
    var dt;
    // addScalar signature to use
    var af = addScalar;
    // multiplyScalar signature to use
    var mf = multiplyScalar;
    // equalScalar signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;

    // process data types
    if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
      // datatype
      dt = adt;
      // find signatures that matches (dt, dt)
      af = typed.find(addScalar, [dt, dt]);
      mf = typed.find(multiplyScalar, [dt, dt]);
      eq = typed.find(equalScalar, [dt, dt]);
      // convert 0 to the same datatype
      zero = typed.convert(0, dt);
    }

    // result
    var cvalues = [];
    var cindex = [];
    var cptr = [];
    // c matrix
    var c = a.createSparseMatrix({
      values: cvalues,
      index: cindex,
      ptr: cptr,
      size: [arows, bcolumns],
      datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
    });

    // workspace
    var x = [];
    // vector with marks indicating a value x[i] exists in a given column
    var w = [];

    // loop b columns
    for (var jb = 0; jb < bcolumns; jb++) {
      // update ptr
      cptr[jb] = cindex.length;
      // mark in workspace for current column
      var mark = jb + 1;
      // rows in jb
      for (var ib = 0; ib < brows; ib++) {
        // b[ib, jb]
        var vbij = bdata[ib][jb];
        // check b[ib, jb] != 0, avoid loops
        if (!eq(vbij, zero)) {
          // A values & index in ib column
          for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
            // a row
            var ia = aindex[ka];
            // check value exists in current j
            if (w[ia] !== mark) {
              // ia is new entry in j
              w[ia] = mark;
              // add i to pattern of C
              cindex.push(ia);
              // x(ia) = A
              x[ia] = mf(vbij, avalues[ka]);
            } else {
              // i exists in C already
              x[ia] = af(x[ia], mf(vbij, avalues[ka]));
            }
          }
        }
      }
      // copy values from x to column jb of c
      for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) {
        // row
        var ic = cindex[p];
        // copy value
        cvalues[p] = x[ic];
      }
    }
    // update ptr
    cptr[bcolumns] = cindex.length;

    // return sparse matrix
    return c;
  }

  /**
   * C = A * B
   *
   * @param {Matrix} a            SparseMatrix      (MxN)
   * @param {Matrix} b            SparseMatrix      (NxC)
   *
   * @return {Matrix}             SparseMatrix      (MxC)
   */
  function _multiplySparseMatrixSparseMatrix(a, b) {
    // a sparse
    var avalues = a._values;
    var aindex = a._index;
    var aptr = a._ptr;
    var adt = a._datatype || a._data === undefined ? a._datatype : a.getDataType();
    // b sparse
    var bvalues = b._values;
    var bindex = b._index;
    var bptr = b._ptr;
    var bdt = b._datatype || b._data === undefined ? b._datatype : b.getDataType();

    // rows & columns
    var arows = a._size[0];
    var bcolumns = b._size[1];
    // flag indicating both matrices (a & b) contain data
    var values = avalues && bvalues;

    // datatype
    var dt;
    // addScalar signature to use
    var af = addScalar;
    // multiplyScalar signature to use
    var mf = multiplyScalar;

    // process data types
    if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
      // datatype
      dt = adt;
      // find signatures that matches (dt, dt)
      af = typed.find(addScalar, [dt, dt]);
      mf = typed.find(multiplyScalar, [dt, dt]);
    }

    // result
    var cvalues = values ? [] : undefined;
    var cindex = [];
    var cptr = [];
    // c matrix
    var c = a.createSparseMatrix({
      values: cvalues,
      index: cindex,
      ptr: cptr,
      size: [arows, bcolumns],
      datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
    });

    // workspace
    var x = values ? [] : undefined;
    // vector with marks indicating a value x[i] exists in a given column
    var w = [];
    // variables
    var ka, ka0, ka1, kb, kb0, kb1, ia, ib;
    // loop b columns
    for (var jb = 0; jb < bcolumns; jb++) {
      // update ptr
      cptr[jb] = cindex.length;
      // mark in workspace for current column
      var mark = jb + 1;
      // B values & index in j
      for (kb0 = bptr[jb], kb1 = bptr[jb + 1], kb = kb0; kb < kb1; kb++) {
        // b row
        ib = bindex[kb];
        // check we need to process values
        if (values) {
          // loop values in a[:,ib]
          for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
            // row
            ia = aindex[ka];
            // check value exists in current j
            if (w[ia] !== mark) {
              // ia is new entry in j
              w[ia] = mark;
              // add i to pattern of C
              cindex.push(ia);
              // x(ia) = A
              x[ia] = mf(bvalues[kb], avalues[ka]);
            } else {
              // i exists in C already
              x[ia] = af(x[ia], mf(bvalues[kb], avalues[ka]));
            }
          }
        } else {
          // loop values in a[:,ib]
          for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
            // row
            ia = aindex[ka];
            // check value exists in current j
            if (w[ia] !== mark) {
              // ia is new entry in j
              w[ia] = mark;
              // add i to pattern of C
              cindex.push(ia);
            }
          }
        }
      }
      // check we need to process matrix values (pattern matrix)
      if (values) {
        // copy values from x to column jb of c
        for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) {
          // row
          var ic = cindex[p];
          // copy value
          cvalues[p] = x[ic];
        }
      }
    }
    // update ptr
    cptr[bcolumns] = cindex.length;

    // return sparse matrix
    return c;
  }

  /**
   * Multiply two or more values, `x * y`.
   * For matrices, the matrix product is calculated.
   *
   * Syntax:
   *
   *    math.multiply(x, y)
   *    math.multiply(x, y, z, ...)
   *
   * Examples:
   *
   *    math.multiply(4, 5.2)        // returns number 20.8
   *    math.multiply(2, 3, 4)       // returns number 24
   *
   *    const a = math.complex(2, 3)
   *    const b = math.complex(4, 1)
   *    math.multiply(a, b)          // returns Complex 5 + 14i
   *
   *    const c = [[1, 2], [4, 3]]
   *    const d = [[1, 2, 3], [3, -4, 7]]
   *    math.multiply(c, d)          // returns Array [[7, -6, 17], [13, -4, 33]]
   *
   *    const e = math.unit('2.1 km')
   *    math.multiply(3, e)          // returns Unit 6.3 km
   *
   * See also:
   *
   *    divide, prod, cross, dot
   *
   * @param  {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} x First value to multiply
   * @param  {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} y Second value to multiply
   * @return {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y`
   */
  return typed(name$3X, multiplyScalar, {
    // we extend the signatures of multiplyScalar with signatures dealing with matrices

    'Array, Array': typed.referTo('Matrix, Matrix', selfMM => (x, y) => {
      // check dimensions
      _validateMatrixDimensions(arraySize(x), arraySize(y));

      // use dense matrix implementation
      var m = selfMM(matrix(x), matrix(y));
      // return array or scalar
      return isMatrix(m) ? m.valueOf() : m;
    }),
    'Matrix, Matrix': function MatrixMatrix(x, y) {
      // dimensions
      var xsize = x.size();
      var ysize = y.size();

      // check dimensions
      _validateMatrixDimensions(xsize, ysize);

      // process dimensions
      if (xsize.length === 1) {
        // process y dimensions
        if (ysize.length === 1) {
          // Vector * Vector
          return _multiplyVectorVector(x, y, xsize[0]);
        }
        // Vector * Matrix
        return _multiplyVectorMatrix(x, y);
      }
      // process y dimensions
      if (ysize.length === 1) {
        // Matrix * Vector
        return _multiplyMatrixVector(x, y);
      }
      // Matrix * Matrix
      return _multiplyMatrixMatrix(x, y);
    },
    'Matrix, Array': typed.referTo('Matrix,Matrix', selfMM => (x, y) => selfMM(x, matrix(y))),
    'Array, Matrix': typed.referToSelf(self => (x, y) => {
      // use Matrix * Matrix implementation
      return self(matrix(x, y.storage()), y);
    }),
    'SparseMatrix, any': function SparseMatrixAny(x, y) {
      return matAlgo11xS0s(x, y, multiplyScalar, false);
    },
    'DenseMatrix, any': function DenseMatrixAny(x, y) {
      return matAlgo14xDs(x, y, multiplyScalar, false);
    },
    'any, SparseMatrix': function anySparseMatrix(x, y) {
      return matAlgo11xS0s(y, x, multiplyScalar, true);
    },
    'any, DenseMatrix': function anyDenseMatrix(x, y) {
      return matAlgo14xDs(y, x, multiplyScalar, true);
    },
    'Array, any': function ArrayAny(x, y) {
      // use matrix implementation
      return matAlgo14xDs(matrix(x), y, multiplyScalar, false).valueOf();
    },
    'any, Array': function anyArray(x, y) {
      // use matrix implementation
      return matAlgo14xDs(matrix(y), x, multiplyScalar, true).valueOf();
    },
    'any, any': multiplyScalar,
    'any, any, ...any': typed.referToSelf(self => (x, y, rest) => {
      var result = self(x, y);
      for (var i = 0; i < rest.length; i++) {
        result = self(result, rest[i]);
      }
      return result;
    })
  });
});

var name$3W = 'nthRoot';
var dependencies$3W = ['typed', 'matrix', 'equalScalar', 'BigNumber', 'concat'];
var createNthRoot = /* #__PURE__ */factory(name$3W, dependencies$3W, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    BigNumber: _BigNumber,
    concat
  } = _ref;
  var matAlgo01xDSid = createMatAlgo01xDSid({
    typed
  });
  var matAlgo02xDS0 = createMatAlgo02xDS0({
    typed,
    equalScalar
  });
  var matAlgo06xS0S0 = createMatAlgo06xS0S0({
    typed,
    equalScalar
  });
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Calculate the nth root of a value.
   * The principal nth root of a positive real number A, is the positive real
   * solution of the equation
   *
   *     x^root = A
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *     math.nthRoot(a)
   *     math.nthRoot(a, root)
   *
   * Examples:
   *
   *     math.nthRoot(9, 2)    // returns 3 (since 3^2 == 9)
   *     math.sqrt(9)          // returns 3 (since 3^2 == 9)
   *     math.nthRoot(64, 3)   // returns 4 (since 4^3 == 64)
   *
   * See also:
   *
   *     sqrt, pow
   *
   * @param {number | BigNumber | Array | Matrix | Complex} a
   *              Value for which to calculate the nth root
   * @param {number | BigNumber} [root=2]    The root.
   * @return {number | Complex | Array | Matrix} Returns the nth root of `a`
   */
  function complexErr() {
    throw new Error('Complex number not supported in function nthRoot. Use nthRoots instead.');
  }
  return typed(name$3W, {
    number: nthRootNumber,
    'number, number': nthRootNumber,
    BigNumber: x => _bigNthRoot(x, new _BigNumber(2)),
    'BigNumber, BigNumber': _bigNthRoot,
    Complex: complexErr,
    'Complex, number': complexErr,
    Array: typed.referTo('DenseMatrix,number', selfDn => x => selfDn(matrix(x), 2).valueOf()),
    DenseMatrix: typed.referTo('DenseMatrix,number', selfDn => x => selfDn(x, 2)),
    SparseMatrix: typed.referTo('SparseMatrix,number', selfSn => x => selfSn(x, 2)),
    'SparseMatrix, SparseMatrix': typed.referToSelf(self => (x, y) => {
      // density must be one (no zeros in matrix)
      if (y.density() === 1) {
        // sparse + sparse
        return matAlgo06xS0S0(x, y, self);
      } else {
        // throw exception
        throw new Error('Root must be non-zero');
      }
    }),
    'DenseMatrix, SparseMatrix': typed.referToSelf(self => (x, y) => {
      // density must be one (no zeros in matrix)
      if (y.density() === 1) {
        // dense + sparse
        return matAlgo01xDSid(x, y, self, false);
      } else {
        // throw exception
        throw new Error('Root must be non-zero');
      }
    }),
    'Array, SparseMatrix': typed.referTo('DenseMatrix,SparseMatrix', selfDS => (x, y) => selfDS(matrix(x), y)),
    'number | BigNumber, SparseMatrix': typed.referToSelf(self => (x, y) => {
      // density must be one (no zeros in matrix)
      if (y.density() === 1) {
        // sparse - scalar
        return matAlgo11xS0s(y, x, self, true);
      } else {
        // throw exception
        throw new Error('Root must be non-zero');
      }
    })
  }, matrixAlgorithmSuite({
    scalar: 'number | BigNumber',
    SD: matAlgo02xDS0,
    Ss: matAlgo11xS0s,
    sS: false
  }));

  /**
   * Calculate the nth root of a for BigNumbers, solve x^root == a
   * https://rosettacode.org/wiki/Nth_root#JavaScript
   * @param {BigNumber} a
   * @param {BigNumber} root
   * @private
   */
  function _bigNthRoot(a, root) {
    var precision = _BigNumber.precision;
    var Big = _BigNumber.clone({
      precision: precision + 2
    });
    var zero = new _BigNumber(0);
    var one = new Big(1);
    var inv = root.isNegative();
    if (inv) {
      root = root.neg();
    }
    if (root.isZero()) {
      throw new Error('Root must be non-zero');
    }
    if (a.isNegative() && !root.abs().mod(2).equals(1)) {
      throw new Error('Root must be odd when a is negative.');
    }

    // edge cases zero and infinity
    if (a.isZero()) {
      return inv ? new Big(Infinity) : 0;
    }
    if (!a.isFinite()) {
      return inv ? zero : a;
    }
    var x = a.abs().pow(one.div(root));
    // If a < 0, we require that root is an odd integer,
    // so (-1) ^ (1/root) = -1
    x = a.isNeg() ? x.neg() : x;
    return new _BigNumber((inv ? one.div(x) : x).toPrecision(precision));
  }
});

var name$3V = 'sign';
var dependencies$3V = ['typed', 'BigNumber', 'Fraction', 'complex'];
var createSign = /* #__PURE__ */factory(name$3V, dependencies$3V, _ref => {
  var {
    typed,
    BigNumber: _BigNumber,
    complex,
    Fraction: _Fraction
  } = _ref;
  /**
   * Compute the sign of a value. The sign of a value x is:
   *
   * -  1 when x > 0
   * - -1 when x < 0
   * -  0 when x == 0
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.sign(x)
   *
   * Examples:
   *
   *    math.sign(3.5)               // returns 1
   *    math.sign(-4.2)              // returns -1
   *    math.sign(0)                 // returns 0
   *
   *    math.sign([3, 5, -2, 0, 2])  // returns [1, 1, -1, 0, 1]
   *
   * See also:
   *
   *    abs
   *
   * @param  {number | BigNumber | bigint | Fraction | Complex | Array | Matrix | Unit} x
   *            The number for which to determine the sign
   * @return {number | BigNumber | bigint | Fraction | Complex | Array | Matrix | Unit}
   *            The sign of `x`
   */
  return typed(name$3V, {
    number: signNumber,
    Complex: function Complex(x) {
      return x.im === 0 ? complex(signNumber(x.re)) : x.sign();
    },
    BigNumber: function BigNumber(x) {
      return new _BigNumber(x.cmp(0));
    },
    bigint: function bigint(x) {
      return x > 0n ? 1n : x < 0n ? -1n : 0n;
    },
    Fraction: function Fraction(x) {
      return new _Fraction(x.s, 1);
    },
    // deep map collection, skip zeros since sign(0) = 0
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self)),
    Unit: typed.referToSelf(self => x => {
      if (!x._isDerived() && x.units[0].unit.offset !== 0) {
        throw new TypeError('sign is ambiguous for units with offset');
      }
      return typed.find(self, x.valueType())(x.value);
    })
  });
});

var name$3U = 'sqrt';
var dependencies$3U = ['config', 'typed', 'Complex'];
var createSqrt = /* #__PURE__ */factory(name$3U, dependencies$3U, _ref => {
  var {
    config,
    typed,
    Complex
  } = _ref;
  /**
   * Calculate the square root of a value.
   *
   * For matrices, if you want the matrix square root of a square matrix,
   * use the `sqrtm` function. If you wish to apply `sqrt` elementwise to
   * a matrix M, use `math.map(M, math.sqrt)`.
   *
   * Syntax:
   *
   *    math.sqrt(x)
   *
   * Examples:
   *
   *    math.sqrt(25)                // returns 5
   *    math.square(5)               // returns 25
   *    math.sqrt(-4)                // returns Complex 2i
   *
   * See also:
   *
   *    square, multiply, cube, cbrt, sqrtm
   *
   * @param {number | BigNumber | Complex | Unit} x
   *            Value for which to calculate the square root.
   * @return {number | BigNumber | Complex | Unit}
   *            Returns the square root of `x`
   */
  return typed('sqrt', {
    number: _sqrtNumber,
    Complex: function Complex(x) {
      return x.sqrt();
    },
    BigNumber: function BigNumber(x) {
      if (!x.isNegative() || config.predictable) {
        return x.sqrt();
      } else {
        // negative value -> downgrade to number to do complex value computation
        return _sqrtNumber(x.toNumber());
      }
    },
    Unit: function Unit(x) {
      // Someday will work for complex units when they are implemented
      return x.pow(0.5);
    }
  });

  /**
   * Calculate sqrt for a number
   * @param {number} x
   * @returns {number | Complex} Returns the square root of x
   * @private
   */
  function _sqrtNumber(x) {
    if (isNaN(x)) {
      return NaN;
    } else if (x >= 0 || config.predictable) {
      return Math.sqrt(x);
    } else {
      return new Complex(x, 0).sqrt();
    }
  }
});

var name$3T = 'square';
var dependencies$3T = ['typed'];
var createSquare = /* #__PURE__ */factory(name$3T, dependencies$3T, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Compute the square of a value, `x * x`.
   * To avoid confusion with multiplying a square matrix by itself,
   * this function does not apply to matrices. If you wish to square
   * every element of a matrix, see the examples.
   *
   * Syntax:
   *
   *    math.square(x)
   *
   * Examples:
   *
   *    math.square(2)           // returns number 4
   *    math.square(3)           // returns number 9
   *    math.pow(3, 2)           // returns number 9
   *    math.multiply(3, 3)      // returns number 9
   *
   *    math.map([1, 2, 3, 4], math.square)  // returns Array [1, 4, 9, 16]
   *
   * See also:
   *
   *    multiply, cube, sqrt, pow
   *
   * @param  {number | BigNumber | bigint | Fraction | Complex | Unit} x
   *            Number for which to calculate the square
   * @return {number | BigNumber | bigint | Fraction | Complex | Unit}
   *            Squared value
   */
  return typed(name$3T, {
    number: squareNumber,
    Complex: function Complex(x) {
      return x.mul(x);
    },
    BigNumber: function BigNumber(x) {
      return x.times(x);
    },
    bigint: function bigint(x) {
      return x * x;
    },
    Fraction: function Fraction(x) {
      return x.mul(x);
    },
    Unit: function Unit(x) {
      return x.pow(2);
    }
  });
});

var name$3S = 'subtract';
var dependencies$3S = ['typed', 'matrix', 'equalScalar', 'subtractScalar', 'unaryMinus', 'DenseMatrix', 'concat'];
var createSubtract = /* #__PURE__ */factory(name$3S, dependencies$3S, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    subtractScalar,
    unaryMinus,
    DenseMatrix,
    concat
  } = _ref;
  // TODO: split function subtract in two: subtract and subtractScalar

  var matAlgo01xDSid = createMatAlgo01xDSid({
    typed
  });
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo05xSfSf = createMatAlgo05xSfSf({
    typed,
    equalScalar
  });
  var matAlgo10xSids = createMatAlgo10xSids({
    typed,
    DenseMatrix
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Subtract two values, `x - y`.
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.subtract(x, y)
   *
   * Examples:
   *
   *    math.subtract(5.3, 2)        // returns number 3.3
   *
   *    const a = math.complex(2, 3)
   *    const b = math.complex(4, 1)
   *    math.subtract(a, b)          // returns Complex -2 + 2i
   *
   *    math.subtract([5, 7, 4], 4)  // returns Array [1, 3, 0]
   *
   *    const c = math.unit('2.1 km')
   *    const d = math.unit('500m')
   *    math.subtract(c, d)          // returns Unit 1.6 km
   *
   * See also:
   *
   *    add
   *
   * @param  {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} x Initial value
   * @param  {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} y Value to subtract from `x`
   * @return {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} Subtraction of `x` and `y`
   */
  return typed(name$3S, {
    'any, any': subtractScalar
  }, matrixAlgorithmSuite({
    elop: subtractScalar,
    SS: matAlgo05xSfSf,
    DS: matAlgo01xDSid,
    SD: matAlgo03xDSf,
    Ss: matAlgo12xSfs,
    sS: matAlgo10xSids
  }));
});

var name$3R = 'xgcd';
var dependencies$3R = ['typed', 'config', 'matrix', 'BigNumber'];
var createXgcd = /* #__PURE__ */factory(name$3R, dependencies$3R, _ref => {
  var {
    typed,
    config,
    matrix,
    BigNumber
  } = _ref;
  /**
   * Calculate the extended greatest common divisor for two values.
   * See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm.
   *
   * Syntax:
   *
   *    math.xgcd(a, b)
   *
   * Examples:
   *
   *    math.xgcd(8, 12)             // returns [4, -1, 1]
   *    math.gcd(8, 12)              // returns 4
   *    math.xgcd(36163, 21199)      // returns [1247, -7, 12]
   *
   * See also:
   *
   *    gcd, lcm
   *
   * @param {number | BigNumber} a  An integer number
   * @param {number | BigNumber} b  An integer number
   * @return {Array}              Returns an array containing 3 integers `[div, m, n]`
   *                              where `div = gcd(a, b)` and `a*m + b*n = div`
   */
  return typed(name$3R, {
    'number, number': function numberNumber(a, b) {
      var res = xgcdNumber(a, b);
      return config.matrix === 'Array' ? res : matrix(res);
    },
    'BigNumber, BigNumber': _xgcdBigNumber
    // TODO: implement support for Fraction
  });

  /**
   * Calculate xgcd for two BigNumbers
   * @param {BigNumber} a
   * @param {BigNumber} b
   * @return {BigNumber[]} result
   * @private
   */
  function _xgcdBigNumber(a, b) {
    // source: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
    var
    // used to swap two variables
    t;
    var
    // quotient
    q;
    var
    // remainder
    r;
    var zero = new BigNumber(0);
    var one = new BigNumber(1);
    var x = zero;
    var lastx = one;
    var y = one;
    var lasty = zero;
    if (!a.isInt() || !b.isInt()) {
      throw new Error('Parameters in function xgcd must be integer numbers');
    }
    while (!b.isZero()) {
      q = a.div(b).floor();
      r = a.mod(b);
      t = x;
      x = lastx.minus(q.times(x));
      lastx = t;
      t = y;
      y = lasty.minus(q.times(y));
      lasty = t;
      a = b;
      b = r;
    }
    var res;
    if (a.lt(zero)) {
      res = [a.neg(), lastx.neg(), lasty.neg()];
    } else {
      res = [a, !a.isZero() ? lastx : 0, lasty];
    }
    return config.matrix === 'Array' ? res : matrix(res);
  }
});

var name$3Q = 'invmod';
var dependencies$3Q = ['typed', 'config', 'BigNumber', 'xgcd', 'equal', 'smaller', 'mod', 'add', 'isInteger'];
var createInvmod = /* #__PURE__ */factory(name$3Q, dependencies$3Q, _ref => {
  var {
    typed,
    config,
    BigNumber,
    xgcd,
    equal,
    smaller,
    mod,
    add,
    isInteger
  } = _ref;
  /**
   * Calculate the (modular) multiplicative inverse of a modulo b. Solution to the equation `ax ≣ 1 (mod b)`
   * See https://en.wikipedia.org/wiki/Modular_multiplicative_inverse.
   *
   * Syntax:
   *
   *    math.invmod(a, b)
   *
   * Examples:
   *
   *    math.invmod(8, 12)             // returns NaN
   *    math.invmod(7, 13)             // returns 2
   *    math.invmod(15151, 15122)      // returns 10429
   *
   * See also:
   *
   *    gcd, xgcd
   *
   * @param {number | BigNumber} a  An integer number
   * @param {number | BigNumber} b  An integer number
   * @return {number | BigNumber }  Returns an integer number
   *                              where `invmod(a,b)*a ≣ 1 (mod b)`
   */
  return typed(name$3Q, {
    'number, number': invmod,
    'BigNumber, BigNumber': invmod
  });
  function invmod(a, b) {
    if (!isInteger(a) || !isInteger(b)) throw new Error('Parameters in function invmod must be integer numbers');
    a = mod(a, b);
    if (equal(b, 0)) throw new Error('Divisor must be non zero');
    var res = xgcd(a, b);
    res = res.valueOf();
    var [gcd, inv] = res;
    if (!equal(gcd, BigNumber(1))) return NaN;
    inv = mod(inv, b);
    if (smaller(inv, BigNumber(0))) inv = add(inv, b);
    return inv;
  }
});

var name$3P = 'matAlgo09xS0Sf';
var dependencies$3P = ['typed', 'equalScalar'];
var createMatAlgo09xS0Sf = /* #__PURE__ */factory(name$3P, dependencies$3P, _ref => {
  var {
    typed,
    equalScalar
  } = _ref;
  /**
   * Iterates over SparseMatrix A and invokes the callback function f(Aij, Bij).
   * Callback function invoked NZA times, number of nonzero elements in A.
   *
   *
   *          ┌  f(Aij, Bij)  ; A(i,j) !== 0
   * C(i,j) = ┤
   *          └  0            ; otherwise
   *
   *
   * @param {Matrix}   a                 The SparseMatrix instance (A)
   * @param {Matrix}   b                 The SparseMatrix instance (B)
   * @param {Function} callback          The f(Aij,Bij) operation to invoke
   *
   * @return {Matrix}                    SparseMatrix (C)
   *
   * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
   */
  return function matAlgo09xS0Sf(a, b, callback) {
    // sparse matrix arrays
    var avalues = a._values;
    var aindex = a._index;
    var aptr = a._ptr;
    var asize = a._size;
    var adt = a._datatype || a._data === undefined ? a._datatype : a.getDataType();
    // sparse matrix arrays
    var bvalues = b._values;
    var bindex = b._index;
    var bptr = b._ptr;
    var bsize = b._size;
    var bdt = b._datatype || b._data === undefined ? b._datatype : b.getDataType();

    // validate dimensions
    if (asize.length !== bsize.length) {
      throw new DimensionError(asize.length, bsize.length);
    }

    // check rows & columns
    if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
      throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
    }

    // rows & columns
    var rows = asize[0];
    var columns = asize[1];

    // datatype
    var dt;
    // equal signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;
    // callback signature to use
    var cf = callback;

    // process data types
    if (typeof adt === 'string' && adt === bdt && adt !== 'mixed') {
      // datatype
      dt = adt;
      // find signature that matches (dt, dt)
      eq = typed.find(equalScalar, [dt, dt]);
      // convert 0 to the same datatype
      zero = typed.convert(0, dt);
      // callback
      cf = typed.find(callback, [dt, dt]);
    }

    // result arrays
    var cvalues = avalues && bvalues ? [] : undefined;
    var cindex = [];
    var cptr = [];

    // workspaces
    var x = cvalues ? [] : undefined;
    // marks indicating we have a value in x for a given column
    var w = [];

    // vars
    var i, j, k, k0, k1;

    // loop columns
    for (j = 0; j < columns; j++) {
      // update cptr
      cptr[j] = cindex.length;
      // column mark
      var mark = j + 1;
      // check we need to process values
      if (x) {
        // loop B(:,j)
        for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
          // row
          i = bindex[k];
          // update workspace
          w[i] = mark;
          x[i] = bvalues[k];
        }
      }
      // loop A(:,j)
      for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
        // row
        i = aindex[k];
        // check we need to process values
        if (x) {
          // b value @ i,j
          var vb = w[i] === mark ? x[i] : zero;
          // invoke f
          var vc = cf(avalues[k], vb);
          // check zero value
          if (!eq(vc, zero)) {
            // push index
            cindex.push(i);
            // push value
            cvalues.push(vc);
          }
        } else {
          // push index
          cindex.push(i);
        }
      }
    }
    // update cptr
    cptr[columns] = cindex.length;

    // return sparse matrix
    return a.createSparseMatrix({
      values: cvalues,
      index: cindex,
      ptr: cptr,
      size: [rows, columns],
      datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
    });
  };
});

var name$3O = 'dotMultiply';
var dependencies$3O = ['typed', 'matrix', 'equalScalar', 'multiplyScalar', 'concat'];
var createDotMultiply = /* #__PURE__ */factory(name$3O, dependencies$3O, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    multiplyScalar,
    concat
  } = _ref;
  var matAlgo02xDS0 = createMatAlgo02xDS0({
    typed,
    equalScalar
  });
  var matAlgo09xS0Sf = createMatAlgo09xS0Sf({
    typed,
    equalScalar
  });
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Multiply two matrices element wise. The function accepts both matrices and
   * scalar values.
   *
   * Syntax:
   *
   *    math.dotMultiply(x, y)
   *
   * Examples:
   *
   *    math.dotMultiply(2, 4) // returns 8
   *
   *    a = [[9, 5], [6, 1]]
   *    b = [[3, 2], [5, 2]]
   *
   *    math.dotMultiply(a, b) // returns [[27, 10], [30, 2]]
   *    math.multiply(a, b)    // returns [[52, 28], [23, 14]]
   *
   * See also:
   *
   *    multiply, divide, dotDivide
   *
   * @param  {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Left hand value
   * @param  {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Right hand value
   * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix}                    Multiplication of `x` and `y`
   */
  return typed(name$3O, matrixAlgorithmSuite({
    elop: multiplyScalar,
    SS: matAlgo09xS0Sf,
    DS: matAlgo02xDS0,
    Ss: matAlgo11xS0s
  }));
});

/**
 * Bitwise and for Bignumbers
 *
 * Special Cases:
 *   N &  n =  N
 *   n &  0 =  0
 *   n & -1 =  n
 *   n &  n =  n
 *   I &  I =  I
 *  -I & -I = -I
 *   I & -I =  0
 *   I &  n =  n
 *   I & -n =  I
 *  -I &  n =  0
 *  -I & -n = -I
 *
 * @param {BigNumber} x
 * @param {BigNumber} y
 * @return {BigNumber} Result of `x` & `y`, is fully precise
 * @private
 */
function bitAndBigNumber(x, y) {
  if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
    throw new Error('Integers expected in function bitAnd');
  }
  var BigNumber = x.constructor;
  if (x.isNaN() || y.isNaN()) {
    return new BigNumber(NaN);
  }
  if (x.isZero() || y.eq(-1) || x.eq(y)) {
    return x;
  }
  if (y.isZero() || x.eq(-1)) {
    return y;
  }
  if (!x.isFinite() || !y.isFinite()) {
    if (!x.isFinite() && !y.isFinite()) {
      if (x.isNegative() === y.isNegative()) {
        return x;
      }
      return new BigNumber(0);
    }
    if (!x.isFinite()) {
      if (y.isNegative()) {
        return x;
      }
      if (x.isNegative()) {
        return new BigNumber(0);
      }
      return y;
    }
    if (!y.isFinite()) {
      if (x.isNegative()) {
        return y;
      }
      if (y.isNegative()) {
        return new BigNumber(0);
      }
      return x;
    }
  }
  return bitwise(x, y, function (a, b) {
    return a & b;
  });
}

/**
 * Bitwise not
 * @param {BigNumber} x
 * @return {BigNumber} Result of ~`x`, fully precise
 *
 */
function bitNotBigNumber(x) {
  if (x.isFinite() && !x.isInteger()) {
    throw new Error('Integer expected in function bitNot');
  }
  var BigNumber = x.constructor;
  var prevPrec = BigNumber.precision;
  BigNumber.config({
    precision: 1E9
  });
  var result = x.plus(new BigNumber(1));
  result.s = -result.s || null;
  BigNumber.config({
    precision: prevPrec
  });
  return result;
}

/**
 * Bitwise OR for BigNumbers
 *
 * Special Cases:
 *   N |  n =  N
 *   n |  0 =  n
 *   n | -1 = -1
 *   n |  n =  n
 *   I |  I =  I
 *  -I | -I = -I
 *   I | -n = -1
 *   I | -I = -1
 *   I |  n =  I
 *  -I |  n = -I
 *  -I | -n = -n
 *
 * @param {BigNumber} x
 * @param {BigNumber} y
 * @return {BigNumber} Result of `x` | `y`, fully precise
 */
function bitOrBigNumber(x, y) {
  if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
    throw new Error('Integers expected in function bitOr');
  }
  var BigNumber = x.constructor;
  if (x.isNaN() || y.isNaN()) {
    return new BigNumber(NaN);
  }
  var negOne = new BigNumber(-1);
  if (x.isZero() || y.eq(negOne) || x.eq(y)) {
    return y;
  }
  if (y.isZero() || x.eq(negOne)) {
    return x;
  }
  if (!x.isFinite() || !y.isFinite()) {
    if (!x.isFinite() && !x.isNegative() && y.isNegative() || x.isNegative() && !y.isNegative() && !y.isFinite()) {
      return negOne;
    }
    if (x.isNegative() && y.isNegative()) {
      return x.isFinite() ? x : y;
    }
    return x.isFinite() ? y : x;
  }
  return bitwise(x, y, function (a, b) {
    return a | b;
  });
}

/**
 * Applies bitwise function to numbers
 * @param {BigNumber} x
 * @param {BigNumber} y
 * @param {function (a, b)} func
 * @return {BigNumber}
 */
function bitwise(x, y, func) {
  var BigNumber = x.constructor;
  var xBits, yBits;
  var xSign = +(x.s < 0);
  var ySign = +(y.s < 0);
  if (xSign) {
    xBits = decCoefficientToBinaryString(bitNotBigNumber(x));
    for (var i = 0; i < xBits.length; ++i) {
      xBits[i] ^= 1;
    }
  } else {
    xBits = decCoefficientToBinaryString(x);
  }
  if (ySign) {
    yBits = decCoefficientToBinaryString(bitNotBigNumber(y));
    for (var _i = 0; _i < yBits.length; ++_i) {
      yBits[_i] ^= 1;
    }
  } else {
    yBits = decCoefficientToBinaryString(y);
  }
  var minBits, maxBits, minSign;
  if (xBits.length <= yBits.length) {
    minBits = xBits;
    maxBits = yBits;
    minSign = xSign;
  } else {
    minBits = yBits;
    maxBits = xBits;
    minSign = ySign;
  }
  var shortLen = minBits.length;
  var longLen = maxBits.length;
  var expFuncVal = func(xSign, ySign) ^ 1;
  var outVal = new BigNumber(expFuncVal ^ 1);
  var twoPower = new BigNumber(1);
  var two = new BigNumber(2);
  var prevPrec = BigNumber.precision;
  BigNumber.config({
    precision: 1E9
  });
  while (shortLen > 0) {
    if (func(minBits[--shortLen], maxBits[--longLen]) === expFuncVal) {
      outVal = outVal.plus(twoPower);
    }
    twoPower = twoPower.times(two);
  }
  while (longLen > 0) {
    if (func(minSign, maxBits[--longLen]) === expFuncVal) {
      outVal = outVal.plus(twoPower);
    }
    twoPower = twoPower.times(two);
  }
  BigNumber.config({
    precision: prevPrec
  });
  if (expFuncVal === 0) {
    outVal.s = -outVal.s;
  }
  return outVal;
}

/* Extracted from decimal.js, and edited to specialize. */
function decCoefficientToBinaryString(x) {
  // Convert to string
  var a = x.d; // array with digits
  var r = a[0] + '';
  for (var i = 1; i < a.length; ++i) {
    var s = a[i] + '';
    for (var z = 7 - s.length; z--;) {
      s = '0' + s;
    }
    r += s;
  }
  var j = r.length;
  while (r.charAt(j) === '0') {
    j--;
  }
  var xe = x.e;
  var str = r.slice(0, j + 1 || 1);
  var strL = str.length;
  if (xe > 0) {
    if (++xe > strL) {
      // Append zeros.
      xe -= strL;
      while (xe--) {
        str += '0';
      }
    } else if (xe < strL) {
      str = str.slice(0, xe) + '.' + str.slice(xe);
    }
  }

  // Convert from base 10 (decimal) to base 2
  var arr = [0];
  for (var _i2 = 0; _i2 < str.length;) {
    var arrL = arr.length;
    while (arrL--) {
      arr[arrL] *= 10;
    }
    arr[0] += parseInt(str.charAt(_i2++)); // convert to int
    for (var _j = 0; _j < arr.length; ++_j) {
      if (arr[_j] > 1) {
        if (arr[_j + 1] === null || arr[_j + 1] === undefined) {
          arr[_j + 1] = 0;
        }
        arr[_j + 1] += arr[_j] >> 1;
        arr[_j] &= 1;
      }
    }
  }
  return arr.reverse();
}

/**
 * Bitwise XOR for BigNumbers
 *
 * Special Cases:
 *   N ^  n =  N
 *   n ^  0 =  n
 *   n ^  n =  0
 *   n ^ -1 = ~n
 *   I ^  n =  I
 *   I ^ -n = -I
 *   I ^ -I = -1
 *  -I ^  n = -I
 *  -I ^ -n =  I
 *
 * @param {BigNumber} x
 * @param {BigNumber} y
 * @return {BigNumber} Result of `x` ^ `y`, fully precise
 *
 */
function bitXor(x, y) {
  if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
    throw new Error('Integers expected in function bitXor');
  }
  var BigNumber = x.constructor;
  if (x.isNaN() || y.isNaN()) {
    return new BigNumber(NaN);
  }
  if (x.isZero()) {
    return y;
  }
  if (y.isZero()) {
    return x;
  }
  if (x.eq(y)) {
    return new BigNumber(0);
  }
  var negOne = new BigNumber(-1);
  if (x.eq(negOne)) {
    return bitNotBigNumber(y);
  }
  if (y.eq(negOne)) {
    return bitNotBigNumber(x);
  }
  if (!x.isFinite() || !y.isFinite()) {
    if (!x.isFinite() && !y.isFinite()) {
      return negOne;
    }
    return new BigNumber(x.isNegative() === y.isNegative() ? Infinity : -Infinity);
  }
  return bitwise(x, y, function (a, b) {
    return a ^ b;
  });
}

/**
 * Bitwise left shift
 *
 * Special Cases:
 *  n << -n = N
 *  n <<  N = N
 *  N <<  n = N
 *  n <<  0 = n
 *  0 <<  n = 0
 *  I <<  I = N
 *  I <<  n = I
 *  n <<  I = I
 *
 * @param {BigNumber} x
 * @param {BigNumber} y
 * @return {BigNumber} Result of `x` << `y`
 *
 */
function leftShiftBigNumber(x, y) {
  if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
    throw new Error('Integers expected in function leftShift');
  }
  var BigNumber = x.constructor;
  if (x.isNaN() || y.isNaN() || y.isNegative() && !y.isZero()) {
    return new BigNumber(NaN);
  }
  if (x.isZero() || y.isZero()) {
    return x;
  }
  if (!x.isFinite() && !y.isFinite()) {
    return new BigNumber(NaN);
  }

  // Math.pow(2, y) is fully precise for y < 55, and fast
  if (y.lt(55)) {
    return x.times(Math.pow(2, y.toNumber()) + '');
  }
  return x.times(new BigNumber(2).pow(y));
}

/*
 * Special Cases:
 *   n >> -n =  N
 *   n >>  N =  N
 *   N >>  n =  N
 *   I >>  I =  N
 *   n >>  0 =  n
 *   I >>  n =  I
 *  -I >>  n = -I
 *  -I >>  I = -I
 *   n >>  I =  I
 *  -n >>  I = -1
 *   0 >>  n =  0
 *
 * @param {BigNumber} value
 * @param {BigNumber} value
 * @return {BigNumber} Result of `x` >> `y`
 *
 */
function rightArithShiftBigNumber(x, y) {
  if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
    throw new Error('Integers expected in function rightArithShift');
  }
  var BigNumber = x.constructor;
  if (x.isNaN() || y.isNaN() || y.isNegative() && !y.isZero()) {
    return new BigNumber(NaN);
  }
  if (x.isZero() || y.isZero()) {
    return x;
  }
  if (!y.isFinite()) {
    if (x.isNegative()) {
      return new BigNumber(-1);
    }
    if (!x.isFinite()) {
      return new BigNumber(NaN);
    }
    return new BigNumber(0);
  }

  // Math.pow(2, y) is fully precise for y < 55, and fast
  if (y.lt(55)) {
    return x.div(Math.pow(2, y.toNumber()) + '').floor();
  }
  return x.div(new BigNumber(2).pow(y)).floor();
}

var name$3N = 'bitAnd';
var dependencies$3N = ['typed', 'matrix', 'equalScalar', 'concat'];
var createBitAnd = /* #__PURE__ */factory(name$3N, dependencies$3N, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    concat
  } = _ref;
  var matAlgo02xDS0 = createMatAlgo02xDS0({
    typed,
    equalScalar
  });
  var matAlgo06xS0S0 = createMatAlgo06xS0S0({
    typed,
    equalScalar
  });
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Bitwise AND two values, `x & y`.
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.bitAnd(x, y)
   *
   * Examples:
   *
   *    math.bitAnd(53, 131)               // returns number 1
   *
   *    math.bitAnd([1, 12, 31], 42)       // returns Array [0, 8, 10]
   *
   * See also:
   *
   *    bitNot, bitOr, bitXor, leftShift, rightArithShift, rightLogShift
   *
   * @param  {number | BigNumber | bigint | Array | Matrix} x First value to and
   * @param  {number | BigNumber | bigint | Array | Matrix} y Second value to and
   * @return {number | BigNumber | bigint | Array | Matrix} AND of `x` and `y`
   */
  return typed(name$3N, {
    'number, number': bitAndNumber,
    'BigNumber, BigNumber': bitAndBigNumber,
    'bigint, bigint': (x, y) => x & y
  }, matrixAlgorithmSuite({
    SS: matAlgo06xS0S0,
    DS: matAlgo02xDS0,
    Ss: matAlgo11xS0s
  }));
});

var name$3M = 'bitNot';
var dependencies$3M = ['typed'];
var createBitNot = /* #__PURE__ */factory(name$3M, dependencies$3M, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Bitwise NOT value, `~x`.
   * For matrices, the function is evaluated element wise.
   * For units, the function is evaluated on the best prefix base.
   *
   * Syntax:
   *
   *    math.bitNot(x)
   *
   * Examples:
   *
   *    math.bitNot(1)               // returns number -2
   *
   *    math.bitNot([2, -3, 4])      // returns Array [-3, 2, -5]
   *
   * See also:
   *
   *    bitAnd, bitOr, bitXor, leftShift, rightArithShift, rightLogShift
   *
   * @param  {number | BigNumber | bigint | Array | Matrix} x Value to not
   * @return {number | BigNumber | bigint | Array | Matrix} NOT of `x`
   */
  return typed(name$3M, {
    number: bitNotNumber,
    BigNumber: bitNotBigNumber,
    bigint: x => ~x,
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$3L = 'bitOr';
var dependencies$3L = ['typed', 'matrix', 'equalScalar', 'DenseMatrix', 'concat'];
var createBitOr = /* #__PURE__ */factory(name$3L, dependencies$3L, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo01xDSid = createMatAlgo01xDSid({
    typed
  });
  var matAlgo04xSidSid = createMatAlgo04xSidSid({
    typed,
    equalScalar
  });
  var matAlgo10xSids = createMatAlgo10xSids({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Bitwise OR two values, `x | y`.
   * For matrices, the function is evaluated element wise.
   * For units, the function is evaluated on the lowest print base.
   *
   * Syntax:
   *
   *    math.bitOr(x, y)
   *
   * Examples:
   *
   *    math.bitOr(1, 2)               // returns number 3
   *
   *    math.bitOr([1, 2, 3], 4)       // returns Array [5, 6, 7]
   *
   * See also:
   *
   *    bitAnd, bitNot, bitXor, leftShift, rightArithShift, rightLogShift
   *
   * @param  {number | BigNumber | bigint | Array | Matrix} x First value to or
   * @param  {number | BigNumber | bigint | Array | Matrix} y Second value to or
   * @return {number | BigNumber | bigint | Array | Matrix} OR of `x` and `y`
   */
  return typed(name$3L, {
    'number, number': bitOrNumber,
    'BigNumber, BigNumber': bitOrBigNumber,
    'bigint, bigint': (x, y) => x | y
  }, matrixAlgorithmSuite({
    SS: matAlgo04xSidSid,
    DS: matAlgo01xDSid,
    Ss: matAlgo10xSids
  }));
});

var name$3K = 'matAlgo07xSSf';
var dependencies$3K = ['typed', 'DenseMatrix'];
var createMatAlgo07xSSf = /* #__PURE__ */factory(name$3K, dependencies$3K, _ref => {
  var {
    typed,
    DenseMatrix
  } = _ref;
  /**
   * Iterates over SparseMatrix A and SparseMatrix B items (zero and nonzero) and invokes the callback function f(Aij, Bij).
   * Callback function invoked MxN times.
   *
   * C(i,j) = f(Aij, Bij)
   *
   * @param {Matrix}   a                 The SparseMatrix instance (A)
   * @param {Matrix}   b                 The SparseMatrix instance (B)
   * @param {Function} callback          The f(Aij,Bij) operation to invoke
   *
   * @return {Matrix}                    DenseMatrix (C)
   *
   * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
   */
  return function matAlgo07xSSf(a, b, callback) {
    // sparse matrix arrays
    var asize = a._size;
    var adt = a._datatype || a._data === undefined ? a._datatype : a.getDataType();
    // sparse matrix arrays
    var bsize = b._size;
    var bdt = b._datatype || b._data === undefined ? b._datatype : b.getDataType();

    // validate dimensions
    if (asize.length !== bsize.length) {
      throw new DimensionError(asize.length, bsize.length);
    }

    // check rows & columns
    if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
      throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
    }

    // rows & columns
    var rows = asize[0];
    var columns = asize[1];

    // datatype
    var dt;
    // zero value
    var zero = 0;
    // callback signature to use
    var cf = callback;

    // process data types
    if (typeof adt === 'string' && adt === bdt && adt !== 'mixed') {
      // datatype
      dt = adt;
      // convert 0 to the same datatype
      zero = typed.convert(0, dt);
      // callback
      cf = typed.find(callback, [dt, dt]);
    }

    // vars
    var i, j;

    // result arrays
    var cdata = [];
    // initialize c
    for (i = 0; i < rows; i++) {
      cdata[i] = [];
    }

    // workspaces
    var xa = [];
    var xb = [];
    // marks indicating we have a value in x for a given column
    var wa = [];
    var wb = [];

    // loop columns
    for (j = 0; j < columns; j++) {
      // columns mark
      var mark = j + 1;
      // scatter the values of A(:,j) into workspace
      _scatter(a, j, wa, xa, mark);
      // scatter the values of B(:,j) into workspace
      _scatter(b, j, wb, xb, mark);
      // loop rows
      for (i = 0; i < rows; i++) {
        // matrix values @ i,j
        var va = wa[i] === mark ? xa[i] : zero;
        var vb = wb[i] === mark ? xb[i] : zero;
        // invoke callback
        cdata[i][j] = cf(va, vb);
      }
    }

    // return dense matrix
    return new DenseMatrix({
      data: cdata,
      size: [rows, columns],
      datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
    });
  };
  function _scatter(m, j, w, x, mark) {
    // a arrays
    var values = m._values;
    var index = m._index;
    var ptr = m._ptr;
    // loop values in column j
    for (var k = ptr[j], k1 = ptr[j + 1]; k < k1; k++) {
      // row
      var i = index[k];
      // update workspace
      w[i] = mark;
      x[i] = values[k];
    }
  }
});

var name$3J = 'bitXor';
var dependencies$3J = ['typed', 'matrix', 'DenseMatrix', 'concat'];
var createBitXor = /* #__PURE__ */factory(name$3J, dependencies$3J, _ref => {
  var {
    typed,
    matrix,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo07xSSf = createMatAlgo07xSSf({
    typed,
    DenseMatrix
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Bitwise XOR two values, `x ^ y`.
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.bitXor(x, y)
   *
   * Examples:
   *
   *    math.bitXor(1, 2)               // returns number 3
   *
   *    math.bitXor([2, 3, 4], 4)       // returns Array [6, 7, 0]
   *
   * See also:
   *
   *    bitAnd, bitNot, bitOr, leftShift, rightArithShift, rightLogShift
   *
   * @param  {number | BigNumber | bigint | Array | Matrix} x First value to xor
   * @param  {number | BigNumber | bigint | Array | Matrix} y Second value to xor
   * @return {number | BigNumber | bigint | Array | Matrix} XOR of `x` and `y`
   */
  return typed(name$3J, {
    'number, number': bitXorNumber,
    'BigNumber, BigNumber': bitXor,
    'bigint, bigint': (x, y) => x ^ y
  }, matrixAlgorithmSuite({
    SS: matAlgo07xSSf,
    DS: matAlgo03xDSf,
    Ss: matAlgo12xSfs
  }));
});

var name$3I = 'arg';
var dependencies$3I = ['typed'];
var createArg = /* #__PURE__ */factory(name$3I, dependencies$3I, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Compute the argument of a complex value.
   * For a complex number `a + bi`, the argument is computed as `atan2(b, a)`.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.arg(x)
   *
   * Examples:
   *
   *    const a = math.complex(2, 2)
   *    math.arg(a) / math.pi          // returns number 0.25
   *
   *    const b = math.complex('2 + 3i')
   *    math.arg(b)                    // returns number 0.982793723247329
   *    math.atan2(3, 2)               // returns number 0.982793723247329
   *
   * See also:
   *
   *    re, im, conj, abs
   *
   * @param {number | BigNumber | Complex | Array | Matrix} x
   *            A complex number or array with complex numbers
   * @return {number | BigNumber | Array | Matrix} The argument of x
   */
  return typed(name$3I, {
    number: function number(x) {
      return Math.atan2(0, x);
    },
    BigNumber: function BigNumber(x) {
      return x.constructor.atan2(0, x);
    },
    Complex: function Complex(x) {
      return x.arg();
    },
    // TODO: implement BigNumber support for function arg

    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$3H = 'conj';
var dependencies$3H = ['typed'];
var createConj = /* #__PURE__ */factory(name$3H, dependencies$3H, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Compute the complex conjugate of a complex value.
   * If `x = a+bi`, the complex conjugate of `x` is `a - bi`.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.conj(x)
   *
   * Examples:
   *
   *    math.conj(math.complex('2 + 3i'))  // returns Complex 2 - 3i
   *    math.conj(math.complex('2 - 3i'))  // returns Complex 2 + 3i
   *    math.conj(math.complex('-5.2i'))  // returns Complex 5.2i
   *
   * See also:
   *
   *    re, im, arg, abs
   *
   * @param {number | BigNumber | Complex | Array | Matrix} x
   *            A complex number or array with complex numbers
   * @return {number | BigNumber | Complex | Array | Matrix}
   *            The complex conjugate of x
   */
  return typed(name$3H, {
    'number | BigNumber | Fraction': x => x,
    Complex: x => x.conjugate(),
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$3G = 'im';
var dependencies$3G = ['typed'];
var createIm = /* #__PURE__ */factory(name$3G, dependencies$3G, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Get the imaginary part of a complex number.
   * For a complex number `a + bi`, the function returns `b`.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.im(x)
   *
   * Examples:
   *
   *    const a = math.complex(2, 3)
   *    math.re(a)                     // returns number 2
   *    math.im(a)                     // returns number 3
   *
   *    math.re(math.complex('-5.2i')) // returns number -5.2
   *    math.re(math.complex(2.4))     // returns number 0
   *
   * See also:
   *
   *    re, conj, abs, arg
   *
   * @param {number | BigNumber | Complex | Array | Matrix} x
   *            A complex number or array with complex numbers
   * @return {number | BigNumber | Array | Matrix} The imaginary part of x
   */
  return typed(name$3G, {
    number: () => 0,
    'BigNumber | Fraction': x => x.mul(0),
    Complex: x => x.im,
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$3F = 're';
var dependencies$3F = ['typed'];
var createRe = /* #__PURE__ */factory(name$3F, dependencies$3F, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Get the real part of a complex number.
   * For a complex number `a + bi`, the function returns `a`.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.re(x)
   *
   * Examples:
   *
   *    const a = math.complex(2, 3)
   *    math.re(a)                     // returns number 2
   *    math.im(a)                     // returns number 3
   *
   *    math.re(math.complex('-5.2i')) // returns number 0
   *    math.re(math.complex(2.4))     // returns number 2.4
   *
   * See also:
   *
   *    im, conj, abs, arg
   *
   * @param {number | BigNumber | Complex | Array | Matrix} x
   *            A complex number or array with complex numbers
   * @return {number | BigNumber | Array | Matrix} The real part of x
   */
  return typed(name$3F, {
    'number | BigNumber | Fraction': x => x,
    Complex: x => x.re,
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$3E = 'not';
var dependencies$3E = ['typed'];
var createNot = /* #__PURE__ */factory(name$3E, dependencies$3E, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Logical `not`. Flips boolean value of a given parameter.
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.not(x)
   *
   * Examples:
   *
   *    math.not(2)      // returns false
   *    math.not(0)      // returns true
   *    math.not(true)   // returns false
   *
   *    a = [2, -7, 0]
   *    math.not(a)      // returns [false, false, true]
   *
   * See also:
   *
   *    and, or, xor
   *
   * @param  {number | BigNumber | bigint | Complex | Unit | Array | Matrix} x First value to check
   * @return {boolean | Array | Matrix}
   *            Returns true when input is a zero or empty value.
   */
  return typed(name$3E, {
    'null | undefined': () => true,
    number: notNumber,
    Complex: function Complex(x) {
      return x.re === 0 && x.im === 0;
    },
    BigNumber: function BigNumber(x) {
      return x.isZero() || x.isNaN();
    },
    bigint: x => !x,
    Unit: typed.referToSelf(self => x => typed.find(self, x.valueType())(x.value)),
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$3D = 'or';
var dependencies$3D = ['typed', 'matrix', 'equalScalar', 'DenseMatrix', 'concat'];
var createOr = /* #__PURE__ */factory(name$3D, dependencies$3D, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo05xSfSf = createMatAlgo05xSfSf({
    typed,
    equalScalar
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Logical `or`. Test if at least one value is defined with a nonzero/nonempty value.
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.or(x, y)
   *
   * Examples:
   *
   *    math.or(2, 4)   // returns true
   *
   *    a = [2, 5, 0]
   *    b = [0, 22, 0]
   *    c = 0
   *
   *    math.or(a, b)   // returns [true, true, false]
   *    math.or(b, c)   // returns [false, true, false]
   *
   * See also:
   *
   *    and, not, xor
   *
   * @param  {number | BigNumber | bigint | Complex | Unit | Array | Matrix} x First value to check
   * @param  {number | BigNumber | bigint | Complex | Unit | Array | Matrix} y Second value to check
   * @return {boolean | Array | Matrix}
   *            Returns true when one of the inputs is defined with a nonzero/nonempty value.
   */
  return typed(name$3D, {
    'number, number': orNumber,
    'Complex, Complex': function ComplexComplex(x, y) {
      return x.re !== 0 || x.im !== 0 || y.re !== 0 || y.im !== 0;
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      return !x.isZero() && !x.isNaN() || !y.isZero() && !y.isNaN();
    },
    'bigint, bigint': orNumber,
    'Unit, Unit': typed.referToSelf(self => (x, y) => self(x.value || 0, y.value || 0))
  }, matrixAlgorithmSuite({
    SS: matAlgo05xSfSf,
    DS: matAlgo03xDSf,
    Ss: matAlgo12xSfs
  }));
});

var name$3C = 'xor';
var dependencies$3C = ['typed', 'matrix', 'DenseMatrix', 'concat'];
var createXor = /* #__PURE__ */factory(name$3C, dependencies$3C, _ref => {
  var {
    typed,
    matrix,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo07xSSf = createMatAlgo07xSSf({
    typed,
    DenseMatrix
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Logical `xor`. Test whether one and only one value is defined with a nonzero/nonempty value.
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.xor(x, y)
   *
   * Examples:
   *
   *    math.xor(2, 4)   // returns false
   *
   *    a = [2, 0, 0]
   *    b = [2, 7, 0]
   *    c = 0
   *
   *    math.xor(a, b)   // returns [false, true, false]
   *    math.xor(a, c)   // returns [true, false, false]
   *
   * See also:
   *
   *    and, not, or
   *
   * @param  {number | BigNumber | bigint | Complex | Unit | Array | Matrix} x First value to check
   * @param  {number | BigNumber | bigint | Complex | Unit | Array | Matrix} y Second value to check
   * @return {boolean | Array | Matrix}
   *            Returns true when one and only one input is defined with a nonzero/nonempty value.
   */
  return typed(name$3C, {
    'number, number': xorNumber,
    'Complex, Complex': function ComplexComplex(x, y) {
      return (x.re !== 0 || x.im !== 0) !== (y.re !== 0 || y.im !== 0);
    },
    'bigint, bigint': xorNumber,
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      return (!x.isZero() && !x.isNaN()) !== (!y.isZero() && !y.isNaN());
    },
    'Unit, Unit': typed.referToSelf(self => (x, y) => self(x.value || 0, y.value || 0))
  }, matrixAlgorithmSuite({
    SS: matAlgo07xSSf,
    DS: matAlgo03xDSf,
    Ss: matAlgo12xSfs
  }));
});

var name$3B = 'concat';
var dependencies$3B = ['typed', 'matrix', 'isInteger'];
var createConcat = /* #__PURE__ */factory(name$3B, dependencies$3B, _ref => {
  var {
    typed,
    matrix,
    isInteger
  } = _ref;
  /**
   * Concatenate two or more matrices.
   *
   * Syntax:
   *
   *     math.concat(A, B, C, ...)
   *     math.concat(A, B, C, ..., dim)
   *
   * Where:
   *
   * - `dim: number` is a zero-based dimension over which to concatenate the matrices.
   *   By default the last dimension of the matrices.
   *
   * Examples:
   *
   *    const A = [[1, 2], [5, 6]]
   *    const B = [[3, 4], [7, 8]]
   *
   *    math.concat(A, B)                  // returns [[1, 2, 3, 4], [5, 6, 7, 8]]
   *    math.concat(A, B, 0)               // returns [[1, 2], [5, 6], [3, 4], [7, 8]]
   *    math.concat('hello', ' ', 'world') // returns 'hello world'
   *
   * See also:
   *
   *    size, squeeze, subset, transpose
   *
   * @param {... Array | Matrix} args     Two or more matrices
   * @return {Array | Matrix} Concatenated matrix
   */
  return typed(name$3B, {
    // TODO: change signature to '...Array | Matrix, dim?' when supported
    '...Array | Matrix | number | BigNumber': function ArrayMatrixNumberBigNumber(args) {
      var i;
      var len = args.length;
      var dim = -1; // zero-based dimension
      var prevDim;
      var asMatrix = false;
      var matrices = []; // contains multi dimensional arrays

      for (i = 0; i < len; i++) {
        var arg = args[i];

        // test whether we need to return a Matrix (if not we return an Array)
        if (isMatrix(arg)) {
          asMatrix = true;
        }
        if (isNumber(arg) || isBigNumber(arg)) {
          if (i !== len - 1) {
            throw new Error('Dimension must be specified as last argument');
          }

          // last argument contains the dimension on which to concatenate
          prevDim = dim;
          dim = arg.valueOf(); // change BigNumber to number

          if (!isInteger(dim)) {
            throw new TypeError('Integer number expected for dimension');
          }
          if (dim < 0 || i > 0 && dim > prevDim) {
            // TODO: would be more clear when throwing a DimensionError here
            throw new IndexError(dim, prevDim + 1);
          }
        } else {
          // this is a matrix or array
          var m = clone$2(arg).valueOf();
          var size = arraySize(m);
          matrices[i] = m;
          prevDim = dim;
          dim = size.length - 1;

          // verify whether each of the matrices has the same number of dimensions
          if (i > 0 && dim !== prevDim) {
            throw new DimensionError(prevDim + 1, dim + 1);
          }
        }
      }
      if (matrices.length === 0) {
        throw new SyntaxError('At least one matrix expected');
      }
      var res = matrices.shift();
      while (matrices.length) {
        res = concat(res, matrices.shift(), dim);
      }
      return asMatrix ? matrix(res) : res;
    },
    '...string': function string(args) {
      return args.join('');
    }
  });
});

var name$3A = 'column';
var dependencies$3A = ['typed', 'Index', 'matrix', 'range'];
var createColumn = /* #__PURE__ */factory(name$3A, dependencies$3A, _ref => {
  var {
    typed,
    Index,
    matrix,
    range
  } = _ref;
  /**
   * Return a column from a Matrix.
   *
   * Syntax:
   *
   *     math.column(value, index)
   *
   * Example:
   *
   *     // get a column
   *     const d = [[1, 2], [3, 4]]
   *     math.column(d, 1) // returns [[2], [4]]
   *
   * See also:
   *
   *     row
   *
   * @param {Array | Matrix } value   An array or matrix
   * @param {number} column           The index of the column
   * @return {Array | Matrix}         The retrieved column
   */
  return typed(name$3A, {
    'Matrix, number': _column,
    'Array, number': function ArrayNumber(value, column) {
      return _column(matrix(clone$2(value)), column).valueOf();
    }
  });

  /**
   * Retrieve a column of a matrix
   * @param {Matrix } value  A matrix
   * @param {number} column  The index of the column
   * @return {Matrix}        The retrieved column
   */
  function _column(value, column) {
    // check dimensions
    if (value.size().length !== 2) {
      throw new Error('Only two dimensional matrix is supported');
    }
    validateIndex(column, value.size()[1]);
    var rowRange = range(0, value.size()[0]);
    var index = new Index(rowRange, column);
    var result = value.subset(index);
    return isMatrix(result) ? result : matrix([[result]]);
  }
});

var name$3z = 'count';
var dependencies$3z = ['typed', 'size', 'prod'];
var createCount = /* #__PURE__ */factory(name$3z, dependencies$3z, _ref => {
  var {
    typed,
    size,
    prod
  } = _ref;
  /**
   * Count the number of elements of a matrix, array or string.
   *
   * Syntax:
   *
   *     math.count(x)
   *
   * Examples:
   *
   *     math.count('hello world')        // returns 11
   *     const A = [[1, 2, 3], [4, 5, 6]]
   *     math.count(A)                    // returns 6
   *     math.count(math.range(1,6))      // returns 5
   *
   * See also:
   *
   *     size
   *
   * @param {string | Array | Matrix} x  A matrix or string
   * @return {number} An integer with the elements in `x`.
   */
  return typed(name$3z, {
    string: function string(x) {
      return x.length;
    },
    'Matrix | Array': function MatrixArray(x) {
      return prod(size(x));
    }
  });
});

var name$3y = 'cross';
var dependencies$3y = ['typed', 'matrix', 'subtract', 'multiply'];
var createCross = /* #__PURE__ */factory(name$3y, dependencies$3y, _ref => {
  var {
    typed,
    matrix,
    subtract,
    multiply
  } = _ref;
  /**
   * Calculate the cross product for two vectors in three dimensional space.
   * The cross product of `A = [a1, a2, a3]` and `B = [b1, b2, b3]` is defined
   * as:
   *
   *    cross(A, B) = [
   *      a2 * b3 - a3 * b2,
   *      a3 * b1 - a1 * b3,
   *      a1 * b2 - a2 * b1
   *    ]
   *
   * If one of the input vectors has a dimension greater than 1, the output
   * vector will be a 1x3 (2-dimensional) matrix.
   *
   * Syntax:
   *
   *    math.cross(x, y)
   *
   * Examples:
   *
   *    math.cross([1, 1, 0],   [0, 1, 1])       // Returns [1, -1, 1]
   *    math.cross([3, -3, 1],  [4, 9, 2])       // Returns [-15, -2, 39]
   *    math.cross([2, 3, 4],   [5, 6, 7])       // Returns [-3, 6, -3]
   *    math.cross([[1, 2, 3]], [[4], [5], [6]]) // Returns [[-3, 6, -3]]
   *
   * See also:
   *
   *    dot, multiply
   *
   * @param  {Array | Matrix} x   First vector
   * @param  {Array | Matrix} y   Second vector
   * @return {Array | Matrix}     Returns the cross product of `x` and `y`
   */
  return typed(name$3y, {
    'Matrix, Matrix': function MatrixMatrix(x, y) {
      return matrix(_cross(x.toArray(), y.toArray()));
    },
    'Matrix, Array': function MatrixArray(x, y) {
      return matrix(_cross(x.toArray(), y));
    },
    'Array, Matrix': function ArrayMatrix(x, y) {
      return matrix(_cross(x, y.toArray()));
    },
    'Array, Array': _cross
  });

  /**
   * Calculate the cross product for two arrays
   * @param {Array} x  First vector
   * @param {Array} y  Second vector
   * @returns {Array} Returns the cross product of x and y
   * @private
   */
  function _cross(x, y) {
    var highestDimension = Math.max(arraySize(x).length, arraySize(y).length);
    x = squeeze(x);
    y = squeeze(y);
    var xSize = arraySize(x);
    var ySize = arraySize(y);
    if (xSize.length !== 1 || ySize.length !== 1 || xSize[0] !== 3 || ySize[0] !== 3) {
      throw new RangeError('Vectors with length 3 expected ' + '(Size A = [' + xSize.join(', ') + '], B = [' + ySize.join(', ') + '])');
    }
    var product = [subtract(multiply(x[1], y[2]), multiply(x[2], y[1])), subtract(multiply(x[2], y[0]), multiply(x[0], y[2])), subtract(multiply(x[0], y[1]), multiply(x[1], y[0]))];
    if (highestDimension > 1) {
      return [product];
    } else {
      return product;
    }
  }
});

var name$3x = 'diag';
var dependencies$3x = ['typed', 'matrix', 'DenseMatrix', 'SparseMatrix'];
var createDiag = /* #__PURE__ */factory(name$3x, dependencies$3x, _ref => {
  var {
    typed,
    matrix,
    DenseMatrix,
    SparseMatrix
  } = _ref;
  /**
   * Create a diagonal matrix or retrieve the diagonal of a matrix
   *
   * When `x` is a vector, a matrix with vector `x` on the diagonal will be returned.
   * When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector.
   * When k is positive, the values are placed on the super diagonal.
   * When k is negative, the values are placed on the sub diagonal.
   *
   * Syntax:
   *
   *     math.diag(X)
   *     math.diag(X, format)
   *     math.diag(X, k)
   *     math.diag(X, k, format)
   *
   * Examples:
   *
   *     // create a diagonal matrix
   *     math.diag([1, 2, 3])      // returns [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
   *     math.diag([1, 2, 3], 1)   // returns [[0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]
   *     math.diag([1, 2, 3], -1)  // returns [[0, 0, 0], [1, 0, 0], [0, 2, 0], [0, 0, 3]]
   *
   *    // retrieve the diagonal from a matrix
   *    const a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
   *    math.diag(a)   // returns [1, 5, 9]
   *
   * See also:
   *
   *     ones, zeros, identity
   *
   * @param {Matrix | Array} x          A two dimensional matrix or a vector
   * @param {number | BigNumber} [k=0]  The diagonal where the vector will be filled
   *                                    in or retrieved.
   * @param {string} [format='dense']   The matrix storage format.
   *
   * @returns {Matrix | Array} Diagonal matrix from input vector, or diagonal from input matrix.
   */
  return typed(name$3x, {
    // FIXME: simplify this huge amount of signatures as soon as typed-function supports optional arguments

    Array: function Array(x) {
      return _diag(x, 0, arraySize(x), null);
    },
    'Array, number': function ArrayNumber(x, k) {
      return _diag(x, k, arraySize(x), null);
    },
    'Array, BigNumber': function ArrayBigNumber(x, k) {
      return _diag(x, k.toNumber(), arraySize(x), null);
    },
    'Array, string': function ArrayString(x, format) {
      return _diag(x, 0, arraySize(x), format);
    },
    'Array, number, string': function ArrayNumberString(x, k, format) {
      return _diag(x, k, arraySize(x), format);
    },
    'Array, BigNumber, string': function ArrayBigNumberString(x, k, format) {
      return _diag(x, k.toNumber(), arraySize(x), format);
    },
    Matrix: function Matrix(x) {
      return _diag(x, 0, x.size(), x.storage());
    },
    'Matrix, number': function MatrixNumber(x, k) {
      return _diag(x, k, x.size(), x.storage());
    },
    'Matrix, BigNumber': function MatrixBigNumber(x, k) {
      return _diag(x, k.toNumber(), x.size(), x.storage());
    },
    'Matrix, string': function MatrixString(x, format) {
      return _diag(x, 0, x.size(), format);
    },
    'Matrix, number, string': function MatrixNumberString(x, k, format) {
      return _diag(x, k, x.size(), format);
    },
    'Matrix, BigNumber, string': function MatrixBigNumberString(x, k, format) {
      return _diag(x, k.toNumber(), x.size(), format);
    }
  });

  /**
   * Creeate diagonal matrix from a vector or vice versa
   * @param {Array | Matrix} x
   * @param {number} k
   * @param {string} format Storage format for matrix. If null,
   *                          an Array is returned
   * @returns {Array | Matrix}
   * @private
   */
  function _diag(x, k, size, format) {
    if (!isInteger(k)) {
      throw new TypeError('Second parameter in function diag must be an integer');
    }
    var kSuper = k > 0 ? k : 0;
    var kSub = k < 0 ? -k : 0;

    // check dimensions
    switch (size.length) {
      case 1:
        return _createDiagonalMatrix(x, k, format, size[0], kSub, kSuper);
      case 2:
        return _getDiagonal(x, k, format, size, kSub, kSuper);
    }
    throw new RangeError('Matrix for function diag must be 2 dimensional');
  }
  function _createDiagonalMatrix(x, k, format, l, kSub, kSuper) {
    // matrix size
    var ms = [l + kSub, l + kSuper];
    if (format && format !== 'sparse' && format !== 'dense') {
      throw new TypeError("Unknown matrix type ".concat(format, "\""));
    }

    // create diagonal matrix
    var m = format === 'sparse' ? SparseMatrix.diagonal(ms, x, k) : DenseMatrix.diagonal(ms, x, k);
    // check we need to return a matrix
    return format !== null ? m : m.valueOf();
  }
  function _getDiagonal(x, k, format, s, kSub, kSuper) {
    // check x is a Matrix
    if (isMatrix(x)) {
      // get diagonal matrix
      var dm = x.diagonal(k);
      // check we need to return a matrix
      if (format !== null) {
        // check we need to change matrix format
        if (format !== dm.storage()) {
          return matrix(dm, format);
        }
        return dm;
      }
      return dm.valueOf();
    }
    // vector size
    var n = Math.min(s[0] - kSub, s[1] - kSuper);
    // diagonal values
    var vector = [];
    // loop diagonal
    for (var i = 0; i < n; i++) {
      vector[i] = x[i + kSub][i + kSuper];
    }
    // check we need to return a matrix
    return format !== null ? matrix(vector) : vector;
  }
});

/**
 * Invoke a callback for functions like map and filter with a matching number of arguments
 * @param {function} callback
 * @param {any} value
 * @param {number | number[]} index
 * @param {Array} array
 * @param {string} mappingFnName   The name of the function that is invoking these callbacks, for example "map" or "filter"
 * @returns {*}
 */
function applyCallback(callback, value, index, array, mappingFnName) {
  if (typedFunction.isTypedFunction(callback)) {
    // invoke the typed callback function with the matching number of arguments only

    var args3 = [value, index, array];
    var signature3 = typedFunction.resolve(callback, args3);
    if (signature3) {
      return tryWithArgs(signature3.implementation, args3);
    }
    var args2 = [value, index];
    var signature2 = typedFunction.resolve(callback, args2);
    if (signature2) {
      return tryWithArgs(signature2.implementation, args2);
    }
    var args1 = [value];
    var signature1 = typedFunction.resolve(callback, args1);
    if (signature1) {
      return tryWithArgs(signature1.implementation, args1);
    }

    // fallback (will throw an exception)
    return tryWithArgs(callback, args3);
  } else {
    // A regular JavaScript function
    return callback(value, index, array);
  }

  /**
   * @param {function} signature The selected signature of the typed-function
   * @param {Array} args List with arguments to apply to the selected signature
   * @returns {*} Returns the return value of the invoked signature
   * @throws {TypeError} Throws an error when no matching signature was found
   */
  function tryWithArgs(signature, args) {
    try {
      return signature.apply(signature, args);
    } catch (err) {
      var _err$data;
      // Enrich the error message so the user understands that it took place inside the callback function
      if (err instanceof TypeError && ((_err$data = err.data) === null || _err$data === void 0 ? void 0 : _err$data.category) === 'wrongType') {
        var argsDesc = [];
        argsDesc.push("value: ".concat(typeOf(value)));
        if (args.length >= 2) {
          argsDesc.push("index: ".concat(typeOf(index)));
        }
        if (args.length >= 3) {
          argsDesc.push("array: ".concat(typeOf(array)));
        }
        throw new TypeError("Function ".concat(mappingFnName, " cannot apply callback arguments ") + "".concat(callback.name, "(").concat(argsDesc.join(', '), ") at index ").concat(JSON.stringify(index)));
      } else {
        throw new TypeError("Function ".concat(mappingFnName, " cannot apply callback arguments ") + "to function ".concat(callback.name, ": ").concat(err.message));
      }
    }
  }
}

var name$3w = 'filter';
var dependencies$3w = ['typed'];
var createFilter = /* #__PURE__ */factory(name$3w, dependencies$3w, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Filter the items in an array or one dimensional matrix.
   *
   * Syntax:
   *
   *    math.filter(x, test)
   *
   * Examples:
   *
   *    function isPositive (x) {
   *      return x > 0
   *    }
   *    math.filter([6, -2, -1, 4, 3], isPositive) // returns [6, 4, 3]
   *
   *    math.filter(["23", "foo", "100", "55", "bar"], /[0-9]+/) // returns ["23", "100", "55"]
   *
   * See also:
   *
   *    forEach, map, sort
   *
   * @param {Matrix | Array} x    A one dimensional matrix or array to filter
   * @param {Function | RegExp} test
   *        A function or regular expression to test items.
   *        All entries for which `test` returns true are returned.
   *        When `test` is a function, it is invoked with three parameters:
   *        the value of the element, the index of the element, and the
   *        matrix/array being traversed. The function must return a boolean.
   * @return {Matrix | Array} Returns the filtered matrix.
   */
  return typed('filter', {
    'Array, function': _filterCallback,
    'Matrix, function': function MatrixFunction(x, test) {
      return x.create(_filterCallback(x.toArray(), test));
    },
    'Array, RegExp': filterRegExp,
    'Matrix, RegExp': function MatrixRegExp(x, test) {
      return x.create(filterRegExp(x.toArray(), test));
    }
  });
});

/**
 * Filter values in a callback given a callback function
 * @param {Array} x
 * @param {Function} callback
 * @return {Array} Returns the filtered array
 * @private
 */
function _filterCallback(x, callback) {
  return filter(x, function (value, index, array) {
    // invoke the callback function with the right number of arguments
    return applyCallback(callback, value, [index], array, 'filter');
  });
}

var name$3v = 'flatten';
var dependencies$3v = ['typed', 'matrix'];
var createFlatten = /* #__PURE__ */factory(name$3v, dependencies$3v, _ref => {
  var {
    typed,
    matrix
  } = _ref;
  /**
   * Flatten a multidimensional matrix into a single dimensional matrix.
   * A new matrix is returned, the original matrix is left untouched.
   *
   * Syntax:
   *
   *    math.flatten(x)
   *
   * Examples:
   *
   *    math.flatten([[1,2], [3,4]])   // returns [1, 2, 3, 4]
   *
   * See also:
   *
   *    concat, resize, size, squeeze
   *
   * @param {Matrix | Array} x   Matrix to be flattened
   * @return {Matrix | Array} Returns the flattened matrix
   */
  return typed(name$3v, {
    Array: function Array(x) {
      return flatten(x);
    },
    Matrix: function Matrix(x) {
      var flat = flatten(x.toArray());
      // TODO: return the same matrix type as x (Dense or Sparse Matrix)
      return matrix(flat);
    }
  });
});

var name$3u = 'forEach';
var dependencies$3u = ['typed'];
var createForEach = /* #__PURE__ */factory(name$3u, dependencies$3u, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Iterate over all elements of a matrix/array, and executes the given callback function.
   *
   * Syntax:
   *
   *    math.forEach(x, callback)
   *
   * Examples:
   *
   *    math.forEach([1, 2, 3], function(value) {
   *      console.log(value)
   *    })
   *    // outputs 1, 2, 3
   *
   * See also:
   *
   *    filter, map, sort
   *
   * @param {Matrix | Array} x    The matrix to iterate on.
   * @param {Function} callback   The callback function is invoked with three
   *                              parameters: the value of the element, the index
   *                              of the element, and the Matrix/array being traversed.
   */
  return typed(name$3u, {
    'Array, function': _forEach,
    'Matrix, function': function MatrixFunction(x, callback) {
      x.forEach(callback);
    }
  });
});

/**
 * forEach for a multidimensional array
 * @param {Array} array
 * @param {Function} callback
 * @private
 */
function _forEach(array, callback) {
  var recurse = function recurse(value, index) {
    if (Array.isArray(value)) {
      forEach(value, function (child, i) {
        // we create a copy of the index array and append the new index value
        recurse(child, index.concat(i));
      });
    } else {
      // invoke the callback function with the right number of arguments
      return applyCallback(callback, value, index, array, 'forEach');
    }
  };
  recurse(array, []);
}

var name$3t = 'getMatrixDataType';
var dependencies$3t = ['typed'];
var createGetMatrixDataType = /* #__PURE__ */factory(name$3t, dependencies$3t, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Find the data type of all elements in a matrix or array,
   * for example 'number' if all items are a number and 'Complex' if all values
   * are complex numbers.
   * If a matrix contains more than one data type, it will return 'mixed'.
   *
   * Syntax:
   *
   *    math.getMatrixDataType(x)
   *
   * Examples:
   *
   *    const x = [ [1, 2, 3], [4, 5, 6] ]
   *    const mixedX = [ [1, true], [2, 3] ]
   *    const fractionX = [ [math.fraction(1, 3)], [math.fraction(1, 3)] ]
   *    const unitX = [ [math.unit('5cm')], [math.unit('5cm')] ]
   *    const bigNumberX = [ [math.bignumber(1)], [math.bignumber(0)] ]
   *    const sparse = math.sparse(x)
   *    const dense = math.matrix(x)
   *    math.getMatrixDataType(x)   // returns 'number'
   *    math.getMatrixDataType(sparse)   // returns 'number'
   *    math.getMatrixDataType(dense)   // returns 'number'
   *    math.getMatrixDataType(mixedX) // returns 'mixed'
   *    math.getMatrixDataType(fractionX) // returns 'Fraction'
   *    math.getMatrixDataType(unitX) // returns 'Unit'
   *    math.getMatrixDataType(bigNumberX) // return 'BigNumber'
   *
   * See also:
   *  SparseMatrix, DenseMatrix
   *
   * @param {...Matrix | Array} x   The Matrix with values.
   *
   * @return {string} A string representation of the matrix type
   */
  return typed(name$3t, {
    Array: function Array(x) {
      return getArrayDataType(x, typeOf);
    },
    Matrix: function Matrix(x) {
      return x.getDataType();
    }
  });
});

var name$3s = 'identity';
var dependencies$3s = ['typed', 'config', 'matrix', 'BigNumber', 'DenseMatrix', 'SparseMatrix'];
var createIdentity = /* #__PURE__ */factory(name$3s, dependencies$3s, _ref => {
  var {
    typed,
    config,
    matrix,
    BigNumber,
    DenseMatrix,
    SparseMatrix
  } = _ref;
  /**
   * Create a 2-dimensional identity matrix with size m x n or n x n.
   * The matrix has ones on the diagonal and zeros elsewhere.
   *
   * Syntax:
   *
   *    math.identity(n)
   *    math.identity(n, format)
   *    math.identity(m, n)
   *    math.identity(m, n, format)
   *    math.identity([m, n])
   *    math.identity([m, n], format)
   *
   * Examples:
   *
   *    math.identity(3)                    // returns [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
   *    math.identity(3, 2)                 // returns [[1, 0], [0, 1], [0, 0]]
   *
   *    const A = [[1, 2, 3], [4, 5, 6]]
   *    math.identity(math.size(A))         // returns [[1, 0, 0], [0, 1, 0]]
   *
   * See also:
   *
   *    diag, ones, zeros, size, range
   *
   * @param {...number | Matrix | Array} size   The size for the matrix
   * @param {string} [format]                   The Matrix storage format
   *
   * @return {Matrix | Array | number} A matrix with ones on the diagonal.
   */
  return typed(name$3s, {
    '': function _() {
      return config.matrix === 'Matrix' ? matrix([]) : [];
    },
    string: function string(format) {
      return matrix(format);
    },
    'number | BigNumber': function numberBigNumber(rows) {
      return _identity(rows, rows, config.matrix === 'Matrix' ? 'dense' : undefined);
    },
    'number | BigNumber, string': function numberBigNumberString(rows, format) {
      return _identity(rows, rows, format);
    },
    'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(rows, cols) {
      return _identity(rows, cols, config.matrix === 'Matrix' ? 'dense' : undefined);
    },
    'number | BigNumber, number | BigNumber, string': function numberBigNumberNumberBigNumberString(rows, cols, format) {
      return _identity(rows, cols, format);
    },
    Array: function Array(size) {
      return _identityVector(size);
    },
    'Array, string': function ArrayString(size, format) {
      return _identityVector(size, format);
    },
    Matrix: function Matrix(size) {
      return _identityVector(size.valueOf(), size.storage());
    },
    'Matrix, string': function MatrixString(size, format) {
      return _identityVector(size.valueOf(), format);
    }
  });
  function _identityVector(size, format) {
    switch (size.length) {
      case 0:
        return format ? matrix(format) : [];
      case 1:
        return _identity(size[0], size[0], format);
      case 2:
        return _identity(size[0], size[1], format);
      default:
        throw new Error('Vector containing two values expected');
    }
  }

  /**
   * Create an identity matrix
   * @param {number | BigNumber} rows
   * @param {number | BigNumber} cols
   * @param {string} [format]
   * @returns {Matrix}
   * @private
   */
  function _identity(rows, cols, format) {
    // BigNumber constructor with the right precision
    var Big = isBigNumber(rows) || isBigNumber(cols) ? BigNumber : null;
    if (isBigNumber(rows)) rows = rows.toNumber();
    if (isBigNumber(cols)) cols = cols.toNumber();
    if (!isInteger(rows) || rows < 1) {
      throw new Error('Parameters in function identity must be positive integers');
    }
    if (!isInteger(cols) || cols < 1) {
      throw new Error('Parameters in function identity must be positive integers');
    }
    var one = Big ? new BigNumber(1) : 1;
    var defaultValue = Big ? new Big(0) : 0;
    var size = [rows, cols];

    // check we need to return a matrix
    if (format) {
      // create diagonal matrix (use optimized implementation for storage format)
      if (format === 'sparse') {
        return SparseMatrix.diagonal(size, one, 0, defaultValue);
      }
      if (format === 'dense') {
        return DenseMatrix.diagonal(size, one, 0, defaultValue);
      }
      throw new TypeError("Unknown matrix type \"".concat(format, "\""));
    }

    // create and resize array
    var res = resize([], size, defaultValue);
    // fill in ones on the diagonal
    var minimum = rows < cols ? rows : cols;
    // fill diagonal
    for (var d = 0; d < minimum; d++) {
      res[d][d] = one;
    }
    return res;
  }
});

var name$3r = 'kron';
var dependencies$3r = ['typed', 'matrix', 'multiplyScalar'];
var createKron = /* #__PURE__ */factory(name$3r, dependencies$3r, _ref => {
  var {
    typed,
    matrix,
    multiplyScalar
  } = _ref;
  /**
     * Calculates the kronecker product of 2 matrices or vectors.
     *
     * NOTE: If a one dimensional vector / matrix is given, it will be
     * wrapped so its two dimensions.
     * See the examples.
     *
     * Syntax:
     *
     *    math.kron(x, y)
     *
     * Examples:
     *
     *    math.kron([[1, 0], [0, 1]], [[1, 2], [3, 4]])
     *    // returns [ [ 1, 2, 0, 0 ], [ 3, 4, 0, 0 ], [ 0, 0, 1, 2 ], [ 0, 0, 3, 4 ] ]
     *
     *    math.kron([1,1], [2,3,4])
     *    // returns [ [ 2, 3, 4, 2, 3, 4 ] ]
     *
     * See also:
     *
     *    multiply, dot, cross
     *
     * @param  {Array | Matrix} x     First vector
     * @param  {Array | Matrix} y     Second vector
     * @return {Array | Matrix}       Returns the kronecker product of `x` and `y`
     */
  return typed(name$3r, {
    'Matrix, Matrix': function MatrixMatrix(x, y) {
      return matrix(_kron(x.toArray(), y.toArray()));
    },
    'Matrix, Array': function MatrixArray(x, y) {
      return matrix(_kron(x.toArray(), y));
    },
    'Array, Matrix': function ArrayMatrix(x, y) {
      return matrix(_kron(x, y.toArray()));
    },
    'Array, Array': _kron
  });

  /**
     * Calculate the kronecker product of two matrices / vectors
     * @param {Array} a  First vector
     * @param {Array} b  Second vector
     * @returns {Array} Returns the kronecker product of x and y
     * @private
     */
  function _kron(a, b) {
    // Deal with the dimensions of the matricies.
    if (arraySize(a).length === 1) {
      // Wrap it in a 2D Matrix
      a = [a];
    }
    if (arraySize(b).length === 1) {
      // Wrap it in a 2D Matrix
      b = [b];
    }
    if (arraySize(a).length > 2 || arraySize(b).length > 2) {
      throw new RangeError('Vectors with dimensions greater then 2 are not supported expected ' + '(Size x = ' + JSON.stringify(a.length) + ', y = ' + JSON.stringify(b.length) + ')');
    }
    var t = [];
    var r = [];
    return a.map(function (a) {
      return b.map(function (b) {
        r = [];
        t.push(r);
        return a.map(function (y) {
          return b.map(function (x) {
            return r.push(multiplyScalar(y, x));
          });
        });
      });
    }) && t;
  }
});

var name$3q = 'map';
var dependencies$3q = ['typed'];
var createMap = /* #__PURE__ */factory(name$3q, dependencies$3q, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Create a new matrix or array with the results of a callback function executed on
   * each entry of a given matrix/array.
   *
   * For each entry of the input, the callback is invoked with three arguments:
   * the value of the entry, the index at which that entry occurs, and the full
   * matrix/array being traversed. Note that because the matrix/array might be
   * multidimensional, the "index" argument is always an array of numbers giving
   * the index in each dimension. This is true even for vectors: the "index"
   * argument is an array of length 1, rather than simply a number.
   *
   * Syntax:
   *
   *    math.map(x, callback)
   *
   * Examples:
   *
   *    math.map([1, 2, 3], function(value) {
   *      return value * value
   *    })  // returns [1, 4, 9]
   *
   *    // The callback is normally called with three arguments:
   *    //    callback(value, index, Array)
   *    // If you want to call with only one argument, use:
   *    math.map([1, 2, 3], x => math.format(x)) // returns ['1', '2', '3']
   *
   * See also:
   *
   *    filter, forEach, sort
   *
   * @param {Matrix | Array} x    The input to iterate on.
   * @param {Function} callback
   *     The function to call (as described above) on each entry of the input
   * @return {Matrix | array}
   *     Transformed map of x; always has the same type and shape as x
   */
  return typed(name$3q, {
    'Array, function': _map$1,
    'Matrix, function': function MatrixFunction(x, callback) {
      return x.map(callback);
    }
  });
});

/**
 * Map for a multi dimensional array
 * @param {Array} array
 * @param {Function} callback
 * @return {Array}
 * @private
 */
function _map$1(array, callback) {
  var recurse = function recurse(value, index) {
    if (Array.isArray(value)) {
      return value.map(function (child, i) {
        // we create a copy of the index array and append the new index value
        return recurse(child, index.concat(i));
      });
    } else {
      // invoke the callback function with the right number of arguments
      return applyCallback(callback, value, index, array, 'map');
    }
  };
  return recurse(array, []);
}

var name$3p = 'diff';
var dependencies$3p = ['typed', 'matrix', 'subtract', 'number'];
var createDiff = /* #__PURE__ */factory(name$3p, dependencies$3p, _ref => {
  var {
    typed,
    matrix,
    subtract,
    number
  } = _ref;
  /**
   * Create a new matrix or array of the difference between elements of the given array
   * The optional dim parameter lets you specify the dimension to evaluate the difference of
   * If no dimension parameter is passed it is assumed as dimension 0
   *
   * Dimension is zero-based in javascript and one-based in the parser and can be a number or bignumber
   * Arrays must be 'rectangular' meaning arrays like [1, 2]
   * If something is passed as a matrix it will be returned as a matrix but other than that all matrices are converted to arrays
   *
   * Syntax:
   *
   *     math.diff(arr)
   *     math.diff(arr, dim)
   *
   * Examples:
   *
   *     const arr = [1, 2, 4, 7, 0]
   *     math.diff(arr) // returns [1, 2, 3, -7] (no dimension passed so 0 is assumed)
   *     math.diff(math.matrix(arr)) // returns Matrix [1, 2, 3, -7]
   *
   *     const arr = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [9, 8, 7, 6, 4]]
   *     math.diff(arr) // returns [[0, 0, 0, 0, 0], [8, 6, 4, 2, -1]]
   *     math.diff(arr, 0) // returns [[0, 0, 0, 0, 0], [8, 6, 4, 2, -1]]
   *     math.diff(arr, 1) // returns [[1, 1, 1, 1], [1, 1, 1, 1], [-1, -1, -1, -2]]
   *     math.diff(arr, math.bignumber(1)) // returns [[1, 1, 1, 1], [1, 1, 1, 1], [-1, -1, -1, -2]]
   *
   *     math.diff(arr, 2) // throws RangeError as arr is 2 dimensional not 3
   *     math.diff(arr, -1) // throws RangeError as negative dimensions are not allowed
   *
   *     // These will all produce the same result
   *     math.diff([[1, 2], [3, 4]])
   *     math.diff([math.matrix([1, 2]), math.matrix([3, 4])])
   *     math.diff([[1, 2], math.matrix([3, 4])])
   *     math.diff([math.matrix([1, 2]), [3, 4]])
   *     // They do not produce the same result as  math.diff(math.matrix([[1, 2], [3, 4]])) as this returns a matrix
   *
   * See Also:
   *
   *      sum
   *      subtract
   *      partitionSelect
   *
   * @param {Array | Matrix} arr      An array or matrix
   * @param {number | BigNumber} dim  Dimension
   * @return {Array | Matrix}         Difference between array elements in given dimension
   */
  return typed(name$3p, {
    'Array | Matrix': function ArrayMatrix(arr) {
      // No dimension specified => assume dimension 0
      if (isMatrix(arr)) {
        return matrix(_diff(arr.toArray()));
      } else {
        return _diff(arr);
      }
    },
    'Array | Matrix, number': function ArrayMatrixNumber(arr, dim) {
      if (!isInteger(dim)) throw new RangeError('Dimension must be a whole number');
      if (isMatrix(arr)) {
        return matrix(_recursive(arr.toArray(), dim));
      } else {
        return _recursive(arr, dim);
      }
    },
    'Array, BigNumber': typed.referTo('Array,number', selfAn => (arr, dim) => selfAn(arr, number(dim))),
    'Matrix, BigNumber': typed.referTo('Matrix,number', selfMn => (arr, dim) => selfMn(arr, number(dim)))
  });

  /**
   * Recursively find the correct dimension in the array/matrix
   * Then Apply _diff to that dimension
   *
   * @param {Array} arr      The array
   * @param {number} dim     Dimension
   * @return {Array}         resulting array
   */
  function _recursive(arr, dim) {
    if (isMatrix(arr)) {
      arr = arr.toArray(); // Makes sure arrays like [ matrix([0, 1]), matrix([1, 0]) ] are processed properly
    }
    if (!Array.isArray(arr)) {
      throw RangeError('Array/Matrix does not have that many dimensions');
    }
    if (dim > 0) {
      var result = [];
      arr.forEach(element => {
        result.push(_recursive(element, dim - 1));
      });
      return result;
    } else if (dim === 0) {
      return _diff(arr);
    } else {
      throw RangeError('Cannot have negative dimension');
    }
  }

  /**
   * Difference between elements in the array
   *
   * @param {Array} arr      An array
   * @return {Array}         resulting array
   */
  function _diff(arr) {
    var result = [];
    var size = arr.length;
    for (var i = 1; i < size; i++) {
      result.push(_ElementDiff(arr[i - 1], arr[i]));
    }
    return result;
  }

  /**
   * Difference between 2 objects
   *
   * @param {Object} obj1    First object
   * @param {Object} obj2    Second object
   * @return {Array}         resulting array
   */
  function _ElementDiff(obj1, obj2) {
    // Convert matrices to arrays
    if (isMatrix(obj1)) obj1 = obj1.toArray();
    if (isMatrix(obj2)) obj2 = obj2.toArray();
    var obj1IsArray = Array.isArray(obj1);
    var obj2IsArray = Array.isArray(obj2);
    if (obj1IsArray && obj2IsArray) {
      return _ArrayDiff(obj1, obj2);
    }
    if (!obj1IsArray && !obj2IsArray) {
      return subtract(obj2, obj1); // Difference is (second - first) NOT (first - second)
    }
    throw TypeError('Cannot calculate difference between 1 array and 1 non-array');
  }

  /**
   * Difference of elements in 2 arrays
   *
   * @param {Array} arr1     Array 1
   * @param {Array} arr2     Array 2
   * @return {Array}         resulting array
   */
  function _ArrayDiff(arr1, arr2) {
    if (arr1.length !== arr2.length) {
      throw RangeError('Not all sub-arrays have the same length');
    }
    var result = [];
    var size = arr1.length;
    for (var i = 0; i < size; i++) {
      result.push(_ElementDiff(arr1[i], arr2[i]));
    }
    return result;
  }
});

var name$3o = 'ones';
var dependencies$3o = ['typed', 'config', 'matrix', 'BigNumber'];
var createOnes = /* #__PURE__ */factory(name$3o, dependencies$3o, _ref => {
  var {
    typed,
    config,
    matrix,
    BigNumber
  } = _ref;
  /**
   * Create a matrix filled with ones. The created matrix can have one or
   * multiple dimensions.
   *
   * Syntax:
   *
   *    math.ones(m)
   *    math.ones(m, format)
   *    math.ones(m, n)
   *    math.ones(m, n, format)
   *    math.ones([m, n])
   *    math.ones([m, n], format)
   *    math.ones([m, n, p, ...])
   *    math.ones([m, n, p, ...], format)
   *
   * Examples:
   *
   *    math.ones()                    // returns []
   *    math.ones(3)                   // returns [1, 1, 1]
   *    math.ones(3, 2)                // returns [[1, 1], [1, 1], [1, 1]]
   *    math.ones(3, 2, 'dense')       // returns Dense Matrix [[1, 1], [1, 1], [1, 1]]
   *
   *    const A = [[1, 2, 3], [4, 5, 6]]
   *    math.ones(math.size(A))       // returns [[1, 1, 1], [1, 1, 1]]
   *
   * See also:
   *
   *    zeros, identity, size, range
   *
   * @param {...(number|BigNumber) | Array} size    The size of each dimension of the matrix
   * @param {string} [format]           The Matrix storage format
   *
   * @return {Array | Matrix | number}  A matrix filled with ones
   */
  return typed('ones', {
    '': function _() {
      return config.matrix === 'Array' ? _ones([]) : _ones([], 'default');
    },
    // math.ones(m, n, p, ..., format)
    // TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this
    '...number | BigNumber | string': function numberBigNumberString(size) {
      var last = size[size.length - 1];
      if (typeof last === 'string') {
        var format = size.pop();
        return _ones(size, format);
      } else if (config.matrix === 'Array') {
        return _ones(size);
      } else {
        return _ones(size, 'default');
      }
    },
    Array: _ones,
    Matrix: function Matrix(size) {
      var format = size.storage();
      return _ones(size.valueOf(), format);
    },
    'Array | Matrix, string': function ArrayMatrixString(size, format) {
      return _ones(size.valueOf(), format);
    }
  });

  /**
   * Create an Array or Matrix with ones
   * @param {Array} size
   * @param {string} [format='default']
   * @return {Array | Matrix}
   * @private
   */
  function _ones(size, format) {
    var hasBigNumbers = _normalize(size);
    var defaultValue = hasBigNumbers ? new BigNumber(1) : 1;
    _validate(size);
    if (format) {
      // return a matrix
      var m = matrix(format);
      if (size.length > 0) {
        return m.resize(size, defaultValue);
      }
      return m;
    } else {
      // return an Array
      var arr = [];
      if (size.length > 0) {
        return resize(arr, size, defaultValue);
      }
      return arr;
    }
  }

  // replace BigNumbers with numbers, returns true if size contained BigNumbers
  function _normalize(size) {
    var hasBigNumbers = false;
    size.forEach(function (value, index, arr) {
      if (isBigNumber(value)) {
        hasBigNumbers = true;
        arr[index] = value.toNumber();
      }
    });
    return hasBigNumbers;
  }

  // validate arguments
  function _validate(size) {
    size.forEach(function (value) {
      if (typeof value !== 'number' || !isInteger(value) || value < 0) {
        throw new Error('Parameters in function ones must be positive integers');
      }
    });
  }
});

function noBignumber() {
  throw new Error('No "bignumber" implementation available');
}
function noFraction() {
  throw new Error('No "fraction" implementation available');
}
function noMatrix() {
  throw new Error('No "matrix" implementation available');
}

var name$3n = 'range';
var dependencies$3n = ['typed', 'config', '?matrix', '?bignumber', 'smaller', 'smallerEq', 'larger', 'largerEq', 'add', 'isPositive'];
var createRange = /* #__PURE__ */factory(name$3n, dependencies$3n, _ref => {
  var {
    typed,
    config,
    matrix,
    bignumber,
    smaller,
    smallerEq,
    larger,
    largerEq,
    add,
    isPositive
  } = _ref;
  /**
   * Create an array from a range.
   * By default, the range end is excluded. This can be customized by providing
   * an extra parameter `includeEnd`.
   *
   * Syntax:
   *
   *     math.range(str [, includeEnd])               // Create a range from a string,
   *                                                  // where the string contains the
   *                                                  // start, optional step, and end,
   *                                                  // separated by a colon.
   *     math.range(start, end [, includeEnd])        // Create a range with start and
   *                                                  // end and a step size of 1.
   *     math.range(start, end, step [, includeEnd])  // Create a range with start, step,
   *                                                  // and end.
   *
   * Where:
   *
   * - `str: string`
   *   A string 'start:end' or 'start:step:end'
   * - `start: {number | BigNumber | Unit}`
   *   Start of the range
   * - `end: number | BigNumber | Unit`
   *   End of the range, excluded by default, included when parameter includeEnd=true
   * - `step: number | BigNumber | Unit`
   *   Step size. Default value is 1.
   * - `includeEnd: boolean`
   *   Option to specify whether to include the end or not. False by default.
   *
   * Examples:
   *
   *     math.range(2, 6)        // [2, 3, 4, 5]
   *     math.range(2, -3, -1)   // [2, 1, 0, -1, -2]
   *     math.range('2:1:6')     // [2, 3, 4, 5]
   *     math.range(2, 6, true)  // [2, 3, 4, 5, 6]
   *     math.range(math.unit(2, 'm'), math.unit(-3, 'm'), math.unit(-1, 'm')) // [2 m, 1 m, 0 m , -1 m, -2 m]
   *
   * See also:
   *
   *     ones, zeros, size, subset
   *
   * @param {*} args   Parameters describing the ranges `start`, `end`, and optional `step`.
   * @return {Array | Matrix} range
   */
  return typed(name$3n, {
    // TODO: simplify signatures when typed-function supports default values and optional arguments

    // TODO: a number or boolean should not be converted to string here
    string: _strRange,
    'string, boolean': _strRange,
    'number, number': function numberNumber(start, end) {
      return _out(_range(start, end, 1, false));
    },
    'number, number, number': function numberNumberNumber(start, end, step) {
      return _out(_range(start, end, step, false));
    },
    'number, number, boolean': function numberNumberBoolean(start, end, includeEnd) {
      return _out(_range(start, end, 1, includeEnd));
    },
    'number, number, number, boolean': function numberNumberNumberBoolean(start, end, step, includeEnd) {
      return _out(_range(start, end, step, includeEnd));
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(start, end) {
      var BigNumber = start.constructor;
      return _out(_range(start, end, new BigNumber(1), false));
    },
    'BigNumber, BigNumber, BigNumber': function BigNumberBigNumberBigNumber(start, end, step) {
      return _out(_range(start, end, step, false));
    },
    'BigNumber, BigNumber, boolean': function BigNumberBigNumberBoolean(start, end, includeEnd) {
      var BigNumber = start.constructor;
      return _out(_range(start, end, new BigNumber(1), includeEnd));
    },
    'BigNumber, BigNumber, BigNumber, boolean': function BigNumberBigNumberBigNumberBoolean(start, end, step, includeEnd) {
      return _out(_range(start, end, step, includeEnd));
    },
    'Unit, Unit, Unit': function UnitUnitUnit(start, end, step) {
      return _out(_range(start, end, step, false));
    },
    'Unit, Unit, Unit, boolean': function UnitUnitUnitBoolean(start, end, step, includeEnd) {
      return _out(_range(start, end, step, includeEnd));
    }
  });
  function _out(arr) {
    if (config.matrix === 'Matrix') {
      return matrix ? matrix(arr) : noMatrix();
    }
    return arr;
  }
  function _strRange(str, includeEnd) {
    var r = _parse(str);
    if (!r) {
      throw new SyntaxError('String "' + str + '" is no valid range');
    }
    if (config.number === 'BigNumber') {
      if (bignumber === undefined) {
        noBignumber();
      }
      return _out(_range(bignumber(r.start), bignumber(r.end), bignumber(r.step)));
    } else {
      return _out(_range(r.start, r.end, r.step, includeEnd));
    }
  }

  /**
   * Create a range with numbers or BigNumbers
   * @param {number | BigNumber | Unit} start
   * @param {number | BigNumber | Unit} end
   * @param {number | BigNumber | Unit} step
   * @param {boolean} includeEnd
   * @returns {Array} range
   * @private
   */
  function _range(start, end, step, includeEnd) {
    var array = [];
    var ongoing = isPositive(step) ? includeEnd ? smallerEq : smaller : includeEnd ? largerEq : larger;
    var x = start;
    while (ongoing(x, end)) {
      array.push(x);
      x = add(x, step);
    }
    return array;
  }

  /**
   * Parse a string into a range,
   * The string contains the start, optional step, and end, separated by a colon.
   * If the string does not contain a valid range, null is returned.
   * For example str='0:2:11'.
   * @param {string} str
   * @return {{start: number, end: number, step: number} | null} range Object containing properties start, end, step
   * @private
   */
  function _parse(str) {
    var args = str.split(':');

    // number
    var nums = args.map(function (arg) {
      // use Number and not parseFloat as Number returns NaN on invalid garbage in the string
      return Number(arg);
    });
    var invalid = nums.some(function (num) {
      return isNaN(num);
    });
    if (invalid) {
      return null;
    }
    switch (nums.length) {
      case 2:
        return {
          start: nums[0],
          end: nums[1],
          step: 1
        };
      case 3:
        return {
          start: nums[0],
          end: nums[2],
          step: nums[1]
        };
      default:
        return null;
    }
  }
});

var name$3m = 'reshape';
var dependencies$3m = ['typed', 'isInteger', 'matrix'];
var createReshape = /* #__PURE__ */factory(name$3m, dependencies$3m, _ref => {
  var {
    typed,
    isInteger
  } = _ref;
  /**
   * Reshape a multi dimensional array to fit the specified dimensions
   *
   * Syntax:
   *
   *     math.reshape(x, sizes)
   *
   * Examples:
   *
   *     math.reshape([1, 2, 3, 4, 5, 6], [2, 3])
   *     // returns Array  [[1, 2, 3], [4, 5, 6]]
   *
   *     math.reshape([[1, 2], [3, 4]], [1, 4])
   *     // returns Array  [[1, 2, 3, 4]]
   *
   *     math.reshape([[1, 2], [3, 4]], [4])
   *     // returns Array [1, 2, 3, 4]
   *
   *     const x = math.matrix([1, 2, 3, 4, 5, 6, 7, 8])
   *     math.reshape(x, [2, 2, 2])
   *     // returns Matrix [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
   *
   *    math.reshape([1, 2, 3, 4], [-1, 2])
   *    // returns Matrix [[1, 2], [3, 4]]
   *
   * See also:
   *
   *     size, squeeze, resize
   *
   * @param {Array | Matrix | *} x  Matrix to be reshaped
   * @param {number[]} sizes        One dimensional array with integral sizes for
   *                                each dimension. One -1 is allowed as wildcard,
   *                                which calculates this dimension automatically.
   *
   * @return {* | Array | Matrix}   A reshaped clone of matrix `x`
   *
   * @throws {TypeError}            If `sizes` does not contain solely integers
   * @throws {DimensionError}       If the product of the new dimension sizes does
   *                                not equal that of the old ones
   */
  return typed(name$3m, {
    'Matrix, Array': function MatrixArray(x, sizes) {
      return x.reshape(sizes, true);
    },
    'Array, Array': function ArrayArray(x, sizes) {
      sizes.forEach(function (size) {
        if (!isInteger(size)) {
          throw new TypeError('Invalid size for dimension: ' + size);
        }
      });
      return reshape(x, sizes);
    }
  });
});

var name$3l = 'resize';
var dependencies$3l = ['config', 'matrix'];
var createResize = /* #__PURE__ */factory(name$3l, dependencies$3l, _ref => {
  var {
    config,
    matrix
  } = _ref;
  /**
   * Resize a matrix
   *
   * Syntax:
   *
   *     math.resize(x, size)
   *     math.resize(x, size, defaultValue)
   *
   * Examples:
   *
   *     math.resize([1, 2, 3, 4, 5], [3]) // returns Array  [1, 2, 3]
   *     math.resize([1, 2, 3], [5], 0)    // returns Array  [1, 2, 3, 0, 0]
   *     math.resize(2, [2, 3], 0)         // returns Matrix [[2, 0, 0], [0, 0, 0]]
   *     math.resize("hello", [8], "!")    // returns string 'hello!!!'
   *
   * See also:
   *
   *     size, squeeze, subset, reshape
   *
   * @param {Array | Matrix | *} x             Matrix to be resized
   * @param {Array | Matrix} size              One dimensional array with numbers
   * @param {number | string} [defaultValue=0] Zero by default, except in
   *                                           case of a string, in that case
   *                                           defaultValue = ' '
   * @return {* | Array | Matrix} A resized clone of matrix `x`
   */
  // TODO: rework resize to a typed-function
  return function resize$1(x, size, defaultValue) {
    if (arguments.length !== 2 && arguments.length !== 3) {
      throw new ArgumentsError('resize', arguments.length, 2, 3);
    }
    if (isMatrix(size)) {
      size = size.valueOf(); // get Array
    }
    if (isBigNumber(size[0])) {
      // convert bignumbers to numbers
      size = size.map(function (value) {
        return !isBigNumber(value) ? value : value.toNumber();
      });
    }

    // check x is a Matrix
    if (isMatrix(x)) {
      // use optimized matrix implementation, return copy
      return x.resize(size, defaultValue, true);
    }
    if (typeof x === 'string') {
      // resize string
      return _resizeString(x, size, defaultValue);
    }

    // check result should be a matrix
    var asMatrix = Array.isArray(x) ? false : config.matrix !== 'Array';
    if (size.length === 0) {
      // output a scalar
      while (Array.isArray(x)) {
        x = x[0];
      }
      return clone$2(x);
    } else {
      // output an array/matrix
      if (!Array.isArray(x)) {
        x = [x];
      }
      x = clone$2(x);
      var res = resize(x, size, defaultValue);
      return asMatrix ? matrix(res) : res;
    }
  };

  /**
   * Resize a string
   * @param {string} str
   * @param {number[]} size
   * @param {string} [defaultChar=' ']
   * @private
   */
  function _resizeString(str, size, defaultChar) {
    if (defaultChar !== undefined) {
      if (typeof defaultChar !== 'string' || defaultChar.length !== 1) {
        throw new TypeError('Single character expected as defaultValue');
      }
    } else {
      defaultChar = ' ';
    }
    if (size.length !== 1) {
      throw new DimensionError(size.length, 1);
    }
    var len = size[0];
    if (typeof len !== 'number' || !isInteger(len)) {
      throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + format(size) + ')');
    }
    if (str.length > len) {
      return str.substring(0, len);
    } else if (str.length < len) {
      var res = str;
      for (var i = 0, ii = len - str.length; i < ii; i++) {
        res += defaultChar;
      }
      return res;
    } else {
      return str;
    }
  }
});

var name$3k = 'rotate';
var dependencies$3k = ['typed', 'multiply', 'rotationMatrix'];
var createRotate = /* #__PURE__ */factory(name$3k, dependencies$3k, _ref => {
  var {
    typed,
    multiply,
    rotationMatrix
  } = _ref;
  /**
     * Rotate a vector of size 1x2 counter-clockwise by a given angle
     * Rotate a vector of size 1x3 counter-clockwise by a given angle around the given axis
     *
     * Syntax:
     *
     *    math.rotate(w, theta)
     *    math.rotate(w, theta, v)
     *
     * Examples:
     *
     *    math.rotate([11, 12], math.pi / 2)                           // returns [-12, 11]
     *    math.rotate(matrix([11, 12]), math.pi / 2)                   // returns [-12, 11]
     *
     *    math.rotate([1, 0, 0], unit('90deg'), [0, 0, 1])             // returns [0, 1, 0]
     *    math.rotate(matrix([1, 0, 0]), unit('90deg'), [0, 0, 1])     // returns Matrix [0, 1, 0]
     *
     *    math.rotate([1, 0], math.complex(1 + i))                     // returns [cos(1 + i) - sin(1 + i), sin(1 + i) + cos(1 + i)]
     *
     * See also:
     *
     *    matrix, rotationMatrix
     *
     * @param {Array | Matrix} w                             Vector to rotate
     * @param {number | BigNumber | Complex | Unit} theta    Rotation angle
     * @param {Array | Matrix} [v]                           Rotation axis
     * @return {Array | Matrix}                              Multiplication of the rotation matrix and w
     */
  return typed(name$3k, {
    'Array , number | BigNumber | Complex | Unit': function ArrayNumberBigNumberComplexUnit(w, theta) {
      _validateSize(w, 2);
      var matrixRes = multiply(rotationMatrix(theta), w);
      return matrixRes.toArray();
    },
    'Matrix , number | BigNumber | Complex | Unit': function MatrixNumberBigNumberComplexUnit(w, theta) {
      _validateSize(w, 2);
      return multiply(rotationMatrix(theta), w);
    },
    'Array, number | BigNumber | Complex | Unit, Array | Matrix': function ArrayNumberBigNumberComplexUnitArrayMatrix(w, theta, v) {
      _validateSize(w, 3);
      var matrixRes = multiply(rotationMatrix(theta, v), w);
      return matrixRes;
    },
    'Matrix, number | BigNumber | Complex | Unit, Array | Matrix': function MatrixNumberBigNumberComplexUnitArrayMatrix(w, theta, v) {
      _validateSize(w, 3);
      return multiply(rotationMatrix(theta, v), w);
    }
  });
  function _validateSize(v, expectedSize) {
    var actualSize = Array.isArray(v) ? arraySize(v) : v.size();
    if (actualSize.length > 2) {
      throw new RangeError("Vector must be of dimensions 1x".concat(expectedSize));
    }
    if (actualSize.length === 2 && actualSize[1] !== 1) {
      throw new RangeError("Vector must be of dimensions 1x".concat(expectedSize));
    }
    if (actualSize[0] !== expectedSize) {
      throw new RangeError("Vector must be of dimensions 1x".concat(expectedSize));
    }
  }
});

var name$3j = 'rotationMatrix';
var dependencies$3j = ['typed', 'config', 'multiplyScalar', 'addScalar', 'unaryMinus', 'norm', 'matrix', 'BigNumber', 'DenseMatrix', 'SparseMatrix', 'cos', 'sin'];
var createRotationMatrix = /* #__PURE__ */factory(name$3j, dependencies$3j, _ref => {
  var {
    typed,
    config,
    multiplyScalar,
    addScalar,
    unaryMinus,
    norm,
    BigNumber,
    matrix,
    DenseMatrix,
    SparseMatrix,
    cos,
    sin
  } = _ref;
  /**
   * Create a 2-dimensional counter-clockwise rotation matrix (2x2) for a given angle (expressed in radians).
   * Create a 2-dimensional counter-clockwise rotation matrix (3x3) by a given angle (expressed in radians) around a given axis (1x3).
   *
   * Syntax:
   *
   *    math.rotationMatrix(theta)
   *    math.rotationMatrix(theta, format)
   *    math.rotationMatrix(theta, [v])
   *    math.rotationMatrix(theta, [v], format)
   *
   * Examples:
   *
   *    math.rotationMatrix(math.pi / 2)                      // returns [[0, -1], [1, 0]]
   *    math.rotationMatrix(math.bignumber(1))                // returns [[bignumber(cos(1)), bignumber(-sin(1))], [bignumber(sin(1)), bignumber(cos(1))]]
   *    math.rotationMatrix(math.complex(1 + i))              // returns [[cos(1 + i), -sin(1 + i)], [sin(1 + i), cos(1 + i)]]
   *    math.rotationMatrix(math.unit('1rad'))                // returns [[cos(1), -sin(1)], [sin(1), cos(1)]]
   *
   *    math.rotationMatrix(math.pi / 2, [0, 1, 0])           // returns [[0, 0, 1], [0, 1, 0], [-1, 0, 0]]
   *    math.rotationMatrix(math.pi / 2, matrix([0, 1, 0]))   // returns matrix([[0, 0, 1], [0, 1, 0], [-1, 0, 0]])
   *
   *
   * See also:
   *
   *    matrix, cos, sin
   *
   *
   * @param {number | BigNumber | Complex | Unit} theta    Rotation angle
   * @param {Array | Matrix} [v]                           Rotation axis
   * @param {string} [format]                              Result Matrix storage format
   * @return {Array | Matrix}                              Rotation matrix
   */

  return typed(name$3j, {
    '': function _() {
      return config.matrix === 'Matrix' ? matrix([]) : [];
    },
    string: function string(format) {
      return matrix(format);
    },
    'number | BigNumber | Complex | Unit': function numberBigNumberComplexUnit(theta) {
      return _rotationMatrix2x2(theta, config.matrix === 'Matrix' ? 'dense' : undefined);
    },
    'number | BigNumber | Complex | Unit, string': function numberBigNumberComplexUnitString(theta, format) {
      return _rotationMatrix2x2(theta, format);
    },
    'number | BigNumber | Complex | Unit, Array': function numberBigNumberComplexUnitArray(theta, v) {
      var matrixV = matrix(v);
      _validateVector(matrixV);
      return _rotationMatrix3x3(theta, matrixV, undefined);
    },
    'number | BigNumber | Complex | Unit, Matrix': function numberBigNumberComplexUnitMatrix(theta, v) {
      _validateVector(v);
      var storageType = v.storage() || (config.matrix === 'Matrix' ? 'dense' : undefined);
      return _rotationMatrix3x3(theta, v, storageType);
    },
    'number | BigNumber | Complex | Unit, Array, string': function numberBigNumberComplexUnitArrayString(theta, v, format) {
      var matrixV = matrix(v);
      _validateVector(matrixV);
      return _rotationMatrix3x3(theta, matrixV, format);
    },
    'number | BigNumber | Complex | Unit, Matrix, string': function numberBigNumberComplexUnitMatrixString(theta, v, format) {
      _validateVector(v);
      return _rotationMatrix3x3(theta, v, format);
    }
  });

  /**
   * Returns 2x2 matrix of 2D rotation of angle theta
   *
   * @param {number | BigNumber | Complex | Unit} theta  The rotation angle
   * @param {string} format                              The result Matrix storage format
   * @returns {Matrix}
   * @private
   */
  function _rotationMatrix2x2(theta, format) {
    var Big = isBigNumber(theta);
    var minusOne = Big ? new BigNumber(-1) : -1;
    var cosTheta = cos(theta);
    var sinTheta = sin(theta);
    var data = [[cosTheta, multiplyScalar(minusOne, sinTheta)], [sinTheta, cosTheta]];
    return _convertToFormat(data, format);
  }
  function _validateVector(v) {
    var size = v.size();
    if (size.length < 1 || size[0] !== 3) {
      throw new RangeError('Vector must be of dimensions 1x3');
    }
  }
  function _mul(array) {
    return array.reduce((p, curr) => multiplyScalar(p, curr));
  }
  function _convertToFormat(data, format) {
    if (format) {
      if (format === 'sparse') {
        return new SparseMatrix(data);
      }
      if (format === 'dense') {
        return new DenseMatrix(data);
      }
      throw new TypeError("Unknown matrix type \"".concat(format, "\""));
    }
    return data;
  }

  /**
   * Returns a 3x3 matrix of rotation of angle theta around vector v
   *
   * @param {number | BigNumber | Complex | Unit} theta The rotation angle
   * @param {Matrix} v                                  The rotation axis vector
   * @param {string} format                             The storage format of the resulting matrix
   * @returns {Matrix}
   * @private
   */
  function _rotationMatrix3x3(theta, v, format) {
    var normV = norm(v);
    if (normV === 0) {
      throw new RangeError('Rotation around zero vector');
    }
    var Big = isBigNumber(theta) ? BigNumber : null;
    var one = Big ? new Big(1) : 1;
    var minusOne = Big ? new Big(-1) : -1;
    var vx = Big ? new Big(v.get([0]) / normV) : v.get([0]) / normV;
    var vy = Big ? new Big(v.get([1]) / normV) : v.get([1]) / normV;
    var vz = Big ? new Big(v.get([2]) / normV) : v.get([2]) / normV;
    var c = cos(theta);
    var oneMinusC = addScalar(one, unaryMinus(c));
    var s = sin(theta);
    var r11 = addScalar(c, _mul([vx, vx, oneMinusC]));
    var r12 = addScalar(_mul([vx, vy, oneMinusC]), _mul([minusOne, vz, s]));
    var r13 = addScalar(_mul([vx, vz, oneMinusC]), _mul([vy, s]));
    var r21 = addScalar(_mul([vx, vy, oneMinusC]), _mul([vz, s]));
    var r22 = addScalar(c, _mul([vy, vy, oneMinusC]));
    var r23 = addScalar(_mul([vy, vz, oneMinusC]), _mul([minusOne, vx, s]));
    var r31 = addScalar(_mul([vx, vz, oneMinusC]), _mul([minusOne, vy, s]));
    var r32 = addScalar(_mul([vy, vz, oneMinusC]), _mul([vx, s]));
    var r33 = addScalar(c, _mul([vz, vz, oneMinusC]));
    var data = [[r11, r12, r13], [r21, r22, r23], [r31, r32, r33]];
    return _convertToFormat(data, format);
  }
});

var name$3i = 'row';
var dependencies$3i = ['typed', 'Index', 'matrix', 'range'];
var createRow = /* #__PURE__ */factory(name$3i, dependencies$3i, _ref => {
  var {
    typed,
    Index,
    matrix,
    range
  } = _ref;
  /**
   * Return a row from a Matrix.
   *
   * Syntax:
   *
   *     math.row(value, index)
   *
   * Example:
   *
   *     // get a row
   *     const d = [[1, 2], [3, 4]]
   *     math.row(d, 1) // returns [[3, 4]]
   *
   * See also:
   *
   *     column
   *
   * @param {Array | Matrix } value   An array or matrix
   * @param {number} row              The index of the row
   * @return {Array | Matrix}         The retrieved row
   */
  return typed(name$3i, {
    'Matrix, number': _row,
    'Array, number': function ArrayNumber(value, row) {
      return _row(matrix(clone$2(value)), row).valueOf();
    }
  });

  /**
   * Retrieve a row of a matrix
   * @param {Matrix } value  A matrix
   * @param {number} row     The index of the row
   * @return {Matrix}        The retrieved row
   */
  function _row(value, row) {
    // check dimensions
    if (value.size().length !== 2) {
      throw new Error('Only two dimensional matrix is supported');
    }
    validateIndex(row, value.size()[0]);
    var columnRange = range(0, value.size()[1]);
    var index = new Index(row, columnRange);
    var result = value.subset(index);
    return isMatrix(result) ? result : matrix([[result]]);
  }
});

var name$3h = 'size';
var dependencies$3h = ['typed', 'config', '?matrix'];
var createSize = /* #__PURE__ */factory(name$3h, dependencies$3h, _ref => {
  var {
    typed,
    config,
    matrix
  } = _ref;
  /**
   * Calculate the size of a matrix or scalar.
   *
   * Syntax:
   *
   *     math.size(x)
   *
   * Examples:
   *
   *     math.size(2.3)                  // returns []
   *     math.size('hello world')        // returns [11]
   *
   *     const A = [[1, 2, 3], [4, 5, 6]]
   *     math.size(A)                    // returns [2, 3]
   *     math.size(math.range(1,6))      // returns [5]
   *
   * See also:
   *
   *     count, resize, squeeze, subset
   *
   * @param {boolean | number | Complex | Unit | string | Array | Matrix} x  A matrix
   * @return {Array | Matrix} A vector with size of `x`.
   */
  return typed(name$3h, {
    Matrix: function Matrix(x) {
      return x.create(x.size());
    },
    Array: arraySize,
    string: function string(x) {
      return config.matrix === 'Array' ? [x.length] : matrix([x.length]);
    },
    'number | Complex | BigNumber | Unit | boolean | null': function numberComplexBigNumberUnitBooleanNull(x) {
      // scalar
      return config.matrix === 'Array' ? [] : matrix ? matrix([]) : noMatrix();
    }
  });
});

var name$3g = 'squeeze';
var dependencies$3g = ['typed', 'matrix'];
var createSqueeze = /* #__PURE__ */factory(name$3g, dependencies$3g, _ref => {
  var {
    typed,
    matrix
  } = _ref;
  /**
   * Squeeze a matrix, remove inner and outer singleton dimensions from a matrix.
   *
   * Syntax:
   *
   *     math.squeeze(x)
   *
   * Examples:
   *
   *     math.squeeze([3])           // returns 3
   *     math.squeeze([[3]])         // returns 3
   *
   *     const A = math.zeros(3, 1)    // returns [[0], [0], [0]] (size 3x1)
   *     math.squeeze(A)             // returns [0, 0, 0] (size 3)
   *
   *     const B = math.zeros(1, 3)    // returns [[0, 0, 0]] (size 1x3)
   *     math.squeeze(B)             // returns [0, 0, 0] (size 3)
   *
   *     // only inner and outer dimensions are removed
   *     const C = math.zeros(2, 1, 3) // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3)
   *     math.squeeze(C)             // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3)
   *
   * See also:
   *
   *     subset
   *
   * @param {Matrix | Array} x      Matrix to be squeezed
   * @return {Matrix | Array} Squeezed matrix
   */
  return typed(name$3g, {
    Array: function Array(x) {
      return squeeze(clone$2(x));
    },
    Matrix: function Matrix(x) {
      var res = squeeze(x.toArray());
      // FIXME: return the same type of matrix as the input
      return Array.isArray(res) ? matrix(res) : res;
    },
    any: function any(x) {
      // scalar
      return clone$2(x);
    }
  });
});

var name$3f = 'subset';
var dependencies$3f = ['typed', 'matrix', 'zeros', 'add'];
var createSubset = /* #__PURE__ */factory(name$3f, dependencies$3f, _ref => {
  var {
    typed,
    matrix,
    zeros,
    add
  } = _ref;
  /**
   * Get or set a subset of a matrix or string.
   *
   * Syntax:
   *     math.subset(value, index)                                // retrieve a subset
   *     math.subset(value, index, replacement [, defaultValue])  // replace a subset
   *
   * Examples:
   *
   *     // get a subset
   *     const d = [[1, 2], [3, 4]]
   *     math.subset(d, math.index(1, 0))             // returns 3
   *     math.subset(d, math.index([0, 1], 1))        // returns [[2], [4]]
   *     math.subset(d, math.index([false, true], 0)) // returns [[3]]
   *
   *     // replace a subset
   *     const e = []
   *     const f = math.subset(e, math.index(0, [0, 2]), [5, 6])  // f = [[5, 0, 6]]
   *     const g = math.subset(f, math.index(1, 1), 7, 0)         // g = [[5, 0, 6], [0, 7, 0]]
   *     math.subset(g, math.index([false, true], 1), 8)          // returns [[5, 0, 6], [0, 8, 0]]
   *
   *     // get submatrix using ranges
   *     const M = [
   *       [1,2,3],
   *       [4,5,6],
   *       [7,8,9]
   *     ]
   *     math.subset(M, math.index(math.range(0,2), math.range(0,3))) // [[1, 2, 3], [4, 5, 6]]
   *
   * See also:
   *
   *     size, resize, squeeze, index
   *
   * @param {Array | Matrix | string} matrix  An array, matrix, or string
   * @param {Index} index
   *    For each dimension of the target, specifies an index or a list of
   *    indices to fetch or set. `subset` uses the cartesian product of
   *    the indices specified in each dimension.
   * @param {*} [replacement]                 An array, matrix, or scalar.
   *                                          If provided, the subset is replaced with replacement.
   *                                          If not provided, the subset is returned
   * @param {*} [defaultValue=undefined]      Default value, filled in on new entries when
   *                                          the matrix is resized. If not provided,
   *                                          math.matrix elements will be left undefined.
   * @return {Array | Matrix | string} Either the retrieved subset or the updated matrix.
   */

  return typed(name$3f, {
    // get subset
    'Matrix, Index': function MatrixIndex(value, index) {
      if (isEmptyIndex(index)) {
        return matrix();
      }
      validateIndexSourceSize(value, index);
      return value.subset(index);
    },
    'Array, Index': typed.referTo('Matrix, Index', function (subsetRef) {
      return function (value, index) {
        var subsetResult = subsetRef(matrix(value), index);
        return index.isScalar() ? subsetResult : subsetResult.valueOf();
      };
    }),
    'Object, Index': _getObjectProperty,
    'string, Index': _getSubstring,
    // set subset
    'Matrix, Index, any, any': function MatrixIndexAnyAny(value, index, replacement, defaultValue) {
      if (isEmptyIndex(index)) {
        return value;
      }
      validateIndexSourceSize(value, index);
      return value.clone().subset(index, _broadcastReplacement(replacement, index), defaultValue);
    },
    'Array, Index, any, any': typed.referTo('Matrix, Index, any, any', function (subsetRef) {
      return function (value, index, replacement, defaultValue) {
        var subsetResult = subsetRef(matrix(value), index, replacement, defaultValue);
        return subsetResult.isMatrix ? subsetResult.valueOf() : subsetResult;
      };
    }),
    'Array, Index, any': typed.referTo('Matrix, Index, any, any', function (subsetRef) {
      return function (value, index, replacement) {
        return subsetRef(matrix(value), index, replacement, undefined).valueOf();
      };
    }),
    'Matrix, Index, any': typed.referTo('Matrix, Index, any, any', function (subsetRef) {
      return function (value, index, replacement) {
        return subsetRef(value, index, replacement, undefined);
      };
    }),
    'string, Index, string': _setSubstring,
    'string, Index, string, string': _setSubstring,
    'Object, Index, any': _setObjectProperty
  });

  /**
   * Broadcasts a replacment value to be the same size as index
   * @param {number | BigNumber | Array | Matrix} replacement Replacement value to try to broadcast
   * @param {*} index Index value
   * @returns broadcasted replacement that matches the size of index
   */

  function _broadcastReplacement(replacement, index) {
    if (typeof replacement === 'string') {
      throw new Error('can\'t boradcast a string');
    }
    if (index._isScalar) {
      return replacement;
    }
    var indexSize = index.size();
    if (indexSize.every(d => d > 0)) {
      try {
        return add(replacement, zeros(indexSize));
      } catch (error) {
        return replacement;
      }
    } else {
      return replacement;
    }
  }
});

/**
 * Retrieve a subset of a string
 * @param {string} str            string from which to get a substring
 * @param {Index} index           An index or list of indices (character positions)
 * @returns {string} substring
 * @private
 */
function _getSubstring(str, index) {
  if (!isIndex(index)) {
    // TODO: better error message
    throw new TypeError('Index expected');
  }
  if (isEmptyIndex(index)) {
    return '';
  }
  validateIndexSourceSize(Array.from(str), index);
  if (index.size().length !== 1) {
    throw new DimensionError(index.size().length, 1);
  }

  // validate whether the range is out of range
  var strLen = str.length;
  validateIndex(index.min()[0], strLen);
  validateIndex(index.max()[0], strLen);
  var range = index.dimension(0);
  var substr = '';
  range.forEach(function (v) {
    substr += str.charAt(v);
  });
  return substr;
}

/**
 * Replace a substring in a string
 * @param {string} str            string to be replaced
 * @param {Index} index           An index or list of indices (character positions)
 * @param {string} replacement    Replacement string
 * @param {string} [defaultValue] Default value to be used when resizing
 *                                the string. is ' ' by default
 * @returns {string} result
 * @private
 */
function _setSubstring(str, index, replacement, defaultValue) {
  if (!index || index.isIndex !== true) {
    // TODO: better error message
    throw new TypeError('Index expected');
  }
  if (isEmptyIndex(index)) {
    return str;
  }
  validateIndexSourceSize(Array.from(str), index);
  if (index.size().length !== 1) {
    throw new DimensionError(index.size().length, 1);
  }
  if (defaultValue !== undefined) {
    if (typeof defaultValue !== 'string' || defaultValue.length !== 1) {
      throw new TypeError('Single character expected as defaultValue');
    }
  } else {
    defaultValue = ' ';
  }
  var range = index.dimension(0);
  var len = range.size()[0];
  if (len !== replacement.length) {
    throw new DimensionError(range.size()[0], replacement.length);
  }

  // validate whether the range is out of range
  var strLen = str.length;
  validateIndex(index.min()[0]);
  validateIndex(index.max()[0]);

  // copy the string into an array with characters
  var chars = [];
  for (var i = 0; i < strLen; i++) {
    chars[i] = str.charAt(i);
  }
  range.forEach(function (v, i) {
    chars[v] = replacement.charAt(i[0]);
  });

  // initialize undefined characters with a space
  if (chars.length > strLen) {
    for (var _i = strLen - 1, _len = chars.length; _i < _len; _i++) {
      if (!chars[_i]) {
        chars[_i] = defaultValue;
      }
    }
  }
  return chars.join('');
}

/**
 * Retrieve a property from an object
 * @param {Object} object
 * @param {Index} index
 * @return {*} Returns the value of the property
 * @private
 */
function _getObjectProperty(object, index) {
  if (isEmptyIndex(index)) {
    return undefined;
  }
  if (index.size().length !== 1) {
    throw new DimensionError(index.size(), 1);
  }
  var key = index.dimension(0);
  if (typeof key !== 'string') {
    throw new TypeError('String expected as index to retrieve an object property');
  }
  return getSafeProperty(object, key);
}

/**
 * Set a property on an object
 * @param {Object} object
 * @param {Index} index
 * @param {*} replacement
 * @return {*} Returns the updated object
 * @private
 */
function _setObjectProperty(object, index, replacement) {
  if (isEmptyIndex(index)) {
    return object;
  }
  if (index.size().length !== 1) {
    throw new DimensionError(index.size(), 1);
  }
  var key = index.dimension(0);
  if (typeof key !== 'string') {
    throw new TypeError('String expected as index to retrieve an object property');
  }

  // clone the object, and apply the property to the clone
  var updated = clone$2(object);
  setSafeProperty(updated, key, replacement);
  return updated;
}

var name$3e = 'transpose';
var dependencies$3e = ['typed', 'matrix'];
var createTranspose = /* #__PURE__ */factory(name$3e, dependencies$3e, _ref => {
  var {
    typed,
    matrix
  } = _ref;
  /**
   * Transpose a matrix. All values of the matrix are reflected over its
   * main diagonal. Only applicable to two dimensional matrices containing
   * a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional
   * vectors and scalars return the input unchanged.
   *
   * Syntax:
   *
   *     math.transpose(x)
   *
   * Examples:
   *
   *     const A = [[1, 2, 3], [4, 5, 6]]
   *     math.transpose(A)               // returns [[1, 4], [2, 5], [3, 6]]
   *
   * See also:
   *
   *     diag, inv, subset, squeeze
   *
   * @param {Array | Matrix} x  Matrix to be transposed
   * @return {Array | Matrix}   The transposed matrix
   */
  return typed(name$3e, {
    Array: x => transposeMatrix(matrix(x)).valueOf(),
    Matrix: transposeMatrix,
    any: clone$2 // scalars
  });
  function transposeMatrix(x) {
    // matrix size
    var size = x.size();

    // result
    var c;

    // process dimensions
    switch (size.length) {
      case 1:
        // vector
        c = x.clone();
        break;
      case 2:
        {
          // rows and columns
          var rows = size[0];
          var columns = size[1];

          // check columns
          if (columns === 0) {
            // throw exception
            throw new RangeError('Cannot transpose a 2D matrix with no columns (size: ' + format(size) + ')');
          }

          // process storage format
          switch (x.storage()) {
            case 'dense':
              c = _denseTranspose(x, rows, columns);
              break;
            case 'sparse':
              c = _sparseTranspose(x, rows, columns);
              break;
          }
        }
        break;
      default:
        // multi dimensional
        throw new RangeError('Matrix must be a vector or two dimensional (size: ' + format(size) + ')');
    }
    return c;
  }
  function _denseTranspose(m, rows, columns) {
    // matrix array
    var data = m._data;
    // transposed matrix data
    var transposed = [];
    var transposedRow;
    // loop columns
    for (var j = 0; j < columns; j++) {
      // initialize row
      transposedRow = transposed[j] = [];
      // loop rows
      for (var i = 0; i < rows; i++) {
        // set data
        transposedRow[i] = clone$2(data[i][j]);
      }
    }
    // return matrix
    return m.createDenseMatrix({
      data: transposed,
      size: [columns, rows],
      datatype: m._datatype
    });
  }
  function _sparseTranspose(m, rows, columns) {
    // matrix arrays
    var values = m._values;
    var index = m._index;
    var ptr = m._ptr;
    // result matrices
    var cvalues = values ? [] : undefined;
    var cindex = [];
    var cptr = [];
    // row counts
    var w = [];
    for (var x = 0; x < rows; x++) {
      w[x] = 0;
    }
    // vars
    var p, l, j;
    // loop values in matrix
    for (p = 0, l = index.length; p < l; p++) {
      // number of values in row
      w[index[p]]++;
    }
    // cumulative sum
    var sum = 0;
    // initialize cptr with the cummulative sum of row counts
    for (var i = 0; i < rows; i++) {
      // update cptr
      cptr.push(sum);
      // update sum
      sum += w[i];
      // update w
      w[i] = cptr[i];
    }
    // update cptr
    cptr.push(sum);
    // loop columns
    for (j = 0; j < columns; j++) {
      // values & index in column
      for (var k0 = ptr[j], k1 = ptr[j + 1], k = k0; k < k1; k++) {
        // C values & index
        var q = w[index[k]]++;
        // C[j, i] = A[i, j]
        cindex[q] = j;
        // check we need to process values (pattern matrix)
        if (values) {
          cvalues[q] = clone$2(values[k]);
        }
      }
    }
    // return matrix
    return m.createSparseMatrix({
      values: cvalues,
      index: cindex,
      ptr: cptr,
      size: [columns, rows],
      datatype: m._datatype
    });
  }
});

var name$3d = 'ctranspose';
var dependencies$3d = ['typed', 'transpose', 'conj'];
var createCtranspose = /* #__PURE__ */factory(name$3d, dependencies$3d, _ref => {
  var {
    typed,
    transpose,
    conj
  } = _ref;
  /**
   * Transpose and complex conjugate a matrix. All values of the matrix are
   * reflected over its main diagonal and then the complex conjugate is
   * taken. This is equivalent to complex conjugation for scalars and
   * vectors.
   *
   * Syntax:
   *
   *     math.ctranspose(x)
   *
   * Examples:
   *
   *     const A = [[1, 2, 3], [4, 5, math.complex(6,7)]]
   *     math.ctranspose(A)               // returns [[1, 4], [2, 5], [3, {re:6,im:7}]]
   *
   * See also:
   *
   *     transpose, diag, inv, subset, squeeze
   *
   * @param {Array | Matrix} x  Matrix to be ctransposed
   * @return {Array | Matrix}   The ctransposed matrix
   */
  return typed(name$3d, {
    any: function any(x) {
      return conj(transpose(x));
    }
  });
});

var name$3c = 'zeros';
var dependencies$3c = ['typed', 'config', 'matrix', 'BigNumber'];
var createZeros = /* #__PURE__ */factory(name$3c, dependencies$3c, _ref => {
  var {
    typed,
    config,
    matrix,
    BigNumber
  } = _ref;
  /**
   * Create a matrix filled with zeros. The created matrix can have one or
   * multiple dimensions.
   *
   * Syntax:
   *
   *    math.zeros(m)
   *    math.zeros(m, format)
   *    math.zeros(m, n)
   *    math.zeros(m, n, format)
   *    math.zeros([m, n])
   *    math.zeros([m, n], format)
   *
   * Examples:
   *
   *    math.zeros()                   // returns []
   *    math.zeros(3)                  // returns [0, 0, 0]
   *    math.zeros(3, 2)               // returns [[0, 0], [0, 0], [0, 0]]
   *    math.zeros(3, 'dense')         // returns [0, 0, 0]
   *
   *    const A = [[1, 2, 3], [4, 5, 6]]
   *    math.zeros(math.size(A))       // returns [[0, 0, 0], [0, 0, 0]]
   *
   * See also:
   *
   *    ones, identity, size, range
   *
   * @param {...(number|BigNumber) | Array} size    The size of each dimension of the matrix
   * @param {string} [format]           The Matrix storage format
   *
   * @return {Array | Matrix}           A matrix filled with zeros
   */
  return typed(name$3c, {
    '': function _() {
      return config.matrix === 'Array' ? _zeros([]) : _zeros([], 'default');
    },
    // math.zeros(m, n, p, ..., format)
    // TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this
    '...number | BigNumber | string': function numberBigNumberString(size) {
      var last = size[size.length - 1];
      if (typeof last === 'string') {
        var format = size.pop();
        return _zeros(size, format);
      } else if (config.matrix === 'Array') {
        return _zeros(size);
      } else {
        return _zeros(size, 'default');
      }
    },
    Array: _zeros,
    Matrix: function Matrix(size) {
      var format = size.storage();
      return _zeros(size.valueOf(), format);
    },
    'Array | Matrix, string': function ArrayMatrixString(size, format) {
      return _zeros(size.valueOf(), format);
    }
  });

  /**
   * Create an Array or Matrix with zeros
   * @param {Array} size
   * @param {string} [format='default']
   * @return {Array | Matrix}
   * @private
   */
  function _zeros(size, format) {
    var hasBigNumbers = _normalize(size);
    var defaultValue = hasBigNumbers ? new BigNumber(0) : 0;
    _validate(size);
    if (format) {
      // return a matrix
      var m = matrix(format);
      if (size.length > 0) {
        return m.resize(size, defaultValue);
      }
      return m;
    } else {
      // return an Array
      var arr = [];
      if (size.length > 0) {
        return resize(arr, size, defaultValue);
      }
      return arr;
    }
  }

  // replace BigNumbers with numbers, returns true if size contained BigNumbers
  function _normalize(size) {
    var hasBigNumbers = false;
    size.forEach(function (value, index, arr) {
      if (isBigNumber(value)) {
        hasBigNumbers = true;
        arr[index] = value.toNumber();
      }
    });
    return hasBigNumbers;
  }

  // validate arguments
  function _validate(size) {
    size.forEach(function (value) {
      if (typeof value !== 'number' || !isInteger(value) || value < 0) {
        throw new Error('Parameters in function zeros must be positive integers');
      }
    });
  }
});

// TODO: zeros contains almost the same code as ones. Reuse this?

var name$3b = 'fft';
var dependencies$3b = ['typed', 'matrix', 'addScalar', 'multiplyScalar', 'divideScalar', 'exp', 'tau', 'i', 'dotDivide', 'conj', 'pow', 'ceil', 'log2'];
var createFft = /* #__PURE__ */factory(name$3b, dependencies$3b, _ref => {
  var {
    typed,
    matrix,
    addScalar,
    multiplyScalar,
    divideScalar,
    exp,
    tau,
    i: I,
    dotDivide,
    conj,
    pow,
    ceil,
    log2
  } = _ref;
  /**
   * Calculate N-dimensional fourier transform
   *
   * Syntax:
   *
   *     math.fft(arr)
   *
   * Examples:
   *
   *    math.fft([[1, 0], [1, 0]]) // returns [[{re:2, im:0}, {re:2, im:0}], [{re:0, im:0}, {re:0, im:0}]]
   *
   *
   * See Also:
   *
   *      ifft
   *
   * @param {Array | Matrix} arr    An array or matrix
   * @return {Array | Matrix}       N-dimensional fourier transformation of the array
   */
  return typed(name$3b, {
    Array: _ndFft,
    Matrix: function Matrix(matrix) {
      return matrix.create(_ndFft(matrix.toArray()));
    }
  });

  /**
   * Perform an N-dimensional Fourier transform
   *
   * @param {Array} arr      The array
   * @return {Array}         resulting array
   */
  function _ndFft(arr) {
    var size = arraySize(arr);
    if (size.length === 1) return _fft(arr, size[0]);
    // ndFft along dimension 1,...,N-1 then 1dFft along dimension 0
    return _1dFft(arr.map(slice => _ndFft(slice, size.slice(1))), 0);
  }

  /**
   * Perform an 1-dimensional Fourier transform
   *
   * @param {Array} arr      The array
   * @param {number} dim     dimension of the array to perform on
   * @return {Array}         resulting array
   */
  function _1dFft(arr, dim) {
    var size = arraySize(arr);
    if (dim !== 0) return new Array(size[0]).fill(0).map((_, i) => _1dFft(arr[i], dim - 1));
    if (size.length === 1) return _fft(arr);
    function _transpose(arr) {
      // Swap first 2 dimensions
      var size = arraySize(arr);
      return new Array(size[1]).fill(0).map((_, j) => new Array(size[0]).fill(0).map((_, i) => arr[i][j]));
    }
    return _transpose(_1dFft(_transpose(arr), 1));
  }
  /**
   * Perform an 1-dimensional non-power-of-2 Fourier transform using Chirp-Z Transform
   *
   * @param {Array} arr      The array
   * @return {Array}         resulting array
   */
  function _czt(arr) {
    var n = arr.length;
    var w = exp(divideScalar(multiplyScalar(-1, multiplyScalar(I, tau)), n));
    var chirp = [];
    for (var i = 1 - n; i < n; i++) {
      chirp.push(pow(w, divideScalar(pow(i, 2), 2)));
    }
    var N2 = pow(2, ceil(log2(n + n - 1)));
    var xp = [...new Array(n).fill(0).map((_, i) => multiplyScalar(arr[i], chirp[n - 1 + i])), ...new Array(N2 - n).fill(0)];
    var ichirp = [...new Array(n + n - 1).fill(0).map((_, i) => divideScalar(1, chirp[i])), ...new Array(N2 - (n + n - 1)).fill(0)];
    var fftXp = _fft(xp);
    var fftIchirp = _fft(ichirp);
    var fftProduct = new Array(N2).fill(0).map((_, i) => multiplyScalar(fftXp[i], fftIchirp[i]));
    var ifftProduct = dotDivide(conj(_ndFft(conj(fftProduct))), N2);
    var ret = [];
    for (var _i = n - 1; _i < n + n - 1; _i++) {
      ret.push(multiplyScalar(ifftProduct[_i], chirp[_i]));
    }
    return ret;
  }
  /**
   * Perform an 1-dimensional Fourier transform
   *
   * @param {Array} arr      The array
   * @return {Array}         resulting array
   */
  function _fft(arr) {
    var len = arr.length;
    if (len === 1) return [arr[0]];
    if (len % 2 === 0) {
      var ret = [..._fft(arr.filter((_, i) => i % 2 === 0)), ..._fft(arr.filter((_, i) => i % 2 === 1))];
      for (var k = 0; k < len / 2; k++) {
        var p = ret[k];
        var q = multiplyScalar(ret[k + len / 2], exp(multiplyScalar(multiplyScalar(tau, I), divideScalar(-k, len))));
        ret[k] = addScalar(p, q);
        ret[k + len / 2] = addScalar(p, multiplyScalar(-1, q));
      }
      return ret;
    } else {
      // use chirp-z transform for non-power-of-2 FFT
      return _czt(arr);
    }
    // throw new Error('Can only calculate FFT of power-of-two size')
  }
});

var name$3a = 'ifft';
var dependencies$3a = ['typed', 'fft', 'dotDivide', 'conj'];
var createIfft = /* #__PURE__ */factory(name$3a, dependencies$3a, _ref => {
  var {
    typed,
    fft,
    dotDivide,
    conj
  } = _ref;
  /**
   * Calculate N-dimensional inverse fourier transform
   *
   * Syntax:
   *
   *     math.ifft(arr)
   *
   * Examples:
   *
   *    math.ifft([[2, 2], [0, 0]]) // returns [[{re:1, im:0}, {re:0, im:0}], [{re:1, im:0}, {re:0, im:0}]]
   *
   * See Also:
   *
   *      fft
   *
   * @param {Array | Matrix} arr    An array or matrix
   * @return {Array | Matrix}       N-dimensional fourier transformation of the array
   */
  return typed(name$3a, {
    'Array | Matrix': function ArrayMatrix(arr) {
      var size = isMatrix(arr) ? arr.size() : arraySize(arr);
      return dotDivide(conj(fft(conj(arr))), size.reduce((acc, curr) => acc * curr, 1));
    }
  });
});

var defineProperty = {exports: {}};

var toPropertyKey = {exports: {}};

var _typeof = {exports: {}};

(function (module) {
function _typeof(o) {
  "@babel/helpers - typeof";

  return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
    return typeof o;
  } : function (o) {
    return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(o);
}
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
}(_typeof));

var toPrimitive = {exports: {}};

(function (module) {
var _typeof$1 = _typeof.exports["default"];
function toPrimitive(t, r) {
  if ("object" != _typeof$1(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r || "default");
    if ("object" != _typeof$1(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r ? String : Number)(t);
}
module.exports = toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
}(toPrimitive));

(function (module) {
var _typeof$1 = _typeof.exports["default"];
var toPrimitive$1 = toPrimitive.exports;
function toPropertyKey(t) {
  var i = toPrimitive$1(t, "string");
  return "symbol" == _typeof$1(i) ? i : i + "";
}
module.exports = toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
}(toPropertyKey));

(function (module) {
var toPropertyKey$1 = toPropertyKey.exports;
function _defineProperty(e, r, t) {
  return (r = toPropertyKey$1(r)) in e ? Object.defineProperty(e, r, {
    value: t,
    enumerable: !0,
    configurable: !0,
    writable: !0
  }) : e[r] = t, e;
}
module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
}(defineProperty));

var _defineProperty = /*@__PURE__*/getDefaultExportFromCjs(defineProperty.exports);

function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var name$39 = 'solveODE';
var dependencies$39 = ['typed', 'add', 'subtract', 'multiply', 'divide', 'max', 'map', 'abs', 'isPositive', 'isNegative', 'larger', 'smaller', 'matrix', 'bignumber', 'unaryMinus'];
var createSolveODE = /* #__PURE__ */factory(name$39, dependencies$39, _ref => {
  var {
    typed,
    add,
    subtract,
    multiply,
    divide,
    max,
    map,
    abs,
    isPositive,
    isNegative,
    larger,
    smaller,
    matrix,
    bignumber,
    unaryMinus
  } = _ref;
  /**
     * Numerical Integration of Ordinary Differential Equations
     *
     * Two variable step methods are provided:
     * - "RK23": Bogacki–Shampine method
     * - "RK45": Dormand-Prince method RK5(4)7M (default)
     *
     * The arguments are expected as follows.
     *
     * - `func` should be the forcing function `f(t, y)`
     * - `tspan` should be a vector of two numbers or units `[tStart, tEnd]`
     * - `y0` the initial state values, should be a scalar or a flat array
     * - `options` should be an object with the following information:
     *   - `method` ('RK45'): ['RK23', 'RK45']
     *   - `tol` (1e-3): Numeric tolerance of the method, the solver keeps the error estimates less than this value
     *   - `firstStep`: Initial step size
     *   - `minStep`: minimum step size of the method
     *   - `maxStep`: maximum step size of the method
     *   - `minDelta` (0.2): minimum ratio of change for the step
     *   - `maxDelta` (5): maximum ratio of change for the step
     *   - `maxIter` (1e4): maximum number of iterations
     *
     * The returned value is an object with `{t, y}` please note that even though `t` means time, it can represent any other independant variable like `x`:
     * - `t` an array of size `[n]`
     * - `y` the states array can be in two ways
     *   - **if `y0` is a scalar:** returns an array-like of size `[n]`
     *   - **if `y0` is a flat array-like of size [m]:** returns an array like of size `[n, m]`
     *
     * Syntax:
     *
     *     math.solveODE(func, tspan, y0)
     *     math.solveODE(func, tspan, y0, options)
     *
     * Examples:
     *
     *     function func(t, y) {return y}
     *     const tspan = [0, 4]
     *     const y0 = 1
     *     math.solveODE(func, tspan, y0)
     *     math.solveODE(func, tspan, [1, 2])
     *     math.solveODE(func, tspan, y0, { method:"RK23", maxStep:0.1 })
     *
     * See also:
     *
     *     derivative, simplifyCore
     *
     * @param {function} func The forcing function f(t,y)
     * @param {Array | Matrix} tspan The time span
     * @param {number | BigNumber | Unit | Array | Matrix} y0 The initial value
     * @param {Object} [options] Optional configuration options
     * @return {Object} Return an object with t and y values as arrays
     */

  function _rk(butcherTableau) {
    // generates an adaptive runge kutta method from it's butcher tableau

    return function (f, tspan, y0, options) {
      // adaptive runge kutta methods
      var wrongTSpan = !(tspan.length === 2 && (tspan.every(isNumOrBig) || tspan.every(isUnit)));
      if (wrongTSpan) {
        throw new Error('"tspan" must be an Array of two numeric values or two units [tStart, tEnd]');
      }
      var t0 = tspan[0]; // initial time
      var tf = tspan[1]; // final time
      var isForwards = larger(tf, t0);
      var firstStep = options.firstStep;
      if (firstStep !== undefined && !isPositive(firstStep)) {
        throw new Error('"firstStep" must be positive');
      }
      var maxStep = options.maxStep;
      if (maxStep !== undefined && !isPositive(maxStep)) {
        throw new Error('"maxStep" must be positive');
      }
      var minStep = options.minStep;
      if (minStep && isNegative(minStep)) {
        throw new Error('"minStep" must be positive or zero');
      }
      var timeVars = [t0, tf, firstStep, minStep, maxStep].filter(x => x !== undefined);
      if (!(timeVars.every(isNumOrBig) || timeVars.every(isUnit))) {
        throw new Error('Inconsistent type of "t" dependant variables');
      }
      var steps = 1; // divide time in this number of steps
      var tol = options.tol ? options.tol : 1e-4; // define a tolerance (must be an option)
      var minDelta = options.minDelta ? options.minDelta : 0.2;
      var maxDelta = options.maxDelta ? options.maxDelta : 5;
      var maxIter = options.maxIter ? options.maxIter : 10000; // stop inifite evaluation if something goes wrong
      var hasBigNumbers = [t0, tf, ...y0, maxStep, minStep].some(isBigNumber);
      var [a, c, b, bp] = hasBigNumbers ? [bignumber(butcherTableau.a), bignumber(butcherTableau.c), bignumber(butcherTableau.b), bignumber(butcherTableau.bp)] : [butcherTableau.a, butcherTableau.c, butcherTableau.b, butcherTableau.bp];
      var h = firstStep ? isForwards ? firstStep : unaryMinus(firstStep) : divide(subtract(tf, t0), steps); // define the first step size
      var t = [t0]; // start the time array
      var y = [y0]; // start the solution array

      var deltaB = subtract(b, bp); // b - bp

      var n = 0;
      var iter = 0;
      var ongoing = _createOngoing(isForwards);
      var trimStep = _createTrimStep(isForwards);
      // iterate unitil it reaches either the final time or maximum iterations
      while (ongoing(t[n], tf)) {
        var k = [];

        // trim the time step so that it doesn't overshoot
        h = trimStep(t[n], tf, h);

        // calculate the first value of k
        k.push(f(t[n], y[n]));

        // calculate the rest of the values of k
        for (var i = 1; i < c.length; ++i) {
          k.push(f(add(t[n], multiply(c[i], h)), add(y[n], multiply(h, a[i], k))));
        }

        // estimate the error by comparing solutions of different orders
        var TE = max(abs(map(multiply(deltaB, k), X => isUnit(X) ? X.value : X)));
        if (TE < tol && tol / TE > 1 / 4) {
          // push solution if within tol
          t.push(add(t[n], h));
          y.push(add(y[n], multiply(h, b, k)));
          n++;
        }

        // estimate the delta value that will affect the step size
        var delta = 0.84 * (tol / TE) ** (1 / 5);
        if (smaller(delta, minDelta)) {
          delta = minDelta;
        } else if (larger(delta, maxDelta)) {
          delta = maxDelta;
        }
        delta = hasBigNumbers ? bignumber(delta) : delta;
        h = multiply(h, delta);
        if (maxStep && larger(abs(h), maxStep)) {
          h = isForwards ? maxStep : unaryMinus(maxStep);
        } else if (minStep && smaller(abs(h), minStep)) {
          h = isForwards ? minStep : unaryMinus(minStep);
        }
        iter++;
        if (iter > maxIter) {
          throw new Error('Maximum number of iterations reached, try changing options');
        }
      }
      return {
        t,
        y
      };
    };
  }
  function _rk23(f, tspan, y0, options) {
    // Bogacki–Shampine method

    // Define the butcher table
    var a = [[], [1 / 2], [0, 3 / 4], [2 / 9, 1 / 3, 4 / 9]];
    var c = [null, 1 / 2, 3 / 4, 1];
    var b = [2 / 9, 1 / 3, 4 / 9, 0];
    var bp = [7 / 24, 1 / 4, 1 / 3, 1 / 8];
    var butcherTableau = {
      a,
      c,
      b,
      bp
    };

    // Solve an adaptive step size rk method
    return _rk(butcherTableau)(f, tspan, y0, options);
  }
  function _rk45(f, tspan, y0, options) {
    // Dormand Prince method

    // Define the butcher tableau
    var a = [[], [1 / 5], [3 / 40, 9 / 40], [44 / 45, -56 / 15, 32 / 9], [19372 / 6561, -25360 / 2187, 64448 / 6561, -212 / 729], [9017 / 3168, -355 / 33, 46732 / 5247, 49 / 176, -5103 / 18656], [35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84]];
    var c = [null, 1 / 5, 3 / 10, 4 / 5, 8 / 9, 1, 1];
    var b = [35 / 384, 0, 500 / 1113, 125 / 192, -2187 / 6784, 11 / 84, 0];
    var bp = [5179 / 57600, 0, 7571 / 16695, 393 / 640, -92097 / 339200, 187 / 2100, 1 / 40];
    var butcherTableau = {
      a,
      c,
      b,
      bp
    };

    // Solve an adaptive step size rk method
    return _rk(butcherTableau)(f, tspan, y0, options);
  }
  function _solveODE(f, tspan, y0, opt) {
    var method = opt.method ? opt.method : 'RK45';
    var methods = {
      RK23: _rk23,
      RK45: _rk45
    };
    if (method.toUpperCase() in methods) {
      var methodOptions = _objectSpread$2({}, opt); // clone the options object
      delete methodOptions.method; // delete the method as it won't be needed
      return methods[method.toUpperCase()](f, tspan, y0, methodOptions);
    } else {
      // throw an error indicating there is no such method
      var methodsWithQuotes = Object.keys(methods).map(x => "\"".concat(x, "\""));
      // generates a string of methods like: "BDF", "RK23" and "RK45"
      var availableMethodsString = "".concat(methodsWithQuotes.slice(0, -1).join(', '), " and ").concat(methodsWithQuotes.slice(-1));
      throw new Error("Unavailable method \"".concat(method, "\". Available methods are ").concat(availableMethodsString));
    }
  }
  function _createOngoing(isForwards) {
    // returns the correct function to test if it's still iterating
    return isForwards ? smaller : larger;
  }
  function _createTrimStep(isForwards) {
    var outOfBounds = isForwards ? larger : smaller;
    return function (t, tf, h) {
      var next = add(t, h);
      return outOfBounds(next, tf) ? subtract(tf, t) : h;
    };
  }
  function isNumOrBig(x) {
    // checks if it's a number or bignumber
    return isBigNumber(x) || isNumber(x);
  }
  function _matrixSolveODE(f, T, y0, options) {
    // receives matrices and returns matrices
    var sol = _solveODE(f, T.toArray(), y0.toArray(), options);
    return {
      t: matrix(sol.t),
      y: matrix(sol.y)
    };
  }
  return typed('solveODE', {
    'function, Array, Array, Object': _solveODE,
    'function, Matrix, Matrix, Object': _matrixSolveODE,
    'function, Array, Array': (f, T, y0) => _solveODE(f, T, y0, {}),
    'function, Matrix, Matrix': (f, T, y0) => _matrixSolveODE(f, T, y0, {}),
    'function, Array, number | BigNumber | Unit': (f, T, y0) => {
      var sol = _solveODE(f, T, [y0], {});
      return {
        t: sol.t,
        y: sol.y.map(Y => Y[0])
      };
    },
    'function, Matrix, number | BigNumber | Unit': (f, T, y0) => {
      var sol = _solveODE(f, T.toArray(), [y0], {});
      return {
        t: matrix(sol.t),
        y: matrix(sol.y.map(Y => Y[0]))
      };
    },
    'function, Array, number | BigNumber | Unit, Object': (f, T, y0, options) => {
      var sol = _solveODE(f, T, [y0], options);
      return {
        t: sol.t,
        y: sol.y.map(Y => Y[0])
      };
    },
    'function, Matrix, number | BigNumber | Unit, Object': (f, T, y0, options) => {
      var sol = _solveODE(f, T.toArray(), [y0], options);
      return {
        t: matrix(sol.t),
        y: matrix(sol.y.map(Y => Y[0]))
      };
    }
  });
});

/* eslint-disable no-loss-of-precision */
var name$38 = 'erf';
var dependencies$38 = ['typed'];
var createErf = /* #__PURE__ */factory(name$38, dependencies$38, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Compute the erf function of a value using a rational Chebyshev
   * approximations for different intervals of x.
   *
   * This is a translation of W. J. Cody's Fortran implementation from 1987
   * ( https://www.netlib.org/specfun/erf ). See the AMS publication
   * "Rational Chebyshev Approximations for the Error Function" by W. J. Cody
   * for an explanation of this process.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.erf(x)
   *
   * Examples:
   *
   *    math.erf(0.2)    // returns 0.22270258921047847
   *    math.erf(-0.5)   // returns -0.5204998778130465
   *    math.erf(4)      // returns 0.9999999845827421
   *
   * See also:
   *    zeta
   *
   * @param {number | Array | Matrix} x   A real number
   * @return {number | Array | Matrix}    The erf of `x`
   */
  return typed('name', {
    number: function number(x) {
      var y = Math.abs(x);
      if (y >= MAX_NUM) {
        return sign$1(x);
      }
      if (y <= THRESH) {
        return sign$1(x) * erf1(y);
      }
      if (y <= 4.0) {
        return sign$1(x) * (1 - erfc2(y));
      }
      return sign$1(x) * (1 - erfc3(y));
    },
    'Array | Matrix': typed.referToSelf(self => n => deepMap(n, self))

    // TODO: For complex numbers, use the approximation for the Faddeeva function
    //  from "More Efficient Computation of the Complex Error Function" (AMS)
  });

  /**
   * Approximates the error function erf() for x <= 0.46875 using this function:
   *               n
   * erf(x) = x * sum (p_j * x^(2j)) / (q_j * x^(2j))
   *              j=0
   */
  function erf1(y) {
    var ysq = y * y;
    var xnum = P[0][4] * ysq;
    var xden = ysq;
    var i;
    for (i = 0; i < 3; i += 1) {
      xnum = (xnum + P[0][i]) * ysq;
      xden = (xden + Q[0][i]) * ysq;
    }
    return y * (xnum + P[0][3]) / (xden + Q[0][3]);
  }

  /**
   * Approximates the complement of the error function erfc() for
   * 0.46875 <= x <= 4.0 using this function:
   *                       n
   * erfc(x) = e^(-x^2) * sum (p_j * x^j) / (q_j * x^j)
   *                      j=0
   */
  function erfc2(y) {
    var xnum = P[1][8] * y;
    var xden = y;
    var i;
    for (i = 0; i < 7; i += 1) {
      xnum = (xnum + P[1][i]) * y;
      xden = (xden + Q[1][i]) * y;
    }
    var result = (xnum + P[1][7]) / (xden + Q[1][7]);
    var ysq = parseInt(y * 16) / 16;
    var del = (y - ysq) * (y + ysq);
    return Math.exp(-ysq * ysq) * Math.exp(-del) * result;
  }

  /**
   * Approximates the complement of the error function erfc() for x > 4.0 using
   * this function:
   *
   * erfc(x) = (e^(-x^2) / x) * [ 1/sqrt(pi) +
   *               n
   *    1/(x^2) * sum (p_j * x^(-2j)) / (q_j * x^(-2j)) ]
   *              j=0
   */
  function erfc3(y) {
    var ysq = 1 / (y * y);
    var xnum = P[2][5] * ysq;
    var xden = ysq;
    var i;
    for (i = 0; i < 4; i += 1) {
      xnum = (xnum + P[2][i]) * ysq;
      xden = (xden + Q[2][i]) * ysq;
    }
    var result = ysq * (xnum + P[2][4]) / (xden + Q[2][4]);
    result = (SQRPI - result) / y;
    ysq = parseInt(y * 16) / 16;
    var del = (y - ysq) * (y + ysq);
    return Math.exp(-ysq * ysq) * Math.exp(-del) * result;
  }
});

/**
 * Upper bound for the first approximation interval, 0 <= x <= THRESH
 * @constant
 */
var THRESH = 0.46875;

/**
 * Constant used by W. J. Cody's Fortran77 implementation to denote sqrt(pi)
 * @constant
 */
var SQRPI = 5.6418958354775628695e-1;

/**
 * Coefficients for each term of the numerator sum (p_j) for each approximation
 * interval (see W. J. Cody's paper for more details)
 * @constant
 */
var P = [[3.16112374387056560e00, 1.13864154151050156e02, 3.77485237685302021e02, 3.20937758913846947e03, 1.85777706184603153e-1], [5.64188496988670089e-1, 8.88314979438837594e00, 6.61191906371416295e01, 2.98635138197400131e02, 8.81952221241769090e02, 1.71204761263407058e03, 2.05107837782607147e03, 1.23033935479799725e03, 2.15311535474403846e-8], [3.05326634961232344e-1, 3.60344899949804439e-1, 1.25781726111229246e-1, 1.60837851487422766e-2, 6.58749161529837803e-4, 1.63153871373020978e-2]];

/**
 * Coefficients for each term of the denominator sum (q_j) for each approximation
 * interval (see W. J. Cody's paper for more details)
 * @constant
 */
var Q = [[2.36012909523441209e01, 2.44024637934444173e02, 1.28261652607737228e03, 2.84423683343917062e03], [1.57449261107098347e01, 1.17693950891312499e02, 5.37181101862009858e02, 1.62138957456669019e03, 3.29079923573345963e03, 4.36261909014324716e03, 3.43936767414372164e03, 1.23033935480374942e03], [2.56852019228982242e00, 1.87295284992346047e00, 5.27905102951428412e-1, 6.05183413124413191e-2, 2.33520497626869185e-3]];

/**
 * Maximum/minimum safe numbers to input to erf() (in ES6+, this number is
 * Number.[MAX|MIN]_SAFE_INTEGER). erf() for all numbers beyond this limit will
 * return 1
 */
var MAX_NUM = Math.pow(2, 53);

var name$37 = 'zeta';
var dependencies$37 = ['typed', 'config', 'multiply', 'pow', 'divide', 'factorial', 'equal', 'smallerEq', 'isNegative', 'gamma', 'sin', 'subtract', 'add', '?Complex', '?BigNumber', 'pi'];
var createZeta = /* #__PURE__ */factory(name$37, dependencies$37, _ref => {
  var {
    typed,
    config,
    multiply,
    pow,
    divide,
    factorial,
    equal,
    smallerEq,
    isNegative,
    gamma,
    sin,
    subtract,
    add,
    Complex,
    BigNumber: _BigNumber,
    pi
  } = _ref;
  /**
   * Compute the Riemann Zeta function of a value using an infinite series for
   * all of the complex plane using Riemann's Functional equation.
   *
   * Based off the paper by Xavier Gourdon and Pascal Sebah
   * ( http://numbers.computation.free.fr/Constants/Miscellaneous/zetaevaluations.pdf )
   *
   * Implementation and slight modification by Anik Patel
   *
   * Note: the implementation is accurate up to about 6 digits.
   *
   * Syntax:
   *
   *    math.zeta(n)
   *
   * Examples:
   *
   *    math.zeta(5)       // returns 1.0369277551433895
   *    math.zeta(-0.5)    // returns -0.2078862249773449
   *    math.zeta(math.i)  // returns 0.0033002236853253153 - 0.4181554491413212i
   *
   * See also:
   *    erf
   *
   * @param {number | Complex | BigNumber} s   A Real, Complex or BigNumber parameter to the Riemann Zeta Function
   * @return {number | Complex | BigNumber}    The Riemann Zeta of `s`
   */
  return typed(name$37, {
    number: s => zetaNumeric(s, value => value, () => 20),
    BigNumber: s => zetaNumeric(s, value => new _BigNumber(value), () => {
      // relTol is for example 1e-12. Extract the positive exponent 12 from that
      return Math.abs(Math.log10(config.relTol));
    }),
    Complex: zetaComplex
  });

  /**
   * @param {number | BigNumber} s
   * @param {(value: number) => number | BigNumber} createValue
   * @param {(value: number | BigNumber | Complex) => number} determineDigits
   * @returns {number | BigNumber}
   */
  function zetaNumeric(s, createValue, determineDigits) {
    if (equal(s, 0)) {
      return createValue(-0.5);
    }
    if (equal(s, 1)) {
      return createValue(NaN);
    }
    if (!isFinite(s)) {
      return isNegative(s) ? createValue(NaN) : createValue(1);
    }
    return zeta(s, createValue, determineDigits, s => s);
  }

  /**
   * @param {Complex} s
   * @returns {Complex}
   */
  function zetaComplex(s) {
    if (s.re === 0 && s.im === 0) {
      return new Complex(-0.5);
    }
    if (s.re === 1) {
      return new Complex(NaN, NaN);
    }
    if (s.re === Infinity && s.im === 0) {
      return new Complex(1);
    }
    if (s.im === Infinity || s.re === -Infinity) {
      return new Complex(NaN, NaN);
    }
    return zeta(s, value => value, s => Math.round(1.3 * 15 + 0.9 * Math.abs(s.im)), s => s.re);
  }

  /**
   * @param {number | BigNumber | Complex} s
   * @param {(value: number) => number | BigNumber | Complex} createValue
   * @param {(value: number | BigNumber | Complex) => number} determineDigits
   * @param {(value: number | BigNumber | Complex) => number} getRe
   * @returns {*|number}
   */
  function zeta(s, createValue, determineDigits, getRe) {
    var n = determineDigits(s);
    if (getRe(s) > -(n - 1) / 2) {
      return f(s, createValue(n), createValue);
    } else {
      // Function Equation for reflection to x < 1
      var c = multiply(pow(2, s), pow(createValue(pi), subtract(s, 1)));
      c = multiply(c, sin(multiply(divide(createValue(pi), 2), s)));
      c = multiply(c, gamma(subtract(1, s)));
      return multiply(c, zeta(subtract(1, s), createValue, determineDigits, getRe));
    }
  }

  /**
   * Calculate a portion of the sum
   * @param {number | BigNumber} k   a positive integer
   * @param {number | BigNumber} n   a positive integer
   * @return {number}    the portion of the sum
   **/
  function d(k, n) {
    var S = k;
    for (var j = k; smallerEq(j, n); j = add(j, 1)) {
      var factor = divide(multiply(factorial(add(n, subtract(j, 1))), pow(4, j)), multiply(factorial(subtract(n, j)), factorial(multiply(2, j))));
      S = add(S, factor);
    }
    return multiply(n, S);
  }

  /**
   * Calculate the positive Riemann Zeta function
   * @param {number} s   a real or complex number with s.re > 1
   * @param {number} n   a positive integer
   * @param {(number) => number | BigNumber | Complex} createValue
   * @return {number}    Riemann Zeta of s
   **/
  function f(s, n, createValue) {
    var c = divide(1, multiply(d(createValue(0), n), subtract(1, pow(2, subtract(1, s)))));
    var S = createValue(0);
    for (var k = createValue(1); smallerEq(k, n); k = add(k, 1)) {
      S = add(S, divide(multiply((-1) ** (k - 1), d(k, n)), pow(k, s)));
    }
    return multiply(c, S);
  }
});

var name$36 = 'mode';
var dependencies$36 = ['typed', 'isNaN', 'isNumeric'];
var createMode = /* #__PURE__ */factory(name$36, dependencies$36, _ref => {
  var {
    typed,
    isNaN,
    isNumeric
  } = _ref;
  /**
  * Computes the mode of a set of numbers or a list with values(numbers or characters).
  * If there are multiple modes, it returns a list of those values.
  *
  * Syntax:
  *
  *     math.mode(a, b, c, ...)
  *     math.mode(A)
  *
  * Examples:
  *
  *     math.mode(2, 1, 4, 3, 1)                            // returns [1]
  *     math.mode([1, 2.7, 3.2, 4, 2.7])                    // returns [2.7]
  *     math.mode(1, 4, 6, 1, 6)                             // returns [1, 6]
  *     math.mode('a','a','b','c')                           // returns ["a"]
  *     math.mode(1, 1.5, 'abc')                             // returns [1, 1.5, "abc"]
  *
  * See also:
  *
  *     median,
  *     mean
  *
  * @param {... *} args  A single matrix
  * @return {*} The mode of all values
  */
  return typed(name$36, {
    'Array | Matrix': _mode,
    '...': function _(args) {
      return _mode(args);
    }
  });

  /**
   * Calculates the mode in an 1-dimensional array
   * @param {Array} values
   * @return {Array} mode
   * @private
   */
  function _mode(values) {
    values = flatten(values.valueOf());
    var num = values.length;
    if (num === 0) {
      throw new Error('Cannot calculate mode of an empty array');
    }
    var count = {};
    var mode = [];
    var max = 0;
    for (var i = 0; i < values.length; i++) {
      var value = values[i];
      if (isNumeric(value) && isNaN(value)) {
        throw new Error('Cannot calculate mode of an array containing NaN values');
      }
      if (!(value in count)) {
        count[value] = 0;
      }
      count[value]++;
      if (count[value] === max) {
        mode.push(value);
      } else if (count[value] > max) {
        max = count[value];
        mode = [value];
      }
    }
    return mode;
  }
});

/**
 * Improve error messages for statistics functions. Errors are typically
 * thrown in an internally used function like larger, causing the error
 * not to mention the function (like max) which is actually used by the user.
 *
 * @param {Error} err
 * @param {String} fnName
 * @param {*} [value]
 * @return {Error}
 */
function improveErrorMessage(err, fnName, value) {
  // TODO: add information with the index (also needs transform in expression parser)
  var details;
  if (String(err).includes('Unexpected type')) {
    details = arguments.length > 2 ? ' (type: ' + typeOf(value) + ', value: ' + JSON.stringify(value) + ')' : ' (type: ' + err.data.actual + ')';
    return new TypeError('Cannot calculate ' + fnName + ', unexpected type of argument' + details);
  }
  if (String(err).includes('complex numbers')) {
    details = arguments.length > 2 ? ' (type: ' + typeOf(value) + ', value: ' + JSON.stringify(value) + ')' : '';
    return new TypeError('Cannot calculate ' + fnName + ', no ordering relation is defined for complex numbers' + details);
  }
  return err;
}

var name$35 = 'prod';
var dependencies$35 = ['typed', 'config', 'multiplyScalar', 'numeric'];
var createProd = /* #__PURE__ */factory(name$35, dependencies$35, _ref => {
  var {
    typed,
    config,
    multiplyScalar,
    numeric
  } = _ref;
  /**
   * Compute the product of a matrix or a list with values.
   * In case of a multidimensional array or matrix, the sum of all
   * elements will be calculated.
   *
   * Syntax:
   *
   *     math.prod(a, b, c, ...)
   *     math.prod(A)
   *
   * Examples:
   *
   *     math.multiply(2, 3)           // returns 6
   *     math.prod(2, 3)               // returns 6
   *     math.prod(2, 3, 4)            // returns 24
   *     math.prod([2, 3, 4])          // returns 24
   *     math.prod([[2, 5], [4, 3]])   // returns 120
   *
   * See also:
   *
   *    mean, median, min, max, sum, std, variance
   *
   * @param {... *} args  A single matrix or or multiple scalar values
   * @return {*} The product of all values
   */
  return typed(name$35, {
    // prod([a, b, c, d, ...])
    'Array | Matrix': _prod,
    // prod([a, b, c, d, ...], dim)
    'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) {
      // TODO: implement prod(A, dim)
      throw new Error('prod(A, dim) is not yet supported');
      // return reduce(arguments[0], arguments[1], math.prod)
    },
    // prod(a, b, c, d, ...)
    '...': function _(args) {
      return _prod(args);
    }
  });

  /**
   * Recursively calculate the product of an n-dimensional array
   * @param {Array} array
   * @return {number} prod
   * @private
   */
  function _prod(array) {
    var prod;
    deepForEach(array, function (value) {
      try {
        prod = prod === undefined ? value : multiplyScalar(prod, value);
      } catch (err) {
        throw improveErrorMessage(err, 'prod', value);
      }
    });

    // make sure returning numeric value: parse a string into a numeric value
    if (typeof prod === 'string') {
      prod = numeric(prod, safeNumberType(prod, config));
    }
    if (prod === undefined) {
      throw new Error('Cannot calculate prod of an empty array');
    }
    return prod;
  }
});

var name$34 = 'format';
var dependencies$34 = ['typed'];
var createFormat = /* #__PURE__ */factory(name$34, dependencies$34, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Format a value of any type into a string.
   *
   * Syntax:
   *
   *    math.format(value)
   *    math.format(value, options)
   *    math.format(value, precision)
   *    math.format(value, callback)
   *
   * Where:
   *
   *  - `value: *`
   *    The value to be formatted
   *  - `options: Object`
   *    An object with formatting options. Available options:
   *    - `notation: string`
   *      Number notation. Choose from:
   *      - `'fixed'`
   *        Always use regular number notation.
   *        For example `'123.40'` and `'14000000'`
   *      - `'exponential'`
   *        Always use exponential notation.
   *        For example `'1.234e+2'` and `'1.4e+7'`
   *      - `'engineering'`
   *        Always use engineering notation: always have exponential notation,
   *        and select the exponent to be a multiple of `3`.
   *        For example `'123.4e+0'` and `'14.0e+6'`
   *      - `'auto'` (default)
   *        Regular number notation for numbers having an absolute value between
   *        `lower` and `upper` bounds, and uses exponential notation elsewhere.
   *        Lower bound is included, upper bound is excluded.
   *        For example `'123.4'` and `'1.4e7'`.
   *      - `'bin'`, `'oct'`, or `'hex'`
   *        Format the number using binary, octal, or hexadecimal notation.
   *        For example `'0b1101'` and `'0x10fe'`.
   *    - `wordSize: number | BigNumber`
   *      The word size in bits to use for formatting in binary, octal, or
   *      hexadecimal notation. To be used only with `'bin'`, `'oct'`, or `'hex'`
   *      values for `notation` option. When this option is defined the value
   *      is formatted as a signed twos complement integer of the given word
   *      size and the size suffix is appended to the output.
   *      For example `format(-1, {notation: 'hex', wordSize: 8}) === '0xffi8'`.
   *      Default value is undefined.
   *    - `precision: number | BigNumber`
   *      Limit the number of digits of the formatted value.
   *      For regular numbers, must be a number between `0` and `16`.
   *      For bignumbers, the maximum depends on the configured precision,
   *      see function `config()`.
   *      In case of notations `'exponential'`, `'engineering'`, and `'auto'`,
   *      `precision` defines the total number of significant digits returned.
   *      In case of notation `'fixed'`, `precision` defines the number of
   *      significant digits after the decimal point.
   *      `precision` is undefined by default.
   *    - `lowerExp: number`
   *      Exponent determining the lower boundary for formatting a value with
   *      an exponent when `notation='auto'`. Default value is `-3`.
   *    - `upperExp: number`
   *      Exponent determining the upper boundary for formatting a value with
   *      an exponent when `notation='auto'`. Default value is `5`.
   *    - `fraction: string`. Available values: `'ratio'` (default) or `'decimal'`.
   *      For example `format(fraction(1, 3))` will output `'1/3'` when `'ratio'`
   *      is configured, and will output `'0.(3)'` when `'decimal'` is configured.
   *    - `truncate: number`. Specifies the maximum allowed length of the
   *      returned string. If it had been longer, the excess characters
   *      are deleted and replaced with `'...'`.
   * - `callback: function`
   *   A custom formatting function, invoked for all numeric elements in `value`,
   *   for example all elements of a matrix, or the real and imaginary
   *   parts of a complex number. This callback can be used to override the
   *   built-in numeric notation with any type of formatting. Function `callback`
   *   is called with `value` as parameter and must return a string.
   *
   * When `value` is an Object:
   *
   * - When the object contains a property `format` being a function, this function
   *   is invoked as `value.format(options)` and the result is returned.
   * - When the object has its own `toString` method, this method is invoked
   *   and the result is returned.
   * - In other cases the function will loop over all object properties and
   *   return JSON object notation like '{"a": 2, "b": 3}'.
   *
   * When value is a function:
   *
   * - When the function has a property `syntax`, it returns this
   *   syntax description.
   * - In other cases, a string `'function'` is returned.
   *
   * Examples:
   *
   *    math.format(6.4)                                        // returns '6.4'
   *    math.format(1240000)                                    // returns '1.24e+6'
   *    math.format(1/3)                                        // returns '0.3333333333333333'
   *    math.format(1/3, 3)                                     // returns '0.333'
   *    math.format(21385, 2)                                   // returns '21000'
   *    math.format(12e8, {notation: 'fixed'})                  // returns '1200000000'
   *    math.format(2.3,  {notation: 'fixed', precision: 4})    // returns '2.3000'
   *    math.format(52.8, {notation: 'exponential'})            // returns '5.28e+1'
   *    math.format(12400, {notation: 'engineering'})           // returns '12.4e+3'
   *    math.format(2000, {lowerExp: -2, upperExp: 2})          // returns '2e+3'
   *
   *    function formatCurrency(value) {
   *      // return currency notation with two digits:
   *      return '$' + value.toFixed(2)
   *
   *      // you could also use math.format inside the callback:
   *      // return '$' + math.format(value, {notation: 'fixed', precision: 2})
   *    }
   *    math.format([2.1, 3, 0.016], formatCurrency)            // returns '[$2.10, $3.00, $0.02]'
   *
   * See also:
   *
   *    print
   *
   * @param {*} value                               Value to be stringified
   * @param {Object | Function | number} [options]  Formatting options
   * @return {string} The formatted value
   */
  return typed(name$34, {
    any: format,
    'any, Object | function | number | BigNumber': format
  });
});

var name$33 = 'bin';
var dependencies$33 = ['typed', 'format'];

/**
 * Format a number as binary.
 *
 * Syntax:
 *
 *    math.bin(value)
 *
 * Examples:
 *
 *    //the following outputs "0b10"
 *    math.bin(2)
 *
 * See also:
 *
 *    oct
 *    hex
 *
 * @param {number | BigNumber} value    Value to be stringified
 * @param {number | BigNumber} wordSize Optional word size (see `format`)
 * @return {string}         The formatted value
 */
var createBin = factory(name$33, dependencies$33, _ref => {
  var {
    typed,
    format
  } = _ref;
  return typed(name$33, {
    'number | BigNumber': function numberBigNumber(n) {
      return format(n, {
        notation: 'bin'
      });
    },
    'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(n, wordSize) {
      return format(n, {
        notation: 'bin',
        wordSize
      });
    }
  });
});

var name$32 = 'oct';
var dependencies$32 = ['typed', 'format'];

/**
 * Format a number as octal.
 *
 * Syntax:
 *
 *    math.oct(value)
 *
 * Examples:
 *
 *    //the following outputs "0o70"
 *    math.oct(56)
 *
 * See also:
 *
 *    bin
 *    hex
 *
 * @param {number | BigNumber} value    Value to be stringified
 * @param {number | BigNumber} wordSize Optional word size (see `format`)
 * @return {string}         The formatted value
 */

var createOct = factory(name$32, dependencies$32, _ref => {
  var {
    typed,
    format
  } = _ref;
  return typed(name$32, {
    'number | BigNumber': function numberBigNumber(n) {
      return format(n, {
        notation: 'oct'
      });
    },
    'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(n, wordSize) {
      return format(n, {
        notation: 'oct',
        wordSize
      });
    }
  });
});

var name$31 = 'hex';
var dependencies$31 = ['typed', 'format'];

/**
 * Format a number as hexadecimal.
 *
 * Syntax:
 *
 *    math.hex(value)
 *
 * Examples:
 *
 *    math.hex(240) // returns "0xF0"
 *
 * See also:
 *
 *    oct
 *    bin
 *
 * @param {number | BigNumber} value    Value to be stringified
 * @param {number | BigNumber} wordSize Optional word size (see `format`)
 * @return {string}         The formatted value
 */
var createHex = factory(name$31, dependencies$31, _ref => {
  var {
    typed,
    format
  } = _ref;
  return typed(name$31, {
    'number | BigNumber': function numberBigNumber(n) {
      return format(n, {
        notation: 'hex'
      });
    },
    'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(n, wordSize) {
      return format(n, {
        notation: 'hex',
        wordSize
      });
    }
  });
});

var printTemplate = /\$([\w.]+)/g;

var name$30 = 'print';
var dependencies$30 = ['typed'];
var createPrint = /* #__PURE__ */factory(name$30, dependencies$30, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Interpolate values into a string template.
   *
   * Syntax:
   *
   *     math.print(template, values)
   *     math.print(template, values, precision)
   *     math.print(template, values, options)
   *
   * Example usage:
   *
   *     // the following outputs: 'Lucy is 5 years old'
   *     math.print('Lucy is $age years old', {age: 5})
   *
   *     // the following outputs: 'The value of pi is 3.141592654'
   *     math.print('The value of pi is $pi', {pi: math.pi}, 10)
   *
   *     // the following outputs: 'hello Mary! The date is 2013-03-23'
   *     math.print('Hello $user.name! The date is $date', {
   *       user: {
   *         name: 'Mary',
   *       },
   *       date: new Date(2013, 2, 23).toISOString().substring(0, 10)
   *     })
   *
   *     // the following outputs: 'My favorite fruits are apples and bananas !'
   *     math.print('My favorite fruits are $0 and $1 !', [
   *       'apples',
   *       'bananas'
   *     ])
   *
   * See also:
   *
   *     format
   *
   * @param {string} template           A string containing variable placeholders.
   * @param {Object | Array | Matrix}   values An object or array containing variables
   *                                    which will be filled in in the template.
   * @param {number | Object} [options] Formatting options,
   *                                    or the number of digits to format numbers.
   *                                    See function math.format for a description
   *                                    of all options.
   * @return {string} Interpolated string
   */
  return typed(name$30, {
    // note: Matrix will be converted automatically to an Array
    'string, Object | Array': _print,
    'string, Object | Array, number | Object': _print
  });
});

/**
 * Interpolate values into a string template.
 * @param {string} template
 * @param {Object} values
 * @param {number | Object} [options]
 * @returns {string} Interpolated string
 * @private
 */
function _print(template, values, options) {
  return template.replace(printTemplate, function (original, key) {
    var keys = key.split('.');
    var value = values[keys.shift()];
    if (value !== undefined && value.isMatrix) {
      value = value.toArray();
    }
    while (keys.length && value !== undefined) {
      var k = keys.shift();
      value = k ? value[k] : value + '.';
    }
    if (value !== undefined) {
      if (!isString(value)) {
        return format(value, options);
      } else {
        return value;
      }
    }
    return original;
  });
}

var name$2$ = 'to';
var dependencies$2$ = ['typed', 'matrix', 'concat'];
var createTo = /* #__PURE__ */factory(name$2$, dependencies$2$, _ref => {
  var {
    typed,
    matrix,
    concat
  } = _ref;
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Change the unit of a value.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.to(x, unit)
   *
   * Examples:
   *
   *    math.to(math.unit('2 inch'), 'cm')             // returns Unit 5.08 cm
   *    math.to(math.unit('2 inch'), math.unit('cm'))  // returns Unit 5.08 cm
   *    math.to(math.unit(16, 'bytes'), 'bits')        // returns Unit 128 bits
   *
   * See also:
   *
   *    unit
   *
   * @param {Unit | Array | Matrix} x     The unit to be converted.
   * @param {Unit | Array | Matrix} unit  New unit. Can be a string like "cm"
   *                                      or a unit without value.
   * @return {Unit | Array | Matrix} value with changed, fixed unit.
   */
  return typed(name$2$, {
    'Unit, Unit | string': (x, unit) => x.to(unit)
  }, matrixAlgorithmSuite({
    Ds: true
  }));
});

var name$2_ = 'isPrime';
var dependencies$2_ = ['typed'];
var createIsPrime = /* #__PURE__ */factory(name$2_, dependencies$2_, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Test whether a value is prime: has no divisors other than itself and one.
   * The function supports type `number`, `bignumber`.
   *
   * The function is evaluated element-wise in case of Array or Matrix input.
   *
   * Syntax:
   *
   *     math.isPrime(x)
   *
   * Examples:
   *
   *    math.isPrime(3)                     // returns true
   *    math.isPrime(-2)                    // returns false
   *    math.isPrime(0)                     // returns false
   *    math.isPrime(-0)                    // returns false
   *    math.isPrime(0.5)                   // returns false
   *    math.isPrime('2')                   // returns true
   *    math.isPrime([2, 17, 100])           // returns [true, true, false]
   *
   * See also:
   *
   *    isNumeric, isZero, isNegative, isInteger
   *
   * @param {number | BigNumber | bigint | Array | Matrix} x  Value to be tested
   * @return {boolean}  Returns true when `x` is larger than zero.
   *                    Throws an error in case of an unknown data type.
   */
  return typed(name$2_, {
    number: function number(x) {
      if (x <= 3) {
        return x > 1;
      }
      if (x % 2 === 0 || x % 3 === 0) {
        return false;
      }
      for (var i = 5; i * i <= x; i += 6) {
        if (x % i === 0 || x % (i + 2) === 0) {
          return false;
        }
      }
      return true;
    },
    bigint: function bigint(x) {
      if (x <= 3n) {
        return x > 1n;
      }
      if (x % 2n === 0n || x % 3n === 0n) {
        return false;
      }
      for (var i = 5n; i * i <= x; i += 6n) {
        if (x % i === 0n || x % (i + 2n) === 0n) {
          return false;
        }
      }
      return true;
    },
    BigNumber: function BigNumber(n) {
      if (n.lte(3)) return n.gt(1);
      if (n.mod(2).eq(0) || n.mod(3).eq(0)) return false;
      if (n.lt(Math.pow(2, 32))) {
        var x = n.toNumber();
        for (var i = 5; i * i <= x; i += 6) {
          if (x % i === 0 || x % (i + 2) === 0) {
            return false;
          }
        }
        return true;
      }
      function modPow(base, exponent, modulus) {
        // exponent can be huge, use non-recursive variant
        var accumulator = 1;
        while (!exponent.eq(0)) {
          if (exponent.mod(2).eq(0)) {
            exponent = exponent.div(2);
            base = base.mul(base).mod(modulus);
          } else {
            exponent = exponent.sub(1);
            accumulator = base.mul(accumulator).mod(modulus);
          }
        }
        return accumulator;
      }

      // https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants
      var Decimal = n.constructor.clone({
        precision: n.toFixed(0).length * 2
      });
      n = new Decimal(n);
      var r = 0;
      var d = n.sub(1);
      while (d.mod(2).eq(0)) {
        d = d.div(2);
        r += 1;
      }
      var bases = null;
      // https://en.wikipedia.org/wiki/Miller–Rabin_primality_test#Testing_against_small_sets_of_bases
      if (n.lt('3317044064679887385961981')) {
        bases = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41].filter(x => x < n);
      } else {
        var max = Math.min(n.toNumber() - 2, Math.floor(2 * Math.pow(n.toFixed(0).length * Math.log(10), 2)));
        bases = [];
        for (var _i = 2; _i <= max; _i += 1) {
          bases.push(max);
        }
      }
      for (var _i2 = 0; _i2 < bases.length; _i2 += 1) {
        var a = bases[_i2];
        var adn = modPow(n.sub(n).add(a), d, n);
        if (!adn.eq(1)) {
          for (var _i3 = 0, _x = adn; !_x.eq(n.sub(1)); _i3 += 1, _x = _x.mul(_x).mod(n)) {
            if (_i3 === r - 1) {
              return false;
            }
          }
        }
      }
      return true;
    },
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$2Z = 'numeric';
var dependencies$2Z = ['number', '?bignumber', '?fraction'];
var createNumeric = /* #__PURE__ */factory(name$2Z, dependencies$2Z, _ref => {
  var {
    number: _number,
    bignumber,
    fraction
  } = _ref;
  var validInputTypes = {
    string: true,
    number: true,
    BigNumber: true,
    Fraction: true
  };

  // Load the conversion functions for each output type
  var validOutputTypes = {
    number: x => _number(x),
    BigNumber: bignumber ? x => bignumber(x) : noBignumber,
    bigint: x => BigInt(x),
    Fraction: fraction ? x => fraction(x) : noFraction
  };

  /**
   * Convert a numeric input to a specific numeric type: number, BigNumber, bigint, or Fraction.
   *
   * Syntax:
   *
   *    math.numeric(x)
   *
   * Examples:
   *
   *    math.numeric('4')                           // returns 4
   *    math.numeric('4', 'number')                 // returns 4
   *    math.numeric('4', 'bigint')                 // returns 4n
   *    math.numeric('4', 'BigNumber')              // returns BigNumber 4
   *    math.numeric('4', 'Fraction')               // returns Fraction 4
   *    math.numeric(4, 'Fraction')                 // returns Fraction 4
   *    math.numeric(math.fraction(2, 5), 'number') // returns 0.4
   *
   * See also:
   *
   *    number, fraction, bignumber, bigint, string, format
   *
   * @param {string | number | BigNumber | bigint | Fraction } value
   *              A numeric value or a string containing a numeric value
   * @param {string} outputType
   *              Desired numeric output type.
   *              Available values: 'number', 'BigNumber', or 'Fraction'
   * @return {number | BigNumber | bigint | Fraction}
   *              Returns an instance of the numeric in the requested type
   */
  return function numeric(value) {
    var outputType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'number';
    var check = arguments.length > 2 ? arguments[2] : undefined;
    if (check !== undefined) {
      throw new SyntaxError('numeric() takes one or two arguments');
    }
    var inputType = typeOf(value);
    if (!(inputType in validInputTypes)) {
      throw new TypeError('Cannot convert ' + value + ' of type "' + inputType + '"; valid input types are ' + Object.keys(validInputTypes).join(', '));
    }
    if (!(outputType in validOutputTypes)) {
      throw new TypeError('Cannot convert ' + value + ' to type "' + outputType + '"; valid output types are ' + Object.keys(validOutputTypes).join(', '));
    }
    if (outputType === inputType) {
      return value;
    } else {
      return validOutputTypes[outputType](value);
    }
  };
});

var name$2Y = 'divideScalar';
var dependencies$2Y = ['typed', 'numeric'];
var createDivideScalar = /* #__PURE__ */factory(name$2Y, dependencies$2Y, _ref => {
  var {
    typed,
    numeric
  } = _ref;
  /**
   * Divide two scalar values, `x / y`.
   * This function is meant for internal use: it is used by the public functions
   * `divide` and `inv`.
   *
   * This function does not support collections (Array or Matrix).
   *
   * @param  {number | BigNumber | bigint | Fraction | Complex | Unit} x   Numerator
   * @param  {number | BigNumber | bigint | Fraction | Complex} y          Denominator
   * @return {number | BigNumber | bigint | Fraction | Complex | Unit}     Quotient, `x / y`
   * @private
   */
  return typed(name$2Y, {
    'number, number': function numberNumber(x, y) {
      return x / y;
    },
    'Complex, Complex': function ComplexComplex(x, y) {
      return x.div(y);
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      return x.div(y);
    },
    'bigint, bigint': function bigintBigint(x, y) {
      return x / y;
    },
    'Fraction, Fraction': function FractionFraction(x, y) {
      return x.div(y);
    },
    'Unit, number | Complex | Fraction | BigNumber | Unit': (x, y) => x.divide(y),
    'number | Fraction | Complex | BigNumber, Unit': (x, y) => y.divideInto(x)
  });
});

var name$2X = 'pow';
var dependencies$2X = ['typed', 'config', 'identity', 'multiply', 'matrix', 'inv', 'fraction', 'number', 'Complex'];
var createPow = /* #__PURE__ */factory(name$2X, dependencies$2X, _ref => {
  var {
    typed,
    config,
    identity,
    multiply,
    matrix,
    inv,
    number,
    fraction,
    Complex
  } = _ref;
  /**
   * Calculates the power of x to y, `x ^ y`.
   *
   * Matrix exponentiation is supported for square matrices `x` and integers `y`:
   * when `y` is nonnegative, `x` may be any square matrix; and when `y` is
   * negative, `x` must be invertible, and then this function returns
   * inv(x)^(-y).
   *
   * For cubic roots of negative numbers, the function returns the principal
   * root by default. In order to let the function return the real root,
   * math.js can be configured with `math.config({predictable: true})`.
   * To retrieve all cubic roots of a value, use `math.cbrt(x, true)`.
   *
   * Syntax:
   *
   *    math.pow(x, y)
   *
   * Examples:
   *
   *    math.pow(2, 3)               // returns number 8
   *
   *    const a = math.complex(2, 3)
   *    math.pow(a, 2)                // returns Complex -5 + 12i
   *
   *    const b = [[1, 2], [4, 3]]
   *    math.pow(b, 2)               // returns Array [[9, 8], [16, 17]]
   *
   *    const c = [[1, 2], [4, 3]]
   *    math.pow(c, -1)               // returns Array [[-0.6, 0.4], [0.8, -0.2]]
   *
   * See also:
   *
   *    multiply, sqrt, cbrt, nthRoot
   *
   * @param  {number | BigNumber | bigint | Complex | Unit | Array | Matrix} x  The base
   * @param  {number | BigNumber | bigint | Complex} y                          The exponent
   * @return {number | BigNumber | bigint | Complex | Array | Matrix} The value of `x` to the power `y`
   */
  return typed(name$2X, {
    'number, number': _pow,
    'Complex, Complex': function ComplexComplex(x, y) {
      return x.pow(y);
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      if (y.isInteger() || x >= 0 || config.predictable) {
        return x.pow(y);
      } else {
        return new Complex(x.toNumber(), 0).pow(y.toNumber(), 0);
      }
    },
    'bigint, bigint': (x, y) => x ** y,
    'Fraction, Fraction': function FractionFraction(x, y) {
      var result = x.pow(y);
      if (result != null) {
        return result;
      }
      if (config.predictable) {
        throw new Error('Result of pow is non-rational and cannot be expressed as a fraction');
      } else {
        return _pow(x.valueOf(), y.valueOf());
      }
    },
    'Array, number': _powArray,
    'Array, BigNumber': function ArrayBigNumber(x, y) {
      return _powArray(x, y.toNumber());
    },
    'Matrix, number': _powMatrix,
    'Matrix, BigNumber': function MatrixBigNumber(x, y) {
      return _powMatrix(x, y.toNumber());
    },
    'Unit, number | BigNumber': function UnitNumberBigNumber(x, y) {
      return x.pow(y);
    }
  });

  /**
   * Calculates the power of x to y, x^y, for two numbers.
   * @param {number} x
   * @param {number} y
   * @return {number | Complex} res
   * @private
   */
  function _pow(x, y) {
    // Alternatively could define a 'realmode' config option or something, but
    // 'predictable' will work for now
    if (config.predictable && !isInteger(y) && x < 0) {
      // Check to see if y can be represented as a fraction
      try {
        var yFrac = fraction(y);
        var yNum = number(yFrac);
        if (y === yNum || Math.abs((y - yNum) / y) < 1e-14) {
          if (yFrac.d % 2 === 1) {
            return (yFrac.n % 2 === 0 ? 1 : -1) * Math.pow(-x, y);
          }
        }
      } catch (ex) {
        // fraction() throws an error if y is Infinity, etc.
      }

      // Unable to express y as a fraction, so continue on
    }

    // **for predictable mode** x^Infinity === NaN if x < -1
    // N.B. this behavour is different from `Math.pow` which gives
    // (-2)^Infinity === Infinity
    if (config.predictable && (x < -1 && y === Infinity || x > -1 && x < 0 && y === -Infinity)) {
      return NaN;
    }
    if (isInteger(y) || x >= 0 || config.predictable) {
      return powNumber(x, y);
    } else {
      // TODO: the following infinity checks are duplicated from powNumber. Deduplicate this somehow

      // x^Infinity === 0 if -1 < x < 1
      // A real number 0 is returned instead of complex(0)
      if (x * x < 1 && y === Infinity || x * x > 1 && y === -Infinity) {
        return 0;
      }
      return new Complex(x, 0).pow(y, 0);
    }
  }

  /**
   * Calculate the power of a 2d array
   * @param {Array} x     must be a 2 dimensional, square matrix
   * @param {number} y    a integer value (positive if `x` is not invertible)
   * @returns {Array}
   * @private
   */
  function _powArray(x, y) {
    if (!isInteger(y)) {
      throw new TypeError('For A^b, b must be an integer (value is ' + y + ')');
    }
    // verify that A is a 2 dimensional square matrix
    var s = arraySize(x);
    if (s.length !== 2) {
      throw new Error('For A^b, A must be 2 dimensional (A has ' + s.length + ' dimensions)');
    }
    if (s[0] !== s[1]) {
      throw new Error('For A^b, A must be square (size is ' + s[0] + 'x' + s[1] + ')');
    }
    if (y < 0) {
      try {
        return _powArray(inv(x), -y);
      } catch (error) {
        if (error.message === 'Cannot calculate inverse, determinant is zero') {
          throw new TypeError('For A^b, when A is not invertible, b must be a positive integer (value is ' + y + ')');
        }
        throw error;
      }
    }
    var res = identity(s[0]).valueOf();
    var px = x;
    while (y >= 1) {
      if ((y & 1) === 1) {
        res = multiply(px, res);
      }
      y >>= 1;
      px = multiply(px, px);
    }
    return res;
  }

  /**
   * Calculate the power of a 2d matrix
   * @param {Matrix} x     must be a 2 dimensional, square matrix
   * @param {number} y    a positive, integer value
   * @returns {Matrix}
   * @private
   */
  function _powMatrix(x, y) {
    return matrix(_powArray(x.valueOf(), y));
  }
});

var NO_INT = 'Number of decimals in function round must be an integer';
var name$2W = 'round';
var dependencies$2W = ['typed', 'config', 'matrix', 'equalScalar', 'zeros', 'BigNumber', 'DenseMatrix'];
var createRound = /* #__PURE__ */factory(name$2W, dependencies$2W, _ref => {
  var {
    typed,
    config,
    matrix,
    equalScalar,
    zeros,
    BigNumber: _BigNumber,
    DenseMatrix
  } = _ref;
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matAlgo14xDs = createMatAlgo14xDs({
    typed
  });
  function toExponent(epsilon) {
    return Math.abs(splitNumber(epsilon).exponent);
  }

  /**
   * Round a value towards the nearest rounded value.
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.round(x)
   *    math.round(x, n)
   *    math.round(unit, valuelessUnit)
   *    math.round(unit, n, valuelessUnit)
   *
   * Examples:
   *
   *    math.round(3.22)             // returns number 3
   *    math.round(3.82)             // returns number 4
   *    math.round(-4.2)             // returns number -4
   *    math.round(-4.7)             // returns number -5
   *    math.round(3.22, 1)          // returns number 3.2
   *    math.round(3.88, 1)          // returns number 3.9
   *    math.round(-4.21, 1)         // returns number -4.2
   *    math.round(-4.71, 1)         // returns number -4.7
   *    math.round(math.pi, 3)       // returns number 3.142
   *    math.round(123.45678, 2)     // returns number 123.46
   *
   *    const c = math.complex(3.2, -2.7)
   *    math.round(c)                // returns Complex 3 - 3i
   *
   *    const unit = math.unit('3.241 cm')
   *    const cm = math.unit('cm')
   *    const mm = math.unit('mm')
   *    math.round(unit, 1, cm)      // returns Unit 3.2 cm
   *    math.round(unit, 1, mm)      // returns Unit 32.4 mm
   *
   *    math.round([3.2, 3.8, -4.7]) // returns Array [3, 4, -5]
   *
   * See also:
   *
   *    ceil, fix, floor
   *
   * @param  {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x  Value to be rounded
   * @param  {number | BigNumber | Array} [n=0]                            Number of decimals
   * @param  {Unit} [valuelessUnit]                                        A valueless unit
   * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
   */
  return typed(name$2W, {
    number: function number(x) {
      // Handle round off errors by first rounding to relTol precision
      var xEpsilon = roundNumber(x, toExponent(config.relTol));
      var xSelected = nearlyEqual$1(x, xEpsilon, config.relTol, config.absTol) ? xEpsilon : x;
      return roundNumber(xSelected);
    },
    'number, number': function numberNumber(x, n) {
      // Same as number: unless user specifies more decimals than relTol
      var epsilonExponent = toExponent(config.relTol);
      if (n >= epsilonExponent) {
        return roundNumber(x, n);
      }
      var xEpsilon = roundNumber(x, epsilonExponent);
      var xSelected = nearlyEqual$1(x, xEpsilon, config.relTol, config.absTol) ? xEpsilon : x;
      return roundNumber(xSelected, n);
    },
    'number, BigNumber': function numberBigNumber(x, n) {
      if (!n.isInteger()) {
        throw new TypeError(NO_INT);
      }
      return new _BigNumber(x).toDecimalPlaces(n.toNumber());
    },
    Complex: function Complex(x) {
      return x.round();
    },
    'Complex, number': function ComplexNumber(x, n) {
      if (n % 1) {
        throw new TypeError(NO_INT);
      }
      return x.round(n);
    },
    'Complex, BigNumber': function ComplexBigNumber(x, n) {
      if (!n.isInteger()) {
        throw new TypeError(NO_INT);
      }
      var _n = n.toNumber();
      return x.round(_n);
    },
    BigNumber: function BigNumber(x) {
      // Handle round off errors by first rounding to relTol precision
      var xEpsilon = new _BigNumber(x).toDecimalPlaces(toExponent(config.relTol));
      var xSelected = nearlyEqual(x, xEpsilon, config.relTol, config.absTol) ? xEpsilon : x;
      return xSelected.toDecimalPlaces(0);
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(x, n) {
      if (!n.isInteger()) {
        throw new TypeError(NO_INT);
      }

      // Same as BigNumber: unless user specifies more decimals than relTol
      var epsilonExponent = toExponent(config.relTol);
      if (n >= epsilonExponent) {
        return x.toDecimalPlaces(n.toNumber());
      }
      var xEpsilon = x.toDecimalPlaces(epsilonExponent);
      var xSelected = nearlyEqual(x, xEpsilon, config.relTol, config.absTol) ? xEpsilon : x;
      return xSelected.toDecimalPlaces(n.toNumber());
    },
    Fraction: function Fraction(x) {
      return x.round();
    },
    'Fraction, number': function FractionNumber(x, n) {
      if (n % 1) {
        throw new TypeError(NO_INT);
      }
      return x.round(n);
    },
    'Fraction, BigNumber': function FractionBigNumber(x, n) {
      if (!n.isInteger()) {
        throw new TypeError(NO_INT);
      }
      return x.round(n.toNumber());
    },
    'Unit, number, Unit': typed.referToSelf(self => function (x, n, unit) {
      var valueless = x.toNumeric(unit);
      return unit.multiply(self(valueless, n));
    }),
    'Unit, BigNumber, Unit': typed.referToSelf(self => (x, n, unit) => self(x, n.toNumber(), unit)),
    'Unit, Unit': typed.referToSelf(self => (x, unit) => self(x, 0, unit)),
    'Array | Matrix, number, Unit': typed.referToSelf(self => (x, n, unit) => {
      // deep map collection, skip zeros since round(0) = 0
      return deepMap(x, value => self(value, n, unit));
    }),
    'Array | Matrix, BigNumber, Unit': typed.referToSelf(self => (x, n, unit) => self(x, n.toNumber(), unit)),
    'Array | Matrix, Unit': typed.referToSelf(self => (x, unit) => self(x, 0, unit)),
    'Array | Matrix': typed.referToSelf(self => x => {
      // deep map collection, skip zeros since round(0) = 0
      return deepMap(x, self);
    }),
    'SparseMatrix, number | BigNumber': typed.referToSelf(self => (x, n) => {
      return matAlgo11xS0s(x, n, self, false);
    }),
    'DenseMatrix, number | BigNumber': typed.referToSelf(self => (x, n) => {
      return matAlgo14xDs(x, n, self, false);
    }),
    'Array, number | BigNumber': typed.referToSelf(self => (x, n) => {
      // use matrix implementation
      return matAlgo14xDs(matrix(x), n, self, false).valueOf();
    }),
    'number | Complex | BigNumber | Fraction, SparseMatrix': typed.referToSelf(self => (x, n) => {
      // check scalar is zero
      if (equalScalar(x, 0)) {
        // do not execute algorithm, result will be a zero matrix
        return zeros(n.size(), n.storage());
      }
      return matAlgo12xSfs(n, x, self, true);
    }),
    'number | Complex | BigNumber | Fraction, DenseMatrix': typed.referToSelf(self => (x, n) => {
      // check scalar is zero
      if (equalScalar(x, 0)) {
        // do not execute algorithm, result will be a zero matrix
        return zeros(n.size(), n.storage());
      }
      return matAlgo14xDs(n, x, self, true);
    }),
    'number | Complex | BigNumber | Fraction, Array': typed.referToSelf(self => (x, n) => {
      // use matrix implementation
      return matAlgo14xDs(matrix(n), x, self, true).valueOf();
    })
  });
});

var name$2V = 'log';
var dependencies$2V = ['config', 'typed', 'divideScalar', 'Complex'];
var createLog = /* #__PURE__ */factory(name$2V, dependencies$2V, _ref => {
  var {
    typed,
    config,
    divideScalar,
    Complex
  } = _ref;
  /**
   * Calculate the logarithm of a value.
   *
   * To avoid confusion with the matrix logarithm, this function does not
   * apply to matrices.
   *
   * Syntax:
   *
   *    math.log(x)
   *    math.log(x, base)
   *
   * Examples:
   *
   *    math.log(3.5)                  // returns 1.252762968495368
   *    math.exp(math.log(2.4))        // returns 2.4
   *
   *    math.pow(10, 4)                // returns 10000
   *    math.log(10000, 10)            // returns 4
   *    math.log(10000) / math.log(10) // returns 4
   *
   *    math.log(1024, 2)              // returns 10
   *    math.pow(2, 10)                // returns 1024
   *
   * See also:
   *
   *    exp, log2, log10, log1p
   *
   * @param {number | BigNumber | Complex} x
   *            Value for which to calculate the logarithm.
   * @param {number | BigNumber | Complex} [base=e]
   *            Optional base for the logarithm. If not provided, the natural
   *            logarithm of `x` is calculated.
   * @return {number | BigNumber | Complex}
   *            Returns the logarithm of `x`
   */
  return typed(name$2V, {
    number: function number(x) {
      if (x >= 0 || config.predictable) {
        return logNumber(x);
      } else {
        // negative value -> complex value computation
        return new Complex(x, 0).log();
      }
    },
    Complex: function Complex(x) {
      return x.log();
    },
    BigNumber: function BigNumber(x) {
      if (!x.isNegative() || config.predictable) {
        return x.ln();
      } else {
        // downgrade to number, return Complex valued result
        return new Complex(x.toNumber(), 0).log();
      }
    },
    'any, any': typed.referToSelf(self => (x, base) => {
      // calculate logarithm for a specified base, log(x, base)
      return divideScalar(self(x), self(base));
    })
  });
});

var name$2U = 'log1p';
var dependencies$2U = ['typed', 'config', 'divideScalar', 'log', 'Complex'];
var createLog1p = /* #__PURE__ */factory(name$2U, dependencies$2U, _ref => {
  var {
    typed,
    config,
    divideScalar,
    log,
    Complex
  } = _ref;
  /**
   * Calculate the logarithm of a `value+1`.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.log1p(x)
   *    math.log1p(x, base)
   *
   * Examples:
   *
   *    math.log1p(2.5)                 // returns 1.252762968495368
   *    math.exp(math.log1p(1.4))       // returns 2.4
   *
   *    math.pow(10, 4)                 // returns 10000
   *    math.log1p(9999, 10)            // returns 4
   *    math.log1p(9999) / math.log(10) // returns 4
   *
   * See also:
   *
   *    exp, log, log2, log10
   *
   * @param {number | BigNumber | Complex | Array | Matrix} x
   *            Value for which to calculate the logarithm of `x+1`.
   * @param {number | BigNumber | Complex} [base=e]
   *            Optional base for the logarithm. If not provided, the natural
   *            logarithm of `x+1` is calculated.
   * @return {number | BigNumber | Complex | Array | Matrix}
   *            Returns the logarithm of `x+1`
   */
  return typed(name$2U, {
    number: function number(x) {
      if (x >= -1 || config.predictable) {
        return log1p(x);
      } else {
        // negative value -> complex value computation
        return _log1pComplex(new Complex(x, 0));
      }
    },
    Complex: _log1pComplex,
    BigNumber: function BigNumber(x) {
      var y = x.plus(1);
      if (!y.isNegative() || config.predictable) {
        return y.ln();
      } else {
        // downgrade to number, return Complex valued result
        return _log1pComplex(new Complex(x.toNumber(), 0));
      }
    },
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self)),
    'any, any': typed.referToSelf(self => (x, base) => {
      // calculate logarithm for a specified base, log1p(x, base)
      return divideScalar(self(x), log(base));
    })
  });

  /**
   * Calculate the natural logarithm of a complex number + 1
   * @param {Complex} x
   * @returns {Complex}
   * @private
   */
  function _log1pComplex(x) {
    var xRe1p = x.re + 1;
    return new Complex(Math.log(Math.sqrt(xRe1p * xRe1p + x.im * x.im)), Math.atan2(x.im, xRe1p));
  }
});

var name$2T = 'nthRoots';
var dependencies$2T = ['config', 'typed', 'divideScalar', 'Complex'];
var createNthRoots = /* #__PURE__ */factory(name$2T, dependencies$2T, _ref => {
  var {
    typed,
    config,
    divideScalar,
    Complex
  } = _ref;
  /**
   * Each function here returns a real multiple of i as a Complex value.
   * @param  {number} val
   * @return {Complex} val, i*val, -val or -i*val for index 0, 1, 2, 3
   */
  // This is used to fix float artifacts for zero-valued components.
  var _calculateExactResult = [function realPos(val) {
    return new Complex(val, 0);
  }, function imagPos(val) {
    return new Complex(0, val);
  }, function realNeg(val) {
    return new Complex(-val, 0);
  }, function imagNeg(val) {
    return new Complex(0, -val);
  }];

  /**
   * Calculate the nth root of a Complex Number a using De Movire's Theorem.
   * @param  {Complex} a
   * @param  {number} root
   * @return {Array} array of n Complex Roots
   */
  function _nthComplexRoots(a, root) {
    if (root < 0) throw new Error('Root must be greater than zero');
    if (root === 0) throw new Error('Root must be non-zero');
    if (root % 1 !== 0) throw new Error('Root must be an integer');
    if (a === 0 || a.abs() === 0) return [new Complex(0, 0)];
    var aIsNumeric = typeof a === 'number';
    var offset;
    // determine the offset (argument of a)/(pi/2)
    if (aIsNumeric || a.re === 0 || a.im === 0) {
      if (aIsNumeric) {
        offset = 2 * +(a < 0); // numeric value on the real axis
      } else if (a.im === 0) {
        offset = 2 * +(a.re < 0); // complex value on the real axis
      } else {
        offset = 2 * +(a.im < 0) + 1; // complex value on the imaginary axis
      }
    }
    var arg = a.arg();
    var abs = a.abs();
    var roots = [];
    var r = Math.pow(abs, 1 / root);
    for (var k = 0; k < root; k++) {
      var halfPiFactor = (offset + 4 * k) / root;
      /**
       * If (offset + 4*k)/root is an integral multiple of pi/2
       * then we can produce a more exact result.
       */
      if (halfPiFactor === Math.round(halfPiFactor)) {
        roots.push(_calculateExactResult[halfPiFactor % 4](r));
        continue;
      }
      roots.push(new Complex({
        r,
        phi: (arg + 2 * Math.PI * k) / root
      }));
    }
    return roots;
  }

  /**
   * Calculate the nth roots of a value.
   * An nth root of a positive real number A,
   * is a positive real solution of the equation "x^root = A".
   * This function returns an array of complex values.
   *
   * Syntax:
   *
   *    math.nthRoots(x)
   *    math.nthRoots(x, root)
   *
   * Examples:
   *
   *    math.nthRoots(1)
   *    // returns [
   *    //   {re: 1, im: 0},
   *    //   {re: -1, im: 0}
   *    // ]
   *    math.nthRoots(1, 3)
   *    // returns [
   *    //   { re: 1, im: 0 },
   *    //   { re: -0.4999999999999998, im: 0.8660254037844387 },
   *    //   { re: -0.5000000000000004, im: -0.8660254037844385 }
   *    // ]
   *
   * See also:
   *
   *    nthRoot, pow, sqrt
   *
   * @param {number | BigNumber | Fraction | Complex} x Number to be rounded
   * @param {number} [root=2] Optional root, default value is 2
   * @return {number | BigNumber | Fraction | Complex} Returns the nth roots
   */
  return typed(name$2T, {
    Complex: function Complex(x) {
      return _nthComplexRoots(x, 2);
    },
    'Complex, number': _nthComplexRoots
  });
});

var name$2S = 'dotPow';
var dependencies$2S = ['typed', 'equalScalar', 'matrix', 'pow', 'DenseMatrix', 'concat'];
var createDotPow = /* #__PURE__ */factory(name$2S, dependencies$2S, _ref => {
  var {
    typed,
    equalScalar,
    matrix,
    pow,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo07xSSf = createMatAlgo07xSSf({
    typed,
    DenseMatrix
  });
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });
  var powScalarSignatures = {};
  for (var signature in pow.signatures) {
    if (Object.prototype.hasOwnProperty.call(pow.signatures, signature)) {
      if (!signature.includes('Matrix') && !signature.includes('Array')) {
        powScalarSignatures[signature] = pow.signatures[signature];
      }
    }
  }
  var powScalar = typed(powScalarSignatures);

  /**
   * Calculates the power of x to y element wise.
   *
   * Syntax:
   *
   *    math.dotPow(x, y)
   *
   * Examples:
   *
   *    math.dotPow(2, 3)            // returns number 8
   *
   *    const a = [[1, 2], [4, 3]]
   *    math.dotPow(a, 2)            // returns Array [[1, 4], [16, 9]]
   *    math.pow(a, 2)               // returns Array [[9, 8], [16, 17]]
   *
   * See also:
   *
   *    pow, sqrt, multiply
   *
   * @param  {number | BigNumber | Complex | Unit | Array | Matrix} x  The base
   * @param  {number | BigNumber | Complex | Unit | Array | Matrix} y  The exponent
   * @return {number | BigNumber | Complex | Unit | Array | Matrix}                     The value of `x` to the power `y`
   */
  return typed(name$2S, matrixAlgorithmSuite({
    elop: powScalar,
    SS: matAlgo07xSSf,
    DS: matAlgo03xDSf,
    Ss: matAlgo11xS0s,
    sS: matAlgo12xSfs
  }));
});

var name$2R = 'dotDivide';
var dependencies$2R = ['typed', 'matrix', 'equalScalar', 'divideScalar', 'DenseMatrix', 'concat'];
var createDotDivide = /* #__PURE__ */factory(name$2R, dependencies$2R, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    divideScalar,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo02xDS0 = createMatAlgo02xDS0({
    typed,
    equalScalar
  });
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo07xSSf = createMatAlgo07xSSf({
    typed,
    DenseMatrix
  });
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Divide two matrices element wise. The function accepts both matrices and
   * scalar values.
   *
   * Syntax:
   *
   *    math.dotDivide(x, y)
   *
   * Examples:
   *
   *    math.dotDivide(2, 4)   // returns 0.5
   *
   *    a = [[9, 5], [6, 1]]
   *    b = [[3, 2], [5, 2]]
   *
   *    math.dotDivide(a, b)   // returns [[3, 2.5], [1.2, 0.5]]
   *    math.divide(a, b)      // returns [[1.75, 0.75], [-1.75, 2.25]]
   *
   * See also:
   *
   *    divide, multiply, dotMultiply
   *
   * @param  {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Numerator
   * @param  {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Denominator
   * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix}                    Quotient, `x ./ y`
   */
  return typed(name$2R, matrixAlgorithmSuite({
    elop: divideScalar,
    SS: matAlgo07xSSf,
    DS: matAlgo03xDSf,
    SD: matAlgo02xDS0,
    Ss: matAlgo11xS0s,
    sS: matAlgo12xSfs
  }));
});

function createSolveValidation(_ref) {
  var {
    DenseMatrix
  } = _ref;
  /**
   * Validates matrix and column vector b for backward/forward substitution algorithms.
   *
   * @param {Matrix} m            An N x N matrix
   * @param {Array | Matrix} b    A column vector
   * @param {Boolean} copy        Return a copy of vector b
   *
   * @return {DenseMatrix}        Dense column vector b
   */
  return function solveValidation(m, b, copy) {
    var mSize = m.size();
    if (mSize.length !== 2) {
      throw new RangeError('Matrix must be two dimensional (size: ' + format(mSize) + ')');
    }
    var rows = mSize[0];
    var columns = mSize[1];
    if (rows !== columns) {
      throw new RangeError('Matrix must be square (size: ' + format(mSize) + ')');
    }
    var data = [];
    if (isMatrix(b)) {
      var bSize = b.size();
      var bdata = b._data;

      // 1-dim vector
      if (bSize.length === 1) {
        if (bSize[0] !== rows) {
          throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
        }
        for (var i = 0; i < rows; i++) {
          data[i] = [bdata[i]];
        }
        return new DenseMatrix({
          data,
          size: [rows, 1],
          datatype: b._datatype
        });
      }

      // 2-dim column
      if (bSize.length === 2) {
        if (bSize[0] !== rows || bSize[1] !== 1) {
          throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
        }
        if (isDenseMatrix(b)) {
          if (copy) {
            data = [];
            for (var _i = 0; _i < rows; _i++) {
              data[_i] = [bdata[_i][0]];
            }
            return new DenseMatrix({
              data,
              size: [rows, 1],
              datatype: b._datatype
            });
          }
          return b;
        }
        if (isSparseMatrix(b)) {
          for (var _i2 = 0; _i2 < rows; _i2++) {
            data[_i2] = [0];
          }
          var values = b._values;
          var index = b._index;
          var ptr = b._ptr;
          for (var k1 = ptr[1], k = ptr[0]; k < k1; k++) {
            var _i3 = index[k];
            data[_i3][0] = values[k];
          }
          return new DenseMatrix({
            data,
            size: [rows, 1],
            datatype: b._datatype
          });
        }
      }
      throw new RangeError('Dimension mismatch. The right side has to be either 1- or 2-dimensional vector.');
    }
    if (isArray(b)) {
      var bsize = arraySize(b);
      if (bsize.length === 1) {
        if (bsize[0] !== rows) {
          throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
        }
        for (var _i4 = 0; _i4 < rows; _i4++) {
          data[_i4] = [b[_i4]];
        }
        return new DenseMatrix({
          data,
          size: [rows, 1]
        });
      }
      if (bsize.length === 2) {
        if (bsize[0] !== rows || bsize[1] !== 1) {
          throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
        }
        for (var _i5 = 0; _i5 < rows; _i5++) {
          data[_i5] = [b[_i5][0]];
        }
        return new DenseMatrix({
          data,
          size: [rows, 1]
        });
      }
      throw new RangeError('Dimension mismatch. The right side has to be either 1- or 2-dimensional vector.');
    }
  };
}

var name$2Q = 'lsolve';
var dependencies$2Q = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'equalScalar', 'DenseMatrix'];
var createLsolve = /* #__PURE__ */factory(name$2Q, dependencies$2Q, _ref => {
  var {
    typed,
    matrix,
    divideScalar,
    multiplyScalar,
    subtractScalar,
    equalScalar,
    DenseMatrix
  } = _ref;
  var solveValidation = createSolveValidation({
    DenseMatrix
  });

  /**
   * Finds one solution of a linear equation system by forwards substitution. Matrix must be a lower triangular matrix. Throws an error if there's no solution.
   *
   * `L * x = b`
   *
   * Syntax:
   *
   *    math.lsolve(L, b)
   *
   * Examples:
   *
   *    const a = [[-2, 3], [2, 1]]
   *    const b = [11, 9]
   *    const x = lsolve(a, b)  // [[-5.5], [20]]
   *
   * See also:
   *
   *    lsolveAll, lup, slu, usolve, lusolve
   *
   * @param {Matrix, Array} L       A N x N matrix or array (L)
   * @param {Matrix, Array} b       A column vector with the b values
   *
   * @return {DenseMatrix | Array}  A column vector with the linear system solution (x)
   */
  return typed(name$2Q, {
    'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(m, b) {
      return _sparseForwardSubstitution(m, b);
    },
    'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(m, b) {
      return _denseForwardSubstitution(m, b);
    },
    'Array, Array | Matrix': function ArrayArrayMatrix(a, b) {
      var m = matrix(a);
      var r = _denseForwardSubstitution(m, b);
      return r.valueOf();
    }
  });
  function _denseForwardSubstitution(m, b) {
    // validate matrix and vector, return copy of column vector b
    b = solveValidation(m, b, true);
    var bdata = b._data;
    var rows = m._size[0];
    var columns = m._size[1];

    // result
    var x = [];
    var mdata = m._data;

    // loop columns
    for (var j = 0; j < columns; j++) {
      var bj = bdata[j][0] || 0;
      var xj = void 0;
      if (!equalScalar(bj, 0)) {
        // non-degenerate row, find solution

        var vjj = mdata[j][j];
        if (equalScalar(vjj, 0)) {
          throw new Error('Linear system cannot be solved since matrix is singular');
        }
        xj = divideScalar(bj, vjj);

        // loop rows
        for (var i = j + 1; i < rows; i++) {
          bdata[i] = [subtractScalar(bdata[i][0] || 0, multiplyScalar(xj, mdata[i][j]))];
        }
      } else {
        // degenerate row, we can choose any value
        xj = 0;
      }
      x[j] = [xj];
    }
    return new DenseMatrix({
      data: x,
      size: [rows, 1]
    });
  }
  function _sparseForwardSubstitution(m, b) {
    // validate matrix and vector, return copy of column vector b
    b = solveValidation(m, b, true);
    var bdata = b._data;
    var rows = m._size[0];
    var columns = m._size[1];
    var values = m._values;
    var index = m._index;
    var ptr = m._ptr;

    // result
    var x = [];

    // loop columns
    for (var j = 0; j < columns; j++) {
      var bj = bdata[j][0] || 0;
      if (!equalScalar(bj, 0)) {
        // non-degenerate row, find solution

        var vjj = 0;
        // matrix values & indices (column j)
        var jValues = [];
        var jIndices = [];

        // first and last index in the column
        var firstIndex = ptr[j];
        var lastIndex = ptr[j + 1];

        // values in column, find value at [j, j]
        for (var k = firstIndex; k < lastIndex; k++) {
          var i = index[k];

          // check row (rows are not sorted!)
          if (i === j) {
            vjj = values[k];
          } else if (i > j) {
            // store lower triangular
            jValues.push(values[k]);
            jIndices.push(i);
          }
        }

        // at this point we must have a value in vjj
        if (equalScalar(vjj, 0)) {
          throw new Error('Linear system cannot be solved since matrix is singular');
        }
        var xj = divideScalar(bj, vjj);
        for (var _k = 0, l = jIndices.length; _k < l; _k++) {
          var _i = jIndices[_k];
          bdata[_i] = [subtractScalar(bdata[_i][0] || 0, multiplyScalar(xj, jValues[_k]))];
        }
        x[j] = [xj];
      } else {
        // degenerate row, we can choose any value
        x[j] = [0];
      }
    }
    return new DenseMatrix({
      data: x,
      size: [rows, 1]
    });
  }
});

var name$2P = 'usolve';
var dependencies$2P = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'equalScalar', 'DenseMatrix'];
var createUsolve = /* #__PURE__ */factory(name$2P, dependencies$2P, _ref => {
  var {
    typed,
    matrix,
    divideScalar,
    multiplyScalar,
    subtractScalar,
    equalScalar,
    DenseMatrix
  } = _ref;
  var solveValidation = createSolveValidation({
    DenseMatrix
  });

  /**
   * Finds one solution of a linear equation system by backward substitution. Matrix must be an upper triangular matrix. Throws an error if there's no solution.
   *
   * `U * x = b`
   *
   * Syntax:
   *
   *    math.usolve(U, b)
   *
   * Examples:
   *
   *    const a = [[-2, 3], [2, 1]]
   *    const b = [11, 9]
   *    const x = usolve(a, b)  // [[8], [9]]
   *
   * See also:
   *
   *    usolveAll, lup, slu, usolve, lusolve
   *
   * @param {Matrix, Array} U       A N x N matrix or array (U)
   * @param {Matrix, Array} b       A column vector with the b values
   *
   * @return {DenseMatrix | Array}  A column vector with the linear system solution (x)
   */
  return typed(name$2P, {
    'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(m, b) {
      return _sparseBackwardSubstitution(m, b);
    },
    'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(m, b) {
      return _denseBackwardSubstitution(m, b);
    },
    'Array, Array | Matrix': function ArrayArrayMatrix(a, b) {
      var m = matrix(a);
      var r = _denseBackwardSubstitution(m, b);
      return r.valueOf();
    }
  });
  function _denseBackwardSubstitution(m, b) {
    // make b into a column vector
    b = solveValidation(m, b, true);
    var bdata = b._data;
    var rows = m._size[0];
    var columns = m._size[1];

    // result
    var x = [];
    var mdata = m._data;
    // loop columns backwards
    for (var j = columns - 1; j >= 0; j--) {
      // b[j]
      var bj = bdata[j][0] || 0;
      // x[j]
      var xj = void 0;
      if (!equalScalar(bj, 0)) {
        // value at [j, j]
        var vjj = mdata[j][j];
        if (equalScalar(vjj, 0)) {
          // system cannot be solved
          throw new Error('Linear system cannot be solved since matrix is singular');
        }
        xj = divideScalar(bj, vjj);

        // loop rows
        for (var i = j - 1; i >= 0; i--) {
          // update copy of b
          bdata[i] = [subtractScalar(bdata[i][0] || 0, multiplyScalar(xj, mdata[i][j]))];
        }
      } else {
        // zero value at j
        xj = 0;
      }
      // update x
      x[j] = [xj];
    }
    return new DenseMatrix({
      data: x,
      size: [rows, 1]
    });
  }
  function _sparseBackwardSubstitution(m, b) {
    // make b into a column vector
    b = solveValidation(m, b, true);
    var bdata = b._data;
    var rows = m._size[0];
    var columns = m._size[1];
    var values = m._values;
    var index = m._index;
    var ptr = m._ptr;

    // result
    var x = [];

    // loop columns backwards
    for (var j = columns - 1; j >= 0; j--) {
      var bj = bdata[j][0] || 0;
      if (!equalScalar(bj, 0)) {
        // non-degenerate row, find solution

        var vjj = 0;

        // upper triangular matrix values & index (column j)
        var jValues = [];
        var jIndices = [];

        // first & last indeces in column
        var firstIndex = ptr[j];
        var lastIndex = ptr[j + 1];

        // values in column, find value at [j, j], loop backwards
        for (var k = lastIndex - 1; k >= firstIndex; k--) {
          var i = index[k];

          // check row (rows are not sorted!)
          if (i === j) {
            vjj = values[k];
          } else if (i < j) {
            // store upper triangular
            jValues.push(values[k]);
            jIndices.push(i);
          }
        }

        // at this point we must have a value in vjj
        if (equalScalar(vjj, 0)) {
          throw new Error('Linear system cannot be solved since matrix is singular');
        }
        var xj = divideScalar(bj, vjj);
        for (var _k = 0, _lastIndex = jIndices.length; _k < _lastIndex; _k++) {
          var _i = jIndices[_k];
          bdata[_i] = [subtractScalar(bdata[_i][0], multiplyScalar(xj, jValues[_k]))];
        }
        x[j] = [xj];
      } else {
        // degenerate row, we can choose any value
        x[j] = [0];
      }
    }
    return new DenseMatrix({
      data: x,
      size: [rows, 1]
    });
  }
});

var name$2O = 'lsolveAll';
var dependencies$2O = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'equalScalar', 'DenseMatrix'];
var createLsolveAll = /* #__PURE__ */factory(name$2O, dependencies$2O, _ref => {
  var {
    typed,
    matrix,
    divideScalar,
    multiplyScalar,
    subtractScalar,
    equalScalar,
    DenseMatrix
  } = _ref;
  var solveValidation = createSolveValidation({
    DenseMatrix
  });

  /**
   * Finds all solutions of a linear equation system by forwards substitution. Matrix must be a lower triangular matrix.
   *
   * `L * x = b`
   *
   * Syntax:
   *
   *    math.lsolveAll(L, b)
   *
   * Examples:
   *
   *    const a = [[-2, 3], [2, 1]]
   *    const b = [11, 9]
   *    const x = lsolveAll(a, b)  // [ [[-5.5], [20]] ]
   *
   * See also:
   *
   *    lsolve, lup, slu, usolve, lusolve
   *
   * @param {Matrix, Array} L       A N x N matrix or array (L)
   * @param {Matrix, Array} b       A column vector with the b values
   *
   * @return {DenseMatrix[] | Array[]}  An array of affine-independent column vectors (x) that solve the linear system
   */
  return typed(name$2O, {
    'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(m, b) {
      return _sparseForwardSubstitution(m, b);
    },
    'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(m, b) {
      return _denseForwardSubstitution(m, b);
    },
    'Array, Array | Matrix': function ArrayArrayMatrix(a, b) {
      var m = matrix(a);
      var R = _denseForwardSubstitution(m, b);
      return R.map(r => r.valueOf());
    }
  });
  function _denseForwardSubstitution(m, b_) {
    // the algorithm is derived from
    // https://www.overleaf.com/read/csvgqdxggyjv

    // array of right-hand sides
    var B = [solveValidation(m, b_, true)._data.map(e => e[0])];
    var M = m._data;
    var rows = m._size[0];
    var columns = m._size[1];

    // loop columns
    for (var i = 0; i < columns; i++) {
      var L = B.length;

      // loop right-hand sides
      for (var k = 0; k < L; k++) {
        var b = B[k];
        if (!equalScalar(M[i][i], 0)) {
          // non-singular row

          b[i] = divideScalar(b[i], M[i][i]);
          for (var j = i + 1; j < columns; j++) {
            // b[j] -= b[i] * M[j,i]
            b[j] = subtractScalar(b[j], multiplyScalar(b[i], M[j][i]));
          }
        } else if (!equalScalar(b[i], 0)) {
          // singular row, nonzero RHS

          if (k === 0) {
            // There is no valid solution
            return [];
          } else {
            // This RHS is invalid but other solutions may still exist
            B.splice(k, 1);
            k -= 1;
            L -= 1;
          }
        } else if (k === 0) {
          // singular row, RHS is zero

          var bNew = [...b];
          bNew[i] = 1;
          for (var _j = i + 1; _j < columns; _j++) {
            bNew[_j] = subtractScalar(bNew[_j], M[_j][i]);
          }
          B.push(bNew);
        }
      }
    }
    return B.map(x => new DenseMatrix({
      data: x.map(e => [e]),
      size: [rows, 1]
    }));
  }
  function _sparseForwardSubstitution(m, b_) {
    // array of right-hand sides
    var B = [solveValidation(m, b_, true)._data.map(e => e[0])];
    var rows = m._size[0];
    var columns = m._size[1];
    var values = m._values;
    var index = m._index;
    var ptr = m._ptr;

    // loop columns
    for (var i = 0; i < columns; i++) {
      var L = B.length;

      // loop right-hand sides
      for (var k = 0; k < L; k++) {
        var b = B[k];

        // values & indices (column i)
        var iValues = [];
        var iIndices = [];

        // first & last indeces in column
        var firstIndex = ptr[i];
        var lastIndex = ptr[i + 1];

        // find the value at [i, i]
        var Mii = 0;
        for (var j = firstIndex; j < lastIndex; j++) {
          var J = index[j];
          // check row
          if (J === i) {
            Mii = values[j];
          } else if (J > i) {
            // store lower triangular
            iValues.push(values[j]);
            iIndices.push(J);
          }
        }
        if (!equalScalar(Mii, 0)) {
          // non-singular row

          b[i] = divideScalar(b[i], Mii);
          for (var _j2 = 0, _lastIndex = iIndices.length; _j2 < _lastIndex; _j2++) {
            var _J = iIndices[_j2];
            b[_J] = subtractScalar(b[_J], multiplyScalar(b[i], iValues[_j2]));
          }
        } else if (!equalScalar(b[i], 0)) {
          // singular row, nonzero RHS

          if (k === 0) {
            // There is no valid solution
            return [];
          } else {
            // This RHS is invalid but other solutions may still exist
            B.splice(k, 1);
            k -= 1;
            L -= 1;
          }
        } else if (k === 0) {
          // singular row, RHS is zero

          var bNew = [...b];
          bNew[i] = 1;
          for (var _j3 = 0, _lastIndex2 = iIndices.length; _j3 < _lastIndex2; _j3++) {
            var _J2 = iIndices[_j3];
            bNew[_J2] = subtractScalar(bNew[_J2], iValues[_j3]);
          }
          B.push(bNew);
        }
      }
    }
    return B.map(x => new DenseMatrix({
      data: x.map(e => [e]),
      size: [rows, 1]
    }));
  }
});

var name$2N = 'usolveAll';
var dependencies$2N = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'equalScalar', 'DenseMatrix'];
var createUsolveAll = /* #__PURE__ */factory(name$2N, dependencies$2N, _ref => {
  var {
    typed,
    matrix,
    divideScalar,
    multiplyScalar,
    subtractScalar,
    equalScalar,
    DenseMatrix
  } = _ref;
  var solveValidation = createSolveValidation({
    DenseMatrix
  });

  /**
   * Finds all solutions of a linear equation system by backward substitution. Matrix must be an upper triangular matrix.
   *
   * `U * x = b`
   *
   * Syntax:
   *
   *    math.usolveAll(U, b)
   *
   * Examples:
   *
   *    const a = [[-2, 3], [2, 1]]
   *    const b = [11, 9]
   *    const x = usolveAll(a, b)  // [ [[8], [9]] ]
   *
   * See also:
   *
   *    usolve, lup, slu, usolve, lusolve
   *
   * @param {Matrix, Array} U       A N x N matrix or array (U)
   * @param {Matrix, Array} b       A column vector with the b values
   *
   * @return {DenseMatrix[] | Array[]}  An array of affine-independent column vectors (x) that solve the linear system
   */
  return typed(name$2N, {
    'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(m, b) {
      return _sparseBackwardSubstitution(m, b);
    },
    'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(m, b) {
      return _denseBackwardSubstitution(m, b);
    },
    'Array, Array | Matrix': function ArrayArrayMatrix(a, b) {
      var m = matrix(a);
      var R = _denseBackwardSubstitution(m, b);
      return R.map(r => r.valueOf());
    }
  });
  function _denseBackwardSubstitution(m, b_) {
    // the algorithm is derived from
    // https://www.overleaf.com/read/csvgqdxggyjv

    // array of right-hand sides
    var B = [solveValidation(m, b_, true)._data.map(e => e[0])];
    var M = m._data;
    var rows = m._size[0];
    var columns = m._size[1];

    // loop columns backwards
    for (var i = columns - 1; i >= 0; i--) {
      var L = B.length;

      // loop right-hand sides
      for (var k = 0; k < L; k++) {
        var b = B[k];
        if (!equalScalar(M[i][i], 0)) {
          // non-singular row

          b[i] = divideScalar(b[i], M[i][i]);
          for (var j = i - 1; j >= 0; j--) {
            // b[j] -= b[i] * M[j,i]
            b[j] = subtractScalar(b[j], multiplyScalar(b[i], M[j][i]));
          }
        } else if (!equalScalar(b[i], 0)) {
          // singular row, nonzero RHS

          if (k === 0) {
            // There is no valid solution
            return [];
          } else {
            // This RHS is invalid but other solutions may still exist
            B.splice(k, 1);
            k -= 1;
            L -= 1;
          }
        } else if (k === 0) {
          // singular row, RHS is zero

          var bNew = [...b];
          bNew[i] = 1;
          for (var _j = i - 1; _j >= 0; _j--) {
            bNew[_j] = subtractScalar(bNew[_j], M[_j][i]);
          }
          B.push(bNew);
        }
      }
    }
    return B.map(x => new DenseMatrix({
      data: x.map(e => [e]),
      size: [rows, 1]
    }));
  }
  function _sparseBackwardSubstitution(m, b_) {
    // array of right-hand sides
    var B = [solveValidation(m, b_, true)._data.map(e => e[0])];
    var rows = m._size[0];
    var columns = m._size[1];
    var values = m._values;
    var index = m._index;
    var ptr = m._ptr;

    // loop columns backwards
    for (var i = columns - 1; i >= 0; i--) {
      var L = B.length;

      // loop right-hand sides
      for (var k = 0; k < L; k++) {
        var b = B[k];

        // values & indices (column i)
        var iValues = [];
        var iIndices = [];

        // first & last indeces in column
        var firstIndex = ptr[i];
        var lastIndex = ptr[i + 1];

        // find the value at [i, i]
        var Mii = 0;
        for (var j = lastIndex - 1; j >= firstIndex; j--) {
          var J = index[j];
          // check row
          if (J === i) {
            Mii = values[j];
          } else if (J < i) {
            // store upper triangular
            iValues.push(values[j]);
            iIndices.push(J);
          }
        }
        if (!equalScalar(Mii, 0)) {
          // non-singular row

          b[i] = divideScalar(b[i], Mii);

          // loop upper triangular
          for (var _j2 = 0, _lastIndex = iIndices.length; _j2 < _lastIndex; _j2++) {
            var _J = iIndices[_j2];
            b[_J] = subtractScalar(b[_J], multiplyScalar(b[i], iValues[_j2]));
          }
        } else if (!equalScalar(b[i], 0)) {
          // singular row, nonzero RHS

          if (k === 0) {
            // There is no valid solution
            return [];
          } else {
            // This RHS is invalid but other solutions may still exist
            B.splice(k, 1);
            k -= 1;
            L -= 1;
          }
        } else if (k === 0) {
          // singular row, RHS is zero

          var bNew = [...b];
          bNew[i] = 1;

          // loop upper triangular
          for (var _j3 = 0, _lastIndex2 = iIndices.length; _j3 < _lastIndex2; _j3++) {
            var _J2 = iIndices[_j3];
            bNew[_J2] = subtractScalar(bNew[_J2], iValues[_j3]);
          }
          B.push(bNew);
        }
      }
    }
    return B.map(x => new DenseMatrix({
      data: x.map(e => [e]),
      size: [rows, 1]
    }));
  }
});

var name$2M = 'matAlgo08xS0Sid';
var dependencies$2M = ['typed', 'equalScalar'];
var createMatAlgo08xS0Sid = /* #__PURE__ */factory(name$2M, dependencies$2M, _ref => {
  var {
    typed,
    equalScalar
  } = _ref;
  /**
   * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij).
   * Callback function invoked MAX(NNZA, NNZB) times
   *
   *
   *          ┌  f(Aij, Bij)  ; A(i,j) !== 0 && B(i,j) !== 0
   * C(i,j) = ┤  A(i,j)       ; A(i,j) !== 0 && B(i,j) === 0
   *          └  0            ; otherwise
   *
   *
   * @param {Matrix}   a                 The SparseMatrix instance (A)
   * @param {Matrix}   b                 The SparseMatrix instance (B)
   * @param {Function} callback          The f(Aij,Bij) operation to invoke
   *
   * @return {Matrix}                    SparseMatrix (C)
   *
   * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
   */
  return function matAlgo08xS0Sid(a, b, callback) {
    // sparse matrix arrays
    var avalues = a._values;
    var aindex = a._index;
    var aptr = a._ptr;
    var asize = a._size;
    var adt = a._datatype || a._data === undefined ? a._datatype : a.getDataType();
    // sparse matrix arrays
    var bvalues = b._values;
    var bindex = b._index;
    var bptr = b._ptr;
    var bsize = b._size;
    var bdt = b._datatype || b._data === undefined ? b._datatype : b.getDataType();

    // validate dimensions
    if (asize.length !== bsize.length) {
      throw new DimensionError(asize.length, bsize.length);
    }

    // check rows & columns
    if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
      throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
    }

    // sparse matrix cannot be a Pattern matrix
    if (!avalues || !bvalues) {
      throw new Error('Cannot perform operation on Pattern Sparse Matrices');
    }

    // rows & columns
    var rows = asize[0];
    var columns = asize[1];

    // datatype
    var dt;
    // equal signature to use
    var eq = equalScalar;
    // zero value
    var zero = 0;
    // callback signature to use
    var cf = callback;

    // process data types
    if (typeof adt === 'string' && adt === bdt && adt !== 'mixed') {
      // datatype
      dt = adt;
      // find signature that matches (dt, dt)
      eq = typed.find(equalScalar, [dt, dt]);
      // convert 0 to the same datatype
      zero = typed.convert(0, dt);
      // callback
      cf = typed.find(callback, [dt, dt]);
    }

    // result arrays
    var cvalues = [];
    var cindex = [];
    var cptr = [];

    // workspace
    var x = [];
    // marks indicating we have a value in x for a given column
    var w = [];

    // vars
    var k, k0, k1, i;

    // loop columns
    for (var j = 0; j < columns; j++) {
      // update cptr
      cptr[j] = cindex.length;
      // columns mark
      var mark = j + 1;
      // loop values in a
      for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
        // row
        i = aindex[k];
        // mark workspace
        w[i] = mark;
        // set value
        x[i] = avalues[k];
        // add index
        cindex.push(i);
      }
      // loop values in b
      for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
        // row
        i = bindex[k];
        // check value exists in workspace
        if (w[i] === mark) {
          // evaluate callback
          x[i] = cf(x[i], bvalues[k]);
        }
      }
      // initialize first index in j
      k = cptr[j];
      // loop index in j
      while (k < cindex.length) {
        // row
        i = cindex[k];
        // value @ i
        var v = x[i];
        // check for zero value
        if (!eq(v, zero)) {
          // push value
          cvalues.push(v);
          // increment pointer
          k++;
        } else {
          // remove value @ i, do not increment pointer
          cindex.splice(k, 1);
        }
      }
    }
    // update cptr
    cptr[columns] = cindex.length;

    // return sparse matrix
    return a.createSparseMatrix({
      values: cvalues,
      index: cindex,
      ptr: cptr,
      size: [rows, columns],
      datatype: adt === a._datatype && bdt === b._datatype ? dt : undefined
    });
  };
});

var createUseMatrixForArrayScalar = /* #__PURE__ */factory('useMatrixForArrayScalar', ['typed', 'matrix'], _ref => {
  var {
    typed,
    matrix
  } = _ref;
  return {
    'Array, number': typed.referTo('DenseMatrix, number', selfDn => (x, y) => selfDn(matrix(x), y).valueOf()),
    'Array, BigNumber': typed.referTo('DenseMatrix, BigNumber', selfDB => (x, y) => selfDB(matrix(x), y).valueOf()),
    'number, Array': typed.referTo('number, DenseMatrix', selfnD => (x, y) => selfnD(x, matrix(y)).valueOf()),
    'BigNumber, Array': typed.referTo('BigNumber, DenseMatrix', selfBD => (x, y) => selfBD(x, matrix(y)).valueOf())
  };
});

var name$2L = 'leftShift';
var dependencies$2L = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix', 'concat'];
var createLeftShift = /* #__PURE__ */factory(name$2L, dependencies$2L, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    zeros,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo01xDSid = createMatAlgo01xDSid({
    typed
  });
  var matAlgo02xDS0 = createMatAlgo02xDS0({
    typed,
    equalScalar
  });
  var matAlgo08xS0Sid = createMatAlgo08xS0Sid({
    typed,
    equalScalar
  });
  var matAlgo10xSids = createMatAlgo10xSids({
    typed,
    DenseMatrix
  });
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matAlgo14xDs = createMatAlgo14xDs({
    typed
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });
  var useMatrixForArrayScalar = createUseMatrixForArrayScalar({
    typed,
    matrix
  });

  /**
   * Bitwise left logical shift of a value x by y number of bits, `x << y`.
   * For matrices, the function is evaluated element wise.
   * For units, the function is evaluated on the best prefix base.
   *
   * Syntax:
   *
   *    math.leftShift(x, y)
   *
   * Examples:
   *
   *    math.leftShift(1, 2)               // returns number 4
   *
   *    math.leftShift([1, 2, 4], 4)       // returns Array [16, 32, 64]
   *
   * See also:
   *
   *    leftShift, bitNot, bitOr, bitXor, rightArithShift, rightLogShift
   *
   * @param  {number | BigNumber | bigint | Array | Matrix} x Value to be shifted
   * @param  {number | BigNumber | bigint} y Amount of shifts
   * @return {number | BigNumber | bigint | Array | Matrix} `x` shifted left `y` times
   */
  return typed(name$2L, {
    'number, number': leftShiftNumber,
    'BigNumber, BigNumber': leftShiftBigNumber,
    'bigint, bigint': (x, y) => x << y,
    'SparseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (equalScalar(y, 0)) {
        return x.clone();
      }
      return matAlgo11xS0s(x, y, self, false);
    }),
    'DenseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (equalScalar(y, 0)) {
        return x.clone();
      }
      return matAlgo14xDs(x, y, self, false);
    }),
    'number | BigNumber, SparseMatrix': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (equalScalar(x, 0)) {
        return zeros(y.size(), y.storage());
      }
      return matAlgo10xSids(y, x, self, true);
    }),
    'number | BigNumber, DenseMatrix': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (equalScalar(x, 0)) {
        return zeros(y.size(), y.storage());
      }
      return matAlgo14xDs(y, x, self, true);
    })
  }, useMatrixForArrayScalar, matrixAlgorithmSuite({
    SS: matAlgo08xS0Sid,
    DS: matAlgo01xDSid,
    SD: matAlgo02xDS0
  }));
});

var name$2K = 'rightArithShift';
var dependencies$2K = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix', 'concat'];
var createRightArithShift = /* #__PURE__ */factory(name$2K, dependencies$2K, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    zeros,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo01xDSid = createMatAlgo01xDSid({
    typed
  });
  var matAlgo02xDS0 = createMatAlgo02xDS0({
    typed,
    equalScalar
  });
  var matAlgo08xS0Sid = createMatAlgo08xS0Sid({
    typed,
    equalScalar
  });
  var matAlgo10xSids = createMatAlgo10xSids({
    typed,
    DenseMatrix
  });
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matAlgo14xDs = createMatAlgo14xDs({
    typed
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });
  var useMatrixForArrayScalar = createUseMatrixForArrayScalar({
    typed,
    matrix
  });

  /**
   * Bitwise right arithmetic shift of a value x by y number of bits, `x >> y`.
   * For matrices, the function is evaluated element wise.
   * For units, the function is evaluated on the best prefix base.
   *
   * Syntax:
   *
   *    math.rightArithShift(x, y)
   *
   * Examples:
   *
   *    math.rightArithShift(4, 2)               // returns number 1
   *
   *    math.rightArithShift([16, -32, 64], 4)   // returns Array [1, -2, 4]
   *
   * See also:
   *
   *    bitAnd, bitNot, bitOr, bitXor, rightArithShift, rightLogShift
   *
   * @param  {number | BigNumber | bigint | Array | Matrix} x Value to be shifted
   * @param  {number | BigNumber | bigint} y Amount of shifts
   * @return {number | BigNumber | bigint | Array | Matrix} `x` zero-filled shifted right `y` times
   */
  return typed(name$2K, {
    'number, number': rightArithShiftNumber,
    'BigNumber, BigNumber': rightArithShiftBigNumber,
    'bigint, bigint': (x, y) => x >> y,
    'SparseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (equalScalar(y, 0)) {
        return x.clone();
      }
      return matAlgo11xS0s(x, y, self, false);
    }),
    'DenseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (equalScalar(y, 0)) {
        return x.clone();
      }
      return matAlgo14xDs(x, y, self, false);
    }),
    'number | BigNumber, SparseMatrix': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (equalScalar(x, 0)) {
        return zeros(y.size(), y.storage());
      }
      return matAlgo10xSids(y, x, self, true);
    }),
    'number | BigNumber, DenseMatrix': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (equalScalar(x, 0)) {
        return zeros(y.size(), y.storage());
      }
      return matAlgo14xDs(y, x, self, true);
    })
  }, useMatrixForArrayScalar, matrixAlgorithmSuite({
    SS: matAlgo08xS0Sid,
    DS: matAlgo01xDSid,
    SD: matAlgo02xDS0
  }));
});

var name$2J = 'rightLogShift';
var dependencies$2J = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix', 'concat'];
var createRightLogShift = /* #__PURE__ */factory(name$2J, dependencies$2J, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    zeros,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo01xDSid = createMatAlgo01xDSid({
    typed
  });
  var matAlgo02xDS0 = createMatAlgo02xDS0({
    typed,
    equalScalar
  });
  var matAlgo08xS0Sid = createMatAlgo08xS0Sid({
    typed,
    equalScalar
  });
  var matAlgo10xSids = createMatAlgo10xSids({
    typed,
    DenseMatrix
  });
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matAlgo14xDs = createMatAlgo14xDs({
    typed
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });
  var useMatrixForArrayScalar = createUseMatrixForArrayScalar({
    typed,
    matrix
  });

  /**
   * Bitwise right logical shift of value x by y number of bits, `x >>> y`.
   * For matrices, the function is evaluated element wise.
   * For units, the function is evaluated on the best prefix base.
   *
   * Syntax:
   *
   *    math.rightLogShift(x, y)
   *
   * Examples:
   *
   *    math.rightLogShift(4, 2)               // returns number 1
   *
   *    math.rightLogShift([16, 32, 64], 4)    // returns Array [1, 2, 4]
   *
   * See also:
   *
   *    bitAnd, bitNot, bitOr, bitXor, leftShift, rightLogShift
   *
   * @param  {number | Array | Matrix} x Value to be shifted
   * @param  {number} y Amount of shifts
   * @return {number | Array | Matrix} `x` zero-filled shifted right `y` times
   */

  return typed(name$2J, {
    'number, number': rightLogShiftNumber,
    // 'BigNumber, BigNumber': ..., // TODO: implement BigNumber support for rightLogShift

    'SparseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (equalScalar(y, 0)) {
        return x.clone();
      }
      return matAlgo11xS0s(x, y, self, false);
    }),
    'DenseMatrix, number | BigNumber': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (equalScalar(y, 0)) {
        return x.clone();
      }
      return matAlgo14xDs(x, y, self, false);
    }),
    'number | BigNumber, SparseMatrix': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (equalScalar(x, 0)) {
        return zeros(y.size(), y.storage());
      }
      return matAlgo10xSids(y, x, self, true);
    }),
    'number | BigNumber, DenseMatrix': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (equalScalar(x, 0)) {
        return zeros(y.size(), y.storage());
      }
      return matAlgo14xDs(y, x, self, true);
    })
  }, useMatrixForArrayScalar, matrixAlgorithmSuite({
    SS: matAlgo08xS0Sid,
    DS: matAlgo01xDSid,
    SD: matAlgo02xDS0
  }));
});

var name$2I = 'and';
var dependencies$2I = ['typed', 'matrix', 'equalScalar', 'zeros', 'not', 'concat'];
var createAnd = /* #__PURE__ */factory(name$2I, dependencies$2I, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    zeros,
    not,
    concat
  } = _ref;
  var matAlgo02xDS0 = createMatAlgo02xDS0({
    typed,
    equalScalar
  });
  var matAlgo06xS0S0 = createMatAlgo06xS0S0({
    typed,
    equalScalar
  });
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matAlgo14xDs = createMatAlgo14xDs({
    typed
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Logical `and`. Test whether two values are both defined with a nonzero/nonempty value.
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.and(x, y)
   *
   * Examples:
   *
   *    math.and(2, 4)   // returns true
   *
   *    a = [2, 0, 0]
   *    b = [3, 7, 0]
   *    c = 0
   *
   *    math.and(a, b)   // returns [true, false, false]
   *    math.and(a, c)   // returns [false, false, false]
   *
   * See also:
   *
   *    not, or, xor
   *
   * @param  {number | BigNumber | bigint | Complex | Unit | Array | Matrix} x First value to check
   * @param  {number | BigNumber | bigint | Complex | Unit | Array | Matrix} y Second value to check
   * @return {boolean | Array | Matrix}
   *            Returns true when both inputs are defined with a nonzero/nonempty value.
   */
  return typed(name$2I, {
    'number, number': andNumber,
    'Complex, Complex': function ComplexComplex(x, y) {
      return (x.re !== 0 || x.im !== 0) && (y.re !== 0 || y.im !== 0);
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      return !x.isZero() && !y.isZero() && !x.isNaN() && !y.isNaN();
    },
    'bigint, bigint': andNumber,
    'Unit, Unit': typed.referToSelf(self => (x, y) => self(x.value || 0, y.value || 0)),
    'SparseMatrix, any': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (not(y)) {
        // return zero matrix
        return zeros(x.size(), x.storage());
      }
      return matAlgo11xS0s(x, y, self, false);
    }),
    'DenseMatrix, any': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (not(y)) {
        // return zero matrix
        return zeros(x.size(), x.storage());
      }
      return matAlgo14xDs(x, y, self, false);
    }),
    'any, SparseMatrix': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (not(x)) {
        // return zero matrix
        return zeros(x.size(), x.storage());
      }
      return matAlgo11xS0s(y, x, self, true);
    }),
    'any, DenseMatrix': typed.referToSelf(self => (x, y) => {
      // check scalar
      if (not(x)) {
        // return zero matrix
        return zeros(x.size(), x.storage());
      }
      return matAlgo14xDs(y, x, self, true);
    }),
    'Array, any': typed.referToSelf(self => (x, y) => {
      // use matrix implementation
      return self(matrix(x), y).valueOf();
    }),
    'any, Array': typed.referToSelf(self => (x, y) => {
      // use matrix implementation
      return self(x, matrix(y)).valueOf();
    })
  }, matrixAlgorithmSuite({
    SS: matAlgo06xS0S0,
    DS: matAlgo02xDS0
  }));
});

var name$2H = 'compare';
var dependencies$2H = ['typed', 'config', 'matrix', 'equalScalar', 'BigNumber', 'Fraction', 'DenseMatrix', 'concat'];
var createCompare = /* #__PURE__ */factory(name$2H, dependencies$2H, _ref => {
  var {
    typed,
    config,
    equalScalar,
    matrix,
    BigNumber,
    Fraction,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo05xSfSf = createMatAlgo05xSfSf({
    typed,
    equalScalar
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });
  var compareUnits = createCompareUnits({
    typed
  });

  /**
   * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y.
   *
   * x and y are considered equal when the relative difference between x and y
   * is smaller than the configured absTol and relTol. The function cannot be used to
   * compare values smaller than approximately 2.22e-16.
   *
   * For matrices, the function is evaluated element wise.
   * Strings are compared by their numerical value.
   *
   * Syntax:
   *
   *    math.compare(x, y)
   *
   * Examples:
   *
   *    math.compare(6, 1)           // returns 1
   *    math.compare(2, 3)           // returns -1
   *    math.compare(7, 7)           // returns 0
   *    math.compare('10', '2')      // returns 1
   *    math.compare('1000', '1e3')  // returns 0
   *
   *    const a = math.unit('5 cm')
   *    const b = math.unit('40 mm')
   *    math.compare(a, b)           // returns 1
   *
   *    math.compare(2, [1, 2, 3])   // returns [1, 0, -1]
   *
   * See also:
   *
   *    equal, unequal, smaller, smallerEq, larger, largerEq, compareNatural, compareText
   *
   * @param  {number | BigNumber | bigint | Fraction | Unit | string | Array | Matrix} x First value to compare
   * @param  {number | BigNumber | bigint | Fraction | Unit | string | Array | Matrix} y Second value to compare
   * @return {number | BigNumber | bigint | Fraction | Array | Matrix} Returns the result of the comparison:
   *                                                          1 when x > y, -1 when x < y, and 0 when x == y.
   */
  return typed(name$2H, createCompareNumber({
    typed,
    config
  }), {
    'boolean, boolean': function booleanBoolean(x, y) {
      return x === y ? 0 : x > y ? 1 : -1;
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      return nearlyEqual(x, y, config.relTol, config.absTol) ? new BigNumber(0) : new BigNumber(x.cmp(y));
    },
    'bigint, bigint': function bigintBigint(x, y) {
      return x === y ? 0n : x > y ? 1n : -1n;
    },
    'Fraction, Fraction': function FractionFraction(x, y) {
      return new Fraction(x.compare(y));
    },
    'Complex, Complex': function ComplexComplex() {
      throw new TypeError('No ordering relation is defined for complex numbers');
    }
  }, compareUnits, matrixAlgorithmSuite({
    SS: matAlgo05xSfSf,
    DS: matAlgo03xDSf,
    Ss: matAlgo12xSfs
  }));
});
var createCompareNumber = /* #__PURE__ */factory(name$2H, ['typed', 'config'], _ref2 => {
  var {
    typed,
    config
  } = _ref2;
  return typed(name$2H, {
    'number, number': function numberNumber(x, y) {
      return nearlyEqual$1(x, y, config.relTol, config.absTol) ? 0 : x > y ? 1 : -1;
    }
  });
});

/*
 * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
 * Author: Jim Palmer (based on chunking idea from Dave Koelle)
 */

/*jshint unused:false */
var naturalSort = function naturalSort (a, b) {
	var re = /(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,
		sre = /(^[ ]*|[ ]*$)/g,
		dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
		hre = /^0x[0-9a-f]+$/i,
		ore = /^0/,
		i = function(s) { return naturalSort.insensitive && ('' + s).toLowerCase() || '' + s; },
		// convert all to strings strip whitespace
		x = i(a).replace(sre, '') || '',
		y = i(b).replace(sre, '') || '',
		// chunk/tokenize
		xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
		yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
		// numeric, hex or date detection
		xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && x.match(dre) && Date.parse(x)),
		yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null,
		oFxNcL, oFyNcL;
	// first try and sort Hex codes or Dates
	if (yD) {
		if ( xD < yD ) { return -1; }
		else if ( xD > yD ) { return 1; }
	}
	// natural sorting through split numeric strings and default strings
	for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
		// find floats not starting with '0', string or 0 if not defined (Clint Priest)
		oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
		oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
		// handle numeric vs string comparison - number < string - (Kyle Adams)
		if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; }
		// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
		else if (typeof oFxNcL !== typeof oFyNcL) {
			oFxNcL += '';
			oFyNcL += '';
		}
		if (oFxNcL < oFyNcL) { return -1; }
		if (oFxNcL > oFyNcL) { return 1; }
	}
	return 0;
};

var name$2G = 'compareNatural';
var dependencies$2G = ['typed', 'compare'];
var createCompareNatural = /* #__PURE__ */factory(name$2G, dependencies$2G, _ref => {
  var {
    typed,
    compare
  } = _ref;
  var compareBooleans = compare.signatures['boolean,boolean'];

  /**
   * Compare two values of any type in a deterministic, natural way.
   *
   * For numeric values, the function works the same as `math.compare`.
   * For types of values that can't be compared mathematically,
   * the function compares in a natural way.
   *
   * For numeric values, x and y are considered equal when the relative
   * difference between x and y is smaller than the configured relTol and absTol.
   * The function cannot be used to compare values smaller than
   * approximately 2.22e-16.
   *
   * For Complex numbers, first the real parts are compared. If equal,
   * the imaginary parts are compared.
   *
   * Strings are compared with a natural sorting algorithm, which
   * orders strings in a "logic" way following some heuristics.
   * This differs from the function `compare`, which converts the string
   * into a numeric value and compares that. The function `compareText`
   * on the other hand compares text lexically.
   *
   * Arrays and Matrices are compared value by value until there is an
   * unequal pair of values encountered. Objects are compared by sorted
   * keys until the keys or their values are unequal.
   *
   * Syntax:
   *
   *    math.compareNatural(x, y)
   *
   * Examples:
   *
   *    math.compareNatural(6, 1)              // returns 1
   *    math.compareNatural(2, 3)              // returns -1
   *    math.compareNatural(7, 7)              // returns 0
   *
   *    math.compareNatural('10', '2')         // returns 1
   *    math.compareText('10', '2')            // returns -1
   *    math.compare('10', '2')                // returns 1
   *
   *    math.compareNatural('Answer: 10', 'Answer: 2') // returns 1
   *    math.compareText('Answer: 10', 'Answer: 2')    // returns -1
   *    math.compare('Answer: 10', 'Answer: 2')
   *        // Error: Cannot convert "Answer: 10" to a number
   *
   *    const a = math.unit('5 cm')
   *    const b = math.unit('40 mm')
   *    math.compareNatural(a, b)              // returns 1
   *
   *    const c = math.complex('2 + 3i')
   *    const d = math.complex('2 + 4i')
   *    math.compareNatural(c, d)              // returns -1
   *
   *    math.compareNatural([1, 2, 4], [1, 2, 3]) // returns 1
   *    math.compareNatural([1, 2, 3], [1, 2])    // returns 1
   *    math.compareNatural([1, 5], [1, 2, 3])    // returns 1
   *    math.compareNatural([1, 2], [1, 2])       // returns 0
   *
   *    math.compareNatural({a: 2}, {a: 4})       // returns -1
   *
   * See also:
   *
   *    compare, compareText
   *
   * @param  {*} x First value to compare
   * @param  {*} y Second value to compare
   * @return {number} Returns the result of the comparison:
   *                  1 when x > y, -1 when x < y, and 0 when x == y.
   */
  return typed(name$2G, {
    'any, any': _compareNatural
  }); // just to check # args

  function _compareNatural(x, y) {
    var typeX = typeOf(x);
    var typeY = typeOf(y);
    var c;

    // numeric types
    if ((typeX === 'number' || typeX === 'BigNumber' || typeX === 'Fraction') && (typeY === 'number' || typeY === 'BigNumber' || typeY === 'Fraction')) {
      c = compare(x, y);
      if (c.toString() !== '0') {
        // c can be number, BigNumber, or Fraction
        return c > 0 ? 1 : -1; // return a number
      } else {
        return naturalSort(typeX, typeY);
      }
    }

    // matrix types
    var matTypes = ['Array', 'DenseMatrix', 'SparseMatrix'];
    if (matTypes.includes(typeX) || matTypes.includes(typeY)) {
      c = compareMatricesAndArrays(_compareNatural, x, y);
      if (c !== 0) {
        return c;
      } else {
        return naturalSort(typeX, typeY);
      }
    }

    // in case of different types, order by name of type, i.e. 'BigNumber' < 'Complex'
    if (typeX !== typeY) {
      return naturalSort(typeX, typeY);
    }
    if (typeX === 'Complex') {
      return compareComplexNumbers(x, y);
    }
    if (typeX === 'Unit') {
      if (x.equalBase(y)) {
        return _compareNatural(x.value, y.value);
      }

      // compare by units
      return compareArrays(_compareNatural, x.formatUnits(), y.formatUnits());
    }
    if (typeX === 'boolean') {
      return compareBooleans(x, y);
    }
    if (typeX === 'string') {
      return naturalSort(x, y);
    }
    if (typeX === 'Object') {
      return compareObjects(_compareNatural, x, y);
    }
    if (typeX === 'null') {
      return 0;
    }
    if (typeX === 'undefined') {
      return 0;
    }

    // this should not occur...
    throw new TypeError('Unsupported type of value "' + typeX + '"');
  }

  /**
   * Compare mixed matrix/array types, by converting to same-shaped array.
   * This comparator is non-deterministic regarding input types.
   * @param {Array | SparseMatrix | DenseMatrix | *} x
   * @param {Array | SparseMatrix | DenseMatrix | *} y
   * @returns {number} Returns the comparison result: -1, 0, or 1
   */
  function compareMatricesAndArrays(compareNatural, x, y) {
    if (isSparseMatrix(x) && isSparseMatrix(y)) {
      return compareArrays(compareNatural, x.toJSON().values, y.toJSON().values);
    }
    if (isSparseMatrix(x)) {
      // note: convert to array is expensive
      return compareMatricesAndArrays(compareNatural, x.toArray(), y);
    }
    if (isSparseMatrix(y)) {
      // note: convert to array is expensive
      return compareMatricesAndArrays(compareNatural, x, y.toArray());
    }

    // convert DenseArray into Array
    if (isDenseMatrix(x)) {
      return compareMatricesAndArrays(compareNatural, x.toJSON().data, y);
    }
    if (isDenseMatrix(y)) {
      return compareMatricesAndArrays(compareNatural, x, y.toJSON().data);
    }

    // convert scalars to array
    if (!Array.isArray(x)) {
      return compareMatricesAndArrays(compareNatural, [x], y);
    }
    if (!Array.isArray(y)) {
      return compareMatricesAndArrays(compareNatural, x, [y]);
    }
    return compareArrays(compareNatural, x, y);
  }

  /**
   * Compare two Arrays
   *
   * - First, compares value by value
   * - Next, if all corresponding values are equal,
   *   look at the length: longest array will be considered largest
   *
   * @param {Array} x
   * @param {Array} y
   * @returns {number} Returns the comparison result: -1, 0, or 1
   */
  function compareArrays(compareNatural, x, y) {
    // compare each value
    for (var i = 0, ii = Math.min(x.length, y.length); i < ii; i++) {
      var v = compareNatural(x[i], y[i]);
      if (v !== 0) {
        return v;
      }
    }

    // compare the size of the arrays
    if (x.length > y.length) {
      return 1;
    }
    if (x.length < y.length) {
      return -1;
    }

    // both Arrays have equal size and content
    return 0;
  }

  /**
   * Compare two objects
   *
   * - First, compare sorted property names
   * - Next, compare the property values
   *
   * @param {Object} x
   * @param {Object} y
   * @returns {number} Returns the comparison result: -1, 0, or 1
   */
  function compareObjects(compareNatural, x, y) {
    var keysX = Object.keys(x);
    var keysY = Object.keys(y);

    // compare keys
    keysX.sort(naturalSort);
    keysY.sort(naturalSort);
    var c = compareArrays(compareNatural, keysX, keysY);
    if (c !== 0) {
      return c;
    }

    // compare values
    for (var i = 0; i < keysX.length; i++) {
      var v = compareNatural(x[keysX[i]], y[keysY[i]]);
      if (v !== 0) {
        return v;
      }
    }
    return 0;
  }
});

/**
 * Compare two complex numbers, `x` and `y`:
 *
 * - First, compare the real values of `x` and `y`
 * - If equal, compare the imaginary values of `x` and `y`
 *
 * @params {Complex} x
 * @params {Complex} y
 * @returns {number} Returns the comparison result: -1, 0, or 1
 */
function compareComplexNumbers(x, y) {
  if (x.re > y.re) {
    return 1;
  }
  if (x.re < y.re) {
    return -1;
  }
  if (x.im > y.im) {
    return 1;
  }
  if (x.im < y.im) {
    return -1;
  }
  return 0;
}

var name$2F = 'compareText';
var dependencies$2F = ['typed', 'matrix', 'concat'];
compareText.signature = 'any, any';
var createCompareText = /* #__PURE__ */factory(name$2F, dependencies$2F, _ref => {
  var {
    typed,
    matrix,
    concat
  } = _ref;
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Compare two strings lexically. Comparison is case sensitive.
   * Returns 1 when x > y, -1 when x < y, and 0 when x == y.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.compareText(x, y)
   *
   * Examples:
   *
   *    math.compareText('B', 'A')     // returns 1
   *    math.compareText('2', '10')    // returns 1
   *    math.compare('2', '10')        // returns -1
   *    math.compareNatural('2', '10') // returns -1
   *
   *    math.compareText('B', ['A', 'B', 'C']) // returns [1, 0, -1]
   *
   * See also:
   *
   *    equal, equalText, compare, compareNatural
   *
   * @param  {string | Array | DenseMatrix} x First string to compare
   * @param  {string | Array | DenseMatrix} y Second string to compare
   * @return {number | Array | DenseMatrix} Returns the result of the comparison:
   *                                        1 when x > y, -1 when x < y, and 0 when x == y.
   */
  return typed(name$2F, compareText, matrixAlgorithmSuite({
    elop: compareText,
    Ds: true
  }));
});

var name$2E = 'equal';
var dependencies$2E = ['typed', 'matrix', 'equalScalar', 'DenseMatrix', 'concat'];
var createEqual = /* #__PURE__ */factory(name$2E, dependencies$2E, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo07xSSf = createMatAlgo07xSSf({
    typed,
    DenseMatrix
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Test whether two values are equal.
   *
   * The function tests whether the relative difference between x and y is
   * smaller than the configured relTol and absTol. The function cannot be used to
   * compare values smaller than approximately 2.22e-16.
   *
   * For matrices, the function is evaluated element wise.
   * In case of complex numbers, x.re must equal y.re, and x.im must equal y.im.
   *
   * Values `null` and `undefined` are compared strictly, thus `null` is only
   * equal to `null` and nothing else, and `undefined` is only equal to
   * `undefined` and nothing else. Strings are compared by their numerical value.
   *
   * Syntax:
   *
   *    math.equal(x, y)
   *
   * Examples:
   *
   *    math.equal(2 + 2, 3)         // returns false
   *    math.equal(2 + 2, 4)         // returns true
   *
   *    const a = math.unit('50 cm')
   *    const b = math.unit('5 m')
   *    math.equal(a, b)             // returns true
   *
   *    const c = [2, 5, 1]
   *    const d = [2, 7, 1]
   *
   *    math.equal(c, d)             // returns [true, false, true]
   *    math.deepEqual(c, d)         // returns false
   *
   *    math.equal("1000", "1e3")    // returns true
   *    math.equal(0, null)          // returns false
   *
   * See also:
   *
   *    unequal, smaller, smallerEq, larger, largerEq, compare, deepEqual, equalText
   *
   * @param  {number | BigNumber | bigint | boolean | Complex | Unit | string | Array | Matrix} x First value to compare
   * @param  {number | BigNumber | bigint | boolean | Complex | Unit | string | Array | Matrix} y Second value to compare
   * @return {boolean | Array | Matrix} Returns true when the compared values are equal, else returns false
   */
  return typed(name$2E, createEqualNumber({
    typed,
    equalScalar
  }), matrixAlgorithmSuite({
    elop: equalScalar,
    SS: matAlgo07xSSf,
    DS: matAlgo03xDSf,
    Ss: matAlgo12xSfs
  }));
});
var createEqualNumber = factory(name$2E, ['typed', 'equalScalar'], _ref2 => {
  var {
    typed,
    equalScalar
  } = _ref2;
  return typed(name$2E, {
    'any, any': function anyAny(x, y) {
      // strict equality for null and undefined?
      if (x === null) {
        return y === null;
      }
      if (y === null) {
        return x === null;
      }
      if (x === undefined) {
        return y === undefined;
      }
      if (y === undefined) {
        return x === undefined;
      }
      return equalScalar(x, y);
    }
  });
});

var name$2D = 'equalText';
var dependencies$2D = ['typed', 'compareText', 'isZero'];
var createEqualText = /* #__PURE__ */factory(name$2D, dependencies$2D, _ref => {
  var {
    typed,
    compareText,
    isZero
  } = _ref;
  /**
   * Check equality of two strings. Comparison is case sensitive.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.equalText(x, y)
   *
   * Examples:
   *
   *    math.equalText('Hello', 'Hello')     // returns true
   *    math.equalText('a', 'A')             // returns false
   *    math.equal('2e3', '2000')            // returns true
   *    math.equalText('2e3', '2000')        // returns false
   *
   *    math.equalText('B', ['A', 'B', 'C']) // returns [false, true, false]
   *
   * See also:
   *
   *    equal, compareText, compare, compareNatural
   *
   * @param  {string | Array | DenseMatrix} x First string to compare
   * @param  {string | Array | DenseMatrix} y Second string to compare
   * @return {number | Array | DenseMatrix} Returns true if the values are equal, and false if not.
   */
  return typed(name$2D, {
    'any, any': function anyAny(x, y) {
      return isZero(compareText(x, y));
    }
  });
});

var name$2C = 'smaller';
var dependencies$2C = ['typed', 'config', 'matrix', 'DenseMatrix', 'concat'];
var createSmaller = /* #__PURE__ */factory(name$2C, dependencies$2C, _ref => {
  var {
    typed,
    config,
    matrix,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo07xSSf = createMatAlgo07xSSf({
    typed,
    DenseMatrix
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });
  var compareUnits = createCompareUnits({
    typed
  });

  /**
   * Test whether value x is smaller than y.
   *
   * The function returns true when x is smaller than y and the relative
   * difference between x and y is smaller than the configured relTol and absTol. The
   * function cannot be used to compare values smaller than approximately 2.22e-16.
   *
   * For matrices, the function is evaluated element wise.
   * Strings are compared by their numerical value.
   *
   * Syntax:
   *
   *    math.smaller(x, y)
   *
   * Examples:
   *
   *    math.smaller(2, 3)            // returns true
   *    math.smaller(5, 2 * 2)        // returns false
   *
   *    const a = math.unit('5 cm')
   *    const b = math.unit('2 inch')
   *    math.smaller(a, b)            // returns true
   *
   * See also:
   *
   *    equal, unequal, smallerEq, smaller, smallerEq, compare
   *
   * @param  {number | BigNumber | bigint | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
   * @param  {number | BigNumber | bigint | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
   * @return {boolean | Array | Matrix} Returns true when the x is smaller than y, else returns false
   */
  return typed(name$2C, createSmallerNumber({
    typed,
    config
  }), {
    'boolean, boolean': (x, y) => x < y,
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      return x.lt(y) && !nearlyEqual(x, y, config.relTol, config.absTol);
    },
    'bigint, bigint': (x, y) => x < y,
    'Fraction, Fraction': (x, y) => x.compare(y) === -1,
    'Complex, Complex': function ComplexComplex(x, y) {
      throw new TypeError('No ordering relation is defined for complex numbers');
    }
  }, compareUnits, matrixAlgorithmSuite({
    SS: matAlgo07xSSf,
    DS: matAlgo03xDSf,
    Ss: matAlgo12xSfs
  }));
});
var createSmallerNumber = /* #__PURE__ */factory(name$2C, ['typed', 'config'], _ref2 => {
  var {
    typed,
    config
  } = _ref2;
  return typed(name$2C, {
    'number, number': function numberNumber(x, y) {
      return x < y && !nearlyEqual$1(x, y, config.relTol, config.absTol);
    }
  });
});

var name$2B = 'smallerEq';
var dependencies$2B = ['typed', 'config', 'matrix', 'DenseMatrix', 'concat'];
var createSmallerEq = /* #__PURE__ */factory(name$2B, dependencies$2B, _ref => {
  var {
    typed,
    config,
    matrix,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo07xSSf = createMatAlgo07xSSf({
    typed,
    DenseMatrix
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });
  var compareUnits = createCompareUnits({
    typed
  });

  /**
   * Test whether value x is smaller or equal to y.
   *
   * The function returns true when x is smaller than y or the relative
   * difference between x and y is smaller than the configured relTol and absTol. The
   * function cannot be used to compare values smaller than approximately 2.22e-16.
   *
   * For matrices, the function is evaluated element wise.
   * Strings are compared by their numerical value.
   *
   * Syntax:
   *
   *    math.smallerEq(x, y)
   *
   * Examples:
   *
   *    math.smaller(1 + 2, 3)        // returns false
   *    math.smallerEq(1 + 2, 3)      // returns true
   *
   * See also:
   *
   *    equal, unequal, smaller, larger, largerEq, compare
   *
   * @param  {number | BigNumber | bigint | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
   * @param  {number | BigNumber | bigint | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
   * @return {boolean | Array | Matrix} Returns true when the x is smaller than y, else returns false
   */
  return typed(name$2B, createSmallerEqNumber({
    typed,
    config
  }), {
    'boolean, boolean': (x, y) => x <= y,
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      return x.lte(y) || nearlyEqual(x, y, config.relTol, config.absTol);
    },
    'bigint, bigint': (x, y) => x <= y,
    'Fraction, Fraction': (x, y) => x.compare(y) !== 1,
    'Complex, Complex': function ComplexComplex() {
      throw new TypeError('No ordering relation is defined for complex numbers');
    }
  }, compareUnits, matrixAlgorithmSuite({
    SS: matAlgo07xSSf,
    DS: matAlgo03xDSf,
    Ss: matAlgo12xSfs
  }));
});
var createSmallerEqNumber = /* #__PURE__ */factory(name$2B, ['typed', 'config'], _ref2 => {
  var {
    typed,
    config
  } = _ref2;
  return typed(name$2B, {
    'number, number': function numberNumber(x, y) {
      return x <= y || nearlyEqual$1(x, y, config.relTol, config.absTol);
    }
  });
});

var name$2A = 'larger';
var dependencies$2A = ['typed', 'config', 'matrix', 'DenseMatrix', 'concat'];
var createLarger = /* #__PURE__ */factory(name$2A, dependencies$2A, _ref => {
  var {
    typed,
    config,
    matrix,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo07xSSf = createMatAlgo07xSSf({
    typed,
    DenseMatrix
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });
  var compareUnits = createCompareUnits({
    typed
  });

  /**
   * Test whether value x is larger than y.
   *
   * The function returns true when x is larger than y and the relative
   * difference between x and y is larger than the configured relTol and absTol. The
   * function cannot be used to compare values smaller than approximately 2.22e-16.
   *
   * For matrices, the function is evaluated element wise.
   * Strings are compared by their numerical value.
   *
   * Syntax:
   *
   *    math.larger(x, y)
   *
   * Examples:
   *
   *    math.larger(2, 3)             // returns false
   *    math.larger(5, 2 + 2)         // returns true
   *
   *    const a = math.unit('5 cm')
   *    const b = math.unit('2 inch')
   *    math.larger(a, b)             // returns false
   *
   * See also:
   *
   *    equal, unequal, smaller, smallerEq, largerEq, compare
   *
   * @param  {number | BigNumber | bigint | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
   * @param  {number | BigNumber | bigint | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
   * @return {boolean | Array | Matrix} Returns true when the x is larger than y, else returns false
   */
  return typed(name$2A, createLargerNumber({
    typed,
    config
  }), {
    'boolean, boolean': (x, y) => x > y,
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      return x.gt(y) && !nearlyEqual(x, y, config.relTol, config.absTol);
    },
    'bigint, bigint': (x, y) => x > y,
    'Fraction, Fraction': (x, y) => x.compare(y) === 1,
    'Complex, Complex': function ComplexComplex() {
      throw new TypeError('No ordering relation is defined for complex numbers');
    }
  }, compareUnits, matrixAlgorithmSuite({
    SS: matAlgo07xSSf,
    DS: matAlgo03xDSf,
    Ss: matAlgo12xSfs
  }));
});
var createLargerNumber = /* #__PURE__ */factory(name$2A, ['typed', 'config'], _ref2 => {
  var {
    typed,
    config
  } = _ref2;
  return typed(name$2A, {
    'number, number': function numberNumber(x, y) {
      return x > y && !nearlyEqual$1(x, y, config.relTol, config.absTol);
    }
  });
});

var name$2z = 'largerEq';
var dependencies$2z = ['typed', 'config', 'matrix', 'DenseMatrix', 'concat'];
var createLargerEq = /* #__PURE__ */factory(name$2z, dependencies$2z, _ref => {
  var {
    typed,
    config,
    matrix,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo07xSSf = createMatAlgo07xSSf({
    typed,
    DenseMatrix
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });
  var compareUnits = createCompareUnits({
    typed
  });

  /**
   * Test whether value x is larger or equal to y.
   *
   * The function returns true when x is larger than y or the relative
   * difference between x and y is smaller than the configured relTol and absTol. The
   * function cannot be used to compare values smaller than approximately 2.22e-16.
   *
   * For matrices, the function is evaluated element wise.
   * Strings are compared by their numerical value.
   *
   * Syntax:
   *
   *    math.largerEq(x, y)
   *
   * Examples:
   *
   *    math.larger(2, 1 + 1)         // returns false
   *    math.largerEq(2, 1 + 1)       // returns true
   *
   * See also:
   *
   *    equal, unequal, smaller, smallerEq, larger, compare
   *
   * @param  {number | BigNumber | bigint | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
   * @param  {number | BigNumber | bigint | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
   * @return {boolean | Array | Matrix} Returns true when the x is larger or equal to y, else returns false
   */
  return typed(name$2z, createLargerEqNumber({
    typed,
    config
  }), {
    'boolean, boolean': (x, y) => x >= y,
    'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
      return x.gte(y) || nearlyEqual(x, y, config.relTol, config.absTol);
    },
    'bigint, bigint': function bigintBigint(x, y) {
      return x >= y;
    },
    'Fraction, Fraction': (x, y) => x.compare(y) !== -1,
    'Complex, Complex': function ComplexComplex() {
      throw new TypeError('No ordering relation is defined for complex numbers');
    }
  }, compareUnits, matrixAlgorithmSuite({
    SS: matAlgo07xSSf,
    DS: matAlgo03xDSf,
    Ss: matAlgo12xSfs
  }));
});
var createLargerEqNumber = /* #__PURE__ */factory(name$2z, ['typed', 'config'], _ref2 => {
  var {
    typed,
    config
  } = _ref2;
  return typed(name$2z, {
    'number, number': function numberNumber(x, y) {
      return x >= y || nearlyEqual$1(x, y, config.relTol, config.absTol);
    }
  });
});

var name$2y = 'deepEqual';
var dependencies$2y = ['typed', 'equal'];
var createDeepEqual = /* #__PURE__ */factory(name$2y, dependencies$2y, _ref => {
  var {
    typed,
    equal
  } = _ref;
  /**
   * Test element wise whether two matrices are equal.
   * The function accepts both matrices and scalar values.
   *
   * Strings are compared by their numerical value.
   *
   * Syntax:
   *
   *    math.deepEqual(x, y)
   *
   * Examples:
   *
   *    math.deepEqual(2, 4)   // returns false
   *
   *    a = [2, 5, 1]
   *    b = [2, 7, 1]
   *
   *    math.deepEqual(a, b)   // returns false
   *    math.equal(a, b)       // returns [true, false, true]
   *
   * See also:
   *
   *    equal, unequal
   *
   * @param  {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First matrix to compare
   * @param  {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second matrix to compare
   * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix}
   *            Returns true when the input matrices have the same size and each of their elements is equal.
   */
  return typed(name$2y, {
    'any, any': function anyAny(x, y) {
      return _deepEqual(x.valueOf(), y.valueOf());
    }
  });

  /**
   * Test whether two arrays have the same size and all elements are equal
   * @param {Array | *} x
   * @param {Array | *} y
   * @return {boolean} Returns true if both arrays are deep equal
   */
  function _deepEqual(x, y) {
    if (Array.isArray(x)) {
      if (Array.isArray(y)) {
        var len = x.length;
        if (len !== y.length) {
          return false;
        }
        for (var i = 0; i < len; i++) {
          if (!_deepEqual(x[i], y[i])) {
            return false;
          }
        }
        return true;
      } else {
        return false;
      }
    } else {
      if (Array.isArray(y)) {
        return false;
      } else {
        return equal(x, y);
      }
    }
  }
});

var name$2x = 'unequal';
var dependencies$2x = ['typed', 'config', 'equalScalar', 'matrix', 'DenseMatrix', 'concat'];
var createUnequal = /* #__PURE__ */factory(name$2x, dependencies$2x, _ref => {
  var {
    typed,
    config,
    equalScalar,
    matrix,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo07xSSf = createMatAlgo07xSSf({
    typed,
    DenseMatrix
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Test whether two values are unequal.
   *
   * The function tests whether the relative difference between x and y is
   * larger than the configured relTol and absTol. The function cannot be used to compare
   * values smaller than approximately 2.22e-16.
   *
   * For matrices, the function is evaluated element wise.
   * In case of complex numbers, x.re must unequal y.re, or x.im must unequal y.im.
   * Strings are compared by their numerical value.
   *
   * Values `null` and `undefined` are compared strictly, thus `null` is unequal
   * with everything except `null`, and `undefined` is unequal with everything
   * except `undefined`.
   *
   * Syntax:
   *
   *    math.unequal(x, y)
   *
   * Examples:
   *
   *    math.unequal(2 + 2, 3)       // returns true
   *    math.unequal(2 + 2, 4)       // returns false
   *
   *    const a = math.unit('50 cm')
   *    const b = math.unit('5 m')
   *    math.unequal(a, b)           // returns false
   *
   *    const c = [2, 5, 1]
   *    const d = [2, 7, 1]
   *
   *    math.unequal(c, d)           // returns [false, true, false]
   *    math.deepEqual(c, d)         // returns false
   *
   *    math.unequal(0, null)        // returns true
   * See also:
   *
   *    equal, deepEqual, smaller, smallerEq, larger, largerEq, compare
   *
   * @param  {number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined} x First value to compare
   * @param  {number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined} y Second value to compare
   * @return {boolean | Array | Matrix} Returns true when the compared values are unequal, else returns false
   */
  return typed(name$2x, createUnequalNumber({
    typed,
    equalScalar
  }), matrixAlgorithmSuite({
    elop: _unequal,
    SS: matAlgo07xSSf,
    DS: matAlgo03xDSf,
    Ss: matAlgo12xSfs
  }));
  function _unequal(x, y) {
    return !equalScalar(x, y);
  }
});
var createUnequalNumber = factory(name$2x, ['typed', 'equalScalar'], _ref2 => {
  var {
    typed,
    equalScalar
  } = _ref2;
  return typed(name$2x, {
    'any, any': function anyAny(x, y) {
      // strict equality for null and undefined?
      if (x === null) {
        return y !== null;
      }
      if (y === null) {
        return x !== null;
      }
      if (x === undefined) {
        return y !== undefined;
      }
      if (y === undefined) {
        return x !== undefined;
      }
      return !equalScalar(x, y);
    }
  });
});

var name$2w = 'partitionSelect';
var dependencies$2w = ['typed', 'isNumeric', 'isNaN', 'compare'];
var createPartitionSelect = /* #__PURE__ */factory(name$2w, dependencies$2w, _ref => {
  var {
    typed,
    isNumeric,
    isNaN,
    compare
  } = _ref;
  var asc = compare;
  var desc = (a, b) => -compare(a, b);

  /**
   * Partition-based selection of an array or 1D matrix.
   * Will find the kth smallest value, and mutates the input array.
   * Uses Quickselect.
   *
   * Syntax:
   *
   *    math.partitionSelect(x, k)
   *    math.partitionSelect(x, k, compare)
   *
   * Examples:
   *
   *    math.partitionSelect([5, 10, 1], 2)                               // returns 10
   *    math.partitionSelect(['C', 'B', 'A', 'D'], 1, math.compareText)   // returns 'B'
   *
   *    function sortByLength (a, b) {
   *      return a.length - b.length
   *    }
   *    math.partitionSelect(['Langdon', 'Tom', 'Sara'], 2, sortByLength) // returns 'Langdon'
   *
   *    // the input array is mutated
   *    arr = [5, 2, 1]
   *    math.partitionSelect(arr, 0) // returns 1, arr is now: [1, 2, 5]
   *    math.partitionSelect(arr, 1, 'desc') // returns 2, arr is now: [5, 2, 1]
   *
   * See also:
   *
   *    sort
   *
   * @param {Matrix | Array} x    A one dimensional matrix or array to sort
   * @param {Number} k            The kth smallest value to be retrieved zero-based index
   * @param {Function | 'asc' | 'desc'} [compare='asc']
   *        An optional comparator function. The function is called as
   *        `compare(a, b)`, and must return 1 when a > b, -1 when a < b,
   *        and 0 when a == b.
   * @return {*} Returns the kth lowest value.
   */
  return typed(name$2w, {
    'Array | Matrix, number': function ArrayMatrixNumber(x, k) {
      return _partitionSelect(x, k, asc);
    },
    'Array | Matrix, number, string': function ArrayMatrixNumberString(x, k, compare) {
      if (compare === 'asc') {
        return _partitionSelect(x, k, asc);
      } else if (compare === 'desc') {
        return _partitionSelect(x, k, desc);
      } else {
        throw new Error('Compare string must be "asc" or "desc"');
      }
    },
    'Array | Matrix, number, function': _partitionSelect
  });
  function _partitionSelect(x, k, compare) {
    if (!isInteger(k) || k < 0) {
      throw new Error('k must be a non-negative integer');
    }
    if (isMatrix(x)) {
      var size = x.size();
      if (size.length > 1) {
        throw new Error('Only one dimensional matrices supported');
      }
      return quickSelect(x.valueOf(), k, compare);
    }
    if (Array.isArray(x)) {
      return quickSelect(x, k, compare);
    }
  }

  /**
   * Quickselect algorithm.
   * Code adapted from:
   * https://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html
   *
   * @param {Array} arr
   * @param {Number} k
   * @param {Function} compare
   * @private
   */
  function quickSelect(arr, k, compare) {
    if (k >= arr.length) {
      throw new Error('k out of bounds');
    }

    // check for NaN values since these can cause an infinite while loop
    for (var i = 0; i < arr.length; i++) {
      if (isNumeric(arr[i]) && isNaN(arr[i])) {
        return arr[i]; // return NaN
      }
    }
    var from = 0;
    var to = arr.length - 1;

    // if from == to we reached the kth element
    while (from < to) {
      var r = from;
      var w = to;
      var pivot = arr[Math.floor(Math.random() * (to - from + 1)) + from];

      // stop if the reader and writer meets
      while (r < w) {
        // arr[r] >= pivot
        if (compare(arr[r], pivot) >= 0) {
          // put the large values at the end
          var tmp = arr[w];
          arr[w] = arr[r];
          arr[r] = tmp;
          --w;
        } else {
          // the value is smaller than the pivot, skip
          ++r;
        }
      }

      // if we stepped up (r++) we need to step one down (arr[r] > pivot)
      if (compare(arr[r], pivot) > 0) {
        --r;
      }

      // the r pointer is on the end of the first k elements
      if (k <= r) {
        to = r;
      } else {
        from = r + 1;
      }
    }
    return arr[k];
  }
});

var name$2v = 'sort';
var dependencies$2v = ['typed', 'matrix', 'compare', 'compareNatural'];
var createSort = /* #__PURE__ */factory(name$2v, dependencies$2v, _ref => {
  var {
    typed,
    matrix,
    compare,
    compareNatural
  } = _ref;
  var compareAsc = compare;
  var compareDesc = (a, b) => -compare(a, b);

  /**
   * Sort the items in a matrix.
   *
   * Syntax:
   *
   *    math.sort(x)
   *    math.sort(x, compare)
   *
   * Examples:
   *
   *    math.sort([5, 10, 1]) // returns [1, 5, 10]
   *    math.sort(['C', 'B', 'A', 'D'], math.compareNatural)
   *    // returns ['A', 'B', 'C', 'D']
   *
   *    function sortByLength (a, b) {
   *      return a.length - b.length
   *    }
   *    math.sort(['Langdon', 'Tom', 'Sara'], sortByLength)
   *    // returns ['Tom', 'Sara', 'Langdon']
   *
   * See also:
   *
   *    filter, forEach, map, compare, compareNatural
   *
   * @param {Matrix | Array} x    A one dimensional matrix or array to sort
   * @param {Function | 'asc' | 'desc' | 'natural'} [compare='asc']
   *        An optional _comparator function or name. The function is called as
   *        `compare(a, b)`, and must return 1 when a > b, -1 when a < b,
   *        and 0 when a == b.
   * @return {Matrix | Array} Returns the sorted matrix.
   */
  return typed(name$2v, {
    Array: function Array(x) {
      _arrayIsVector(x);
      return x.sort(compareAsc);
    },
    Matrix: function Matrix(x) {
      _matrixIsVector(x);
      return matrix(x.toArray().sort(compareAsc), x.storage());
    },
    'Array, function': function ArrayFunction(x, _comparator) {
      _arrayIsVector(x);
      return x.sort(_comparator);
    },
    'Matrix, function': function MatrixFunction(x, _comparator) {
      _matrixIsVector(x);
      return matrix(x.toArray().sort(_comparator), x.storage());
    },
    'Array, string': function ArrayString(x, order) {
      _arrayIsVector(x);
      return x.sort(_comparator(order));
    },
    'Matrix, string': function MatrixString(x, order) {
      _matrixIsVector(x);
      return matrix(x.toArray().sort(_comparator(order)), x.storage());
    }
  });

  /**
   * Get the comparator for given order ('asc', 'desc', 'natural')
   * @param {'asc' | 'desc' | 'natural'} order
   * @return {Function} Returns a _comparator function
   */
  function _comparator(order) {
    if (order === 'asc') {
      return compareAsc;
    } else if (order === 'desc') {
      return compareDesc;
    } else if (order === 'natural') {
      return compareNatural;
    } else {
      throw new Error('String "asc", "desc", or "natural" expected');
    }
  }

  /**
   * Validate whether an array is one dimensional
   * Throws an error when this is not the case
   * @param {Array} array
   * @private
   */
  function _arrayIsVector(array) {
    if (arraySize(array).length !== 1) {
      throw new Error('One dimensional array expected');
    }
  }

  /**
   * Validate whether a matrix is one dimensional
   * Throws an error when this is not the case
   * @param {Matrix} matrix
   * @private
   */
  function _matrixIsVector(matrix) {
    if (matrix.size().length !== 1) {
      throw new Error('One dimensional matrix expected');
    }
  }
});

var name$2u = 'max';
var dependencies$2u = ['typed', 'config', 'numeric', 'larger'];
var createMax = /* #__PURE__ */factory(name$2u, dependencies$2u, _ref => {
  var {
    typed,
    config,
    numeric,
    larger
  } = _ref;
  /**
   * Compute the maximum value of a matrix or a  list with values.
   * In case of a multidimensional array, the maximum of the flattened array
   * will be calculated. When `dim` is provided, the maximum over the selected
   * dimension will be calculated. Parameter `dim` is zero-based.
   *
   * Syntax:
   *
   *     math.max(a, b, c, ...)
   *     math.max(A)
   *     math.max(A, dimension)
   *
   * Examples:
   *
   *     math.max(2, 1, 4, 3)                  // returns 4
   *     math.max([2, 1, 4, 3])                // returns 4
   *
   *     // maximum over a specified dimension (zero-based)
   *     math.max([[2, 5], [4, 3], [1, 7]], 0) // returns [4, 7]
   *     math.max([[2, 5], [4, 3], [1, 7]], 1) // returns [5, 4, 7]
   *
   *     math.max(2.7, 7.1, -4.5, 2.0, 4.1)    // returns 7.1
   *     math.min(2.7, 7.1, -4.5, 2.0, 4.1)    // returns -4.5
   *
   * See also:
   *
   *    mean, median, min, prod, std, sum, variance
   *
   * @param {... *} args  A single matrix or or multiple scalar values
   * @return {*} The maximum value
   */
  return typed(name$2u, {
    // max([a, b, c, d, ...])
    'Array | Matrix': _max,
    // max([a, b, c, d, ...], dim)
    'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) {
      return reduce(array, dim.valueOf(), _largest);
    },
    // max(a, b, c, d, ...)
    '...': function _(args) {
      if (containsCollections(args)) {
        throw new TypeError('Scalar values expected in function max');
      }
      return _max(args);
    }
  });

  /**
   * Return the largest of two values
   * @param {*} x
   * @param {*} y
   * @returns {*} Returns x when x is largest, or y when y is largest
   * @private
   */
  function _largest(x, y) {
    try {
      return larger(x, y) ? x : y;
    } catch (err) {
      throw improveErrorMessage(err, 'max', y);
    }
  }

  /**
   * Recursively calculate the maximum value in an n-dimensional array
   * @param {Array} array
   * @return {number} max
   * @private
   */
  function _max(array) {
    var res;
    deepForEach(array, function (value) {
      try {
        if (isNaN(value) && typeof value === 'number') {
          res = NaN;
        } else if (res === undefined || larger(value, res)) {
          res = value;
        }
      } catch (err) {
        throw improveErrorMessage(err, 'max', value);
      }
    });
    if (res === undefined) {
      throw new Error('Cannot calculate max of an empty array');
    }

    // make sure returning numeric value: parse a string into a numeric value
    if (typeof res === 'string') {
      res = numeric(res, safeNumberType(res, config));
    }
    return res;
  }
});

var name$2t = 'min';
var dependencies$2t = ['typed', 'config', 'numeric', 'smaller'];
var createMin = /* #__PURE__ */factory(name$2t, dependencies$2t, _ref => {
  var {
    typed,
    config,
    numeric,
    smaller
  } = _ref;
  /**
   * Compute the minimum value of a matrix or a  list of values.
   * In case of a multidimensional array, the minimum of the flattened array
   * will be calculated. When `dim` is provided, the minimum over the selected
   * dimension will be calculated. Parameter `dim` is zero-based.
   *
   * Syntax:
   *
   *     math.min(a, b, c, ...)
   *     math.min(A)
   *     math.min(A, dimension)
   *
   * Examples:
   *
   *     math.min(2, 1, 4, 3)                  // returns 1
   *     math.min([2, 1, 4, 3])                // returns 1
   *
   *     // minimum over a specified dimension (zero-based)
   *     math.min([[2, 5], [4, 3], [1, 7]], 0) // returns [1, 3]
   *     math.min([[2, 5], [4, 3], [1, 7]], 1) // returns [2, 3, 1]
   *
   *     math.max(2.7, 7.1, -4.5, 2.0, 4.1)    // returns 7.1
   *     math.min(2.7, 7.1, -4.5, 2.0, 4.1)    // returns -4.5
   *
   * See also:
   *
   *    mean, median, max, prod, std, sum, variance
   *
   * @param {... *} args  A single matrix or or multiple scalar values
   * @return {*} The minimum value
   */
  return typed(name$2t, {
    // min([a, b, c, d, ...])
    'Array | Matrix': _min,
    // min([a, b, c, d, ...], dim)
    'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) {
      return reduce(array, dim.valueOf(), _smallest);
    },
    // min(a, b, c, d, ...)
    '...': function _(args) {
      if (containsCollections(args)) {
        throw new TypeError('Scalar values expected in function min');
      }
      return _min(args);
    }
  });

  /**
   * Return the smallest of two values
   * @param {*} x
   * @param {*} y
   * @returns {*} Returns x when x is smallest, or y when y is smallest
   * @private
   */
  function _smallest(x, y) {
    try {
      return smaller(x, y) ? x : y;
    } catch (err) {
      throw improveErrorMessage(err, 'min', y);
    }
  }

  /**
   * Recursively calculate the minimum value in an n-dimensional array
   * @param {Array} array
   * @return {number} min
   * @private
   */
  function _min(array) {
    var min;
    deepForEach(array, function (value) {
      try {
        if (isNaN(value) && typeof value === 'number') {
          min = NaN;
        } else if (min === undefined || smaller(value, min)) {
          min = value;
        }
      } catch (err) {
        throw improveErrorMessage(err, 'min', value);
      }
    });
    if (min === undefined) {
      throw new Error('Cannot calculate min of an empty array');
    }

    // make sure returning numeric value: parse a string into a numeric value
    if (typeof min === 'string') {
      min = numeric(min, safeNumberType(min, config));
    }
    return min;
  }
});

var name$2s = 'ImmutableDenseMatrix';
var dependencies$2s = ['smaller', 'DenseMatrix'];
var createImmutableDenseMatrixClass = /* #__PURE__ */factory(name$2s, dependencies$2s, _ref => {
  var {
    smaller,
    DenseMatrix
  } = _ref;
  function ImmutableDenseMatrix(data, datatype) {
    if (!(this instanceof ImmutableDenseMatrix)) {
      throw new SyntaxError('Constructor must be called with the new operator');
    }
    if (datatype && !isString(datatype)) {
      throw new Error('Invalid datatype: ' + datatype);
    }
    if (isMatrix(data) || isArray(data)) {
      // use DenseMatrix implementation
      var matrix = new DenseMatrix(data, datatype);
      // internal structures
      this._data = matrix._data;
      this._size = matrix._size;
      this._datatype = matrix._datatype;
      this._min = null;
      this._max = null;
    } else if (data && isArray(data.data) && isArray(data.size)) {
      // initialize fields from JSON representation
      this._data = data.data;
      this._size = data.size;
      this._datatype = data.datatype;
      this._min = typeof data.min !== 'undefined' ? data.min : null;
      this._max = typeof data.max !== 'undefined' ? data.max : null;
    } else if (data) {
      // unsupported type
      throw new TypeError('Unsupported type of data (' + typeOf(data) + ')');
    } else {
      // nothing provided
      this._data = [];
      this._size = [0];
      this._datatype = datatype;
      this._min = null;
      this._max = null;
    }
  }
  ImmutableDenseMatrix.prototype = new DenseMatrix();

  /**
   * Attach type information
   */
  ImmutableDenseMatrix.prototype.type = 'ImmutableDenseMatrix';
  ImmutableDenseMatrix.prototype.isImmutableDenseMatrix = true;

  /**
   * Get a subset of the matrix, or replace a subset of the matrix.
   *
   * Usage:
   *     const subset = matrix.subset(index)               // retrieve subset
   *     const value = matrix.subset(index, replacement)   // replace subset
   *
   * @param {Index} index
   * @param {Array | ImmutableDenseMatrix | *} [replacement]
   * @param {*} [defaultValue=0]      Default value, filled in on new entries when
   *                                  the matrix is resized. If not provided,
   *                                  new matrix elements will be filled with zeros.
   */
  ImmutableDenseMatrix.prototype.subset = function (index) {
    switch (arguments.length) {
      case 1:
        {
          // use base implementation
          var m = DenseMatrix.prototype.subset.call(this, index);
          // check result is a matrix
          if (isMatrix(m)) {
            // return immutable matrix
            return new ImmutableDenseMatrix({
              data: m._data,
              size: m._size,
              datatype: m._datatype
            });
          }
          return m;
        }
      // intentional fall through
      case 2:
      case 3:
        throw new Error('Cannot invoke set subset on an Immutable Matrix instance');
      default:
        throw new SyntaxError('Wrong number of arguments');
    }
  };

  /**
   * Replace a single element in the matrix.
   * @param {Number[]} index   Zero-based index
   * @param {*} value
   * @param {*} [defaultValue]        Default value, filled in on new entries when
   *                                  the matrix is resized. If not provided,
   *                                  new matrix elements will be left undefined.
   * @return {ImmutableDenseMatrix} self
   */
  ImmutableDenseMatrix.prototype.set = function () {
    throw new Error('Cannot invoke set on an Immutable Matrix instance');
  };

  /**
   * Resize the matrix to the given size. Returns a copy of the matrix when
   * `copy=true`, otherwise return the matrix itself (resize in place).
   *
   * @param {Number[]} size           The new size the matrix should have.
   * @param {*} [defaultValue=0]      Default value, filled in on new entries.
   *                                  If not provided, the matrix elements will
   *                                  be filled with zeros.
   * @param {boolean} [copy]          Return a resized copy of the matrix
   *
   * @return {Matrix}                 The resized matrix
   */
  ImmutableDenseMatrix.prototype.resize = function () {
    throw new Error('Cannot invoke resize on an Immutable Matrix instance');
  };

  /**
   * Disallows reshaping in favor of immutability.
   *
   * @throws {Error} Operation not allowed
   */
  ImmutableDenseMatrix.prototype.reshape = function () {
    throw new Error('Cannot invoke reshape on an Immutable Matrix instance');
  };

  /**
   * Create a clone of the matrix
   * @return {ImmutableDenseMatrix} clone
   */
  ImmutableDenseMatrix.prototype.clone = function () {
    return new ImmutableDenseMatrix({
      data: clone$2(this._data),
      size: clone$2(this._size),
      datatype: this._datatype
    });
  };

  /**
   * Get a JSON representation of the matrix
   * @returns {Object}
   */
  ImmutableDenseMatrix.prototype.toJSON = function () {
    return {
      mathjs: 'ImmutableDenseMatrix',
      data: this._data,
      size: this._size,
      datatype: this._datatype
    };
  };

  /**
   * Generate a matrix from a JSON object
   * @param {Object} json  An object structured like
   *                       `{"mathjs": "ImmutableDenseMatrix", data: [], size: []}`,
   *                       where mathjs is optional
   * @returns {ImmutableDenseMatrix}
   */
  ImmutableDenseMatrix.fromJSON = function (json) {
    return new ImmutableDenseMatrix(json);
  };

  /**
   * Swap rows i and j in Matrix.
   *
   * @param {Number} i       Matrix row index 1
   * @param {Number} j       Matrix row index 2
   *
   * @return {Matrix}        The matrix reference
   */
  ImmutableDenseMatrix.prototype.swapRows = function () {
    throw new Error('Cannot invoke swapRows on an Immutable Matrix instance');
  };

  /**
   * Calculate the minimum value in the set
   * @return {Number | undefined} min
   */
  ImmutableDenseMatrix.prototype.min = function () {
    // check min has been calculated before
    if (this._min === null) {
      // minimum
      var m = null;
      // compute min
      this.forEach(function (v) {
        if (m === null || smaller(v, m)) {
          m = v;
        }
      });
      this._min = m !== null ? m : undefined;
    }
    return this._min;
  };

  /**
   * Calculate the maximum value in the set
   * @return {Number | undefined} max
   */
  ImmutableDenseMatrix.prototype.max = function () {
    // check max has been calculated before
    if (this._max === null) {
      // maximum
      var m = null;
      // compute max
      this.forEach(function (v) {
        if (m === null || smaller(m, v)) {
          m = v;
        }
      });
      this._max = m !== null ? m : undefined;
    }
    return this._max;
  };
  return ImmutableDenseMatrix;
}, {
  isClass: true
});

var name$2r = 'Index';
var dependencies$2r = ['ImmutableDenseMatrix', 'getMatrixDataType'];
var createIndexClass = /* #__PURE__ */factory(name$2r, dependencies$2r, _ref => {
  var {
    ImmutableDenseMatrix,
    getMatrixDataType
  } = _ref;
  /**
   * Create an index. An Index can store ranges and sets for multiple dimensions.
   * Matrix.get, Matrix.set, and math.subset accept an Index as input.
   *
   * Usage:
   *     const index = new Index(range1, range2, matrix1, array1, ...)
   *
   * Where each parameter can be any of:
   *     A number
   *     A string (containing a name of an object property)
   *     An instance of Range
   *     An Array with the Set values
   *     An Array with Booleans
   *     A Matrix with the Set values
   *     A Matrix with Booleans
   *
   * The parameters start, end, and step must be integer numbers.
   *
   * @class Index
   * @Constructor Index
   * @param {...*} ranges
   */
  function Index(ranges) {
    if (!(this instanceof Index)) {
      throw new SyntaxError('Constructor must be called with the new operator');
    }
    this._dimensions = [];
    this._sourceSize = [];
    this._isScalar = true;
    for (var i = 0, ii = arguments.length; i < ii; i++) {
      var arg = arguments[i];
      var argIsArray = isArray(arg);
      var argIsMatrix = isMatrix(arg);
      var sourceSize = null;
      if (isRange(arg)) {
        this._dimensions.push(arg);
        this._isScalar = false;
      } else if (argIsArray || argIsMatrix) {
        // create matrix
        var m = void 0;
        if (getMatrixDataType(arg) === 'boolean') {
          if (argIsArray) m = _createImmutableMatrix(_booleansArrayToNumbersForIndex(arg).valueOf());
          if (argIsMatrix) m = _createImmutableMatrix(_booleansArrayToNumbersForIndex(arg._data).valueOf());
          sourceSize = arg.valueOf().length;
        } else {
          m = _createImmutableMatrix(arg.valueOf());
        }
        this._dimensions.push(m);
        // size
        var size = m.size();
        // scalar
        if (size.length !== 1 || size[0] !== 1 || sourceSize !== null) {
          this._isScalar = false;
        }
      } else if (typeof arg === 'number') {
        this._dimensions.push(_createImmutableMatrix([arg]));
      } else if (typeof arg === 'string') {
        // object property (arguments.count should be 1)
        this._dimensions.push(arg);
      } else {
        throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range');
      }
      this._sourceSize.push(sourceSize);
      // TODO: implement support for wildcard '*'
    }
  }

  /**
   * Attach type information
   */
  Index.prototype.type = 'Index';
  Index.prototype.isIndex = true;
  function _createImmutableMatrix(arg) {
    // loop array elements
    for (var i = 0, l = arg.length; i < l; i++) {
      if (typeof arg[i] !== 'number' || !isInteger(arg[i])) {
        throw new TypeError('Index parameters must be positive integer numbers');
      }
    }
    // create matrix
    return new ImmutableDenseMatrix(arg);
  }

  /**
   * Create a clone of the index
   * @memberof Index
   * @return {Index} clone
   */
  Index.prototype.clone = function () {
    var index = new Index();
    index._dimensions = clone$2(this._dimensions);
    index._isScalar = this._isScalar;
    index._sourceSize = this._sourceSize;
    return index;
  };

  /**
   * Create an index from an array with ranges/numbers
   * @memberof Index
   * @param {Array.<Array | number>} ranges
   * @return {Index} index
   * @private
   */
  Index.create = function (ranges) {
    var index = new Index();
    Index.apply(index, ranges);
    return index;
  };

  /**
   * Retrieve the size of the index, the number of elements for each dimension.
   * @memberof Index
   * @returns {number[]} size
   */
  Index.prototype.size = function () {
    var size = [];
    for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
      var d = this._dimensions[i];
      size[i] = typeof d === 'string' ? 1 : d.size()[0];
    }
    return size;
  };

  /**
   * Get the maximum value for each of the indexes ranges.
   * @memberof Index
   * @returns {number[]} max
   */
  Index.prototype.max = function () {
    var values = [];
    for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
      var range = this._dimensions[i];
      values[i] = typeof range === 'string' ? range : range.max();
    }
    return values;
  };

  /**
   * Get the minimum value for each of the indexes ranges.
   * @memberof Index
   * @returns {number[]} min
   */
  Index.prototype.min = function () {
    var values = [];
    for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
      var range = this._dimensions[i];
      values[i] = typeof range === 'string' ? range : range.min();
    }
    return values;
  };

  /**
   * Loop over each of the ranges of the index
   * @memberof Index
   * @param {Function} callback   Called for each range with a Range as first
   *                              argument, the dimension as second, and the
   *                              index object as third.
   */
  Index.prototype.forEach = function (callback) {
    for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
      callback(this._dimensions[i], i, this);
    }
  };

  /**
   * Retrieve the dimension for the given index
   * @memberof Index
   * @param {Number} dim                  Number of the dimension
   * @returns {Range | null} range
   */
  Index.prototype.dimension = function (dim) {
    return this._dimensions[dim] || null;
  };

  /**
   * Test whether this index contains an object property
   * @returns {boolean} Returns true if the index is an object property
   */
  Index.prototype.isObjectProperty = function () {
    return this._dimensions.length === 1 && typeof this._dimensions[0] === 'string';
  };

  /**
   * Returns the object property name when the Index holds a single object property,
   * else returns null
   * @returns {string | null}
   */
  Index.prototype.getObjectProperty = function () {
    return this.isObjectProperty() ? this._dimensions[0] : null;
  };

  /**
   * Test whether this index contains only a single value.
   *
   * This is the case when the index is created with only scalar values as ranges,
   * not for ranges resolving into a single value.
   * @memberof Index
   * @return {boolean} isScalar
   */
  Index.prototype.isScalar = function () {
    return this._isScalar;
  };

  /**
   * Expand the Index into an array.
   * For example new Index([0,3], [2,7]) returns [[0,1,2], [2,3,4,5,6]]
   * @memberof Index
   * @returns {Array} array
   */
  Index.prototype.toArray = function () {
    var array = [];
    for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
      var dimension = this._dimensions[i];
      array.push(typeof dimension === 'string' ? dimension : dimension.toArray());
    }
    return array;
  };

  /**
   * Get the primitive value of the Index, a two dimensional array.
   * Equivalent to Index.toArray().
   * @memberof Index
   * @returns {Array} array
   */
  Index.prototype.valueOf = Index.prototype.toArray;

  /**
   * Get the string representation of the index, for example '[2:6]' or '[0:2:10, 4:7, [1,2,3]]'
   * @memberof Index
   * @returns {String} str
   */
  Index.prototype.toString = function () {
    var strings = [];
    for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
      var dimension = this._dimensions[i];
      if (typeof dimension === 'string') {
        strings.push(JSON.stringify(dimension));
      } else {
        strings.push(dimension.toString());
      }
    }
    return '[' + strings.join(', ') + ']';
  };

  /**
   * Get a JSON representation of the Index
   * @memberof Index
   * @returns {Object} Returns a JSON object structured as:
   *                   `{"mathjs": "Index", "ranges": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}`
   */
  Index.prototype.toJSON = function () {
    return {
      mathjs: 'Index',
      dimensions: this._dimensions
    };
  };

  /**
   * Instantiate an Index from a JSON object
   * @memberof Index
   * @param {Object} json A JSON object structured as:
   *                     `{"mathjs": "Index", "dimensions": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}`
   * @return {Index}
   */
  Index.fromJSON = function (json) {
    return Index.create(json.dimensions);
  };
  return Index;
}, {
  isClass: true
});

/**
 * Receives an array of booleans and returns an array of Numbers for Index
 * @param {Array} booleanArrayIndex An array of booleans
 * @return {Array} A set of numbers ready for index
 */
function _booleansArrayToNumbersForIndex(booleanArrayIndex) {
  // gets an array of booleans and returns an array of numbers
  var indexOfNumbers = [];
  booleanArrayIndex.forEach((bool, idx) => {
    if (bool) {
      indexOfNumbers.push(idx);
    }
  });
  return indexOfNumbers;
}

var name$2q = 'FibonacciHeap';
var dependencies$2q = ['smaller', 'larger'];
var createFibonacciHeapClass = /* #__PURE__ */factory(name$2q, dependencies$2q, _ref => {
  var {
    smaller,
    larger
  } = _ref;
  var oneOverLogPhi = 1.0 / Math.log((1.0 + Math.sqrt(5.0)) / 2.0);

  /**
   * Fibonacci Heap implementation, used interally for Matrix math.
   * @class FibonacciHeap
   * @constructor FibonacciHeap
   */
  function FibonacciHeap() {
    if (!(this instanceof FibonacciHeap)) {
      throw new SyntaxError('Constructor must be called with the new operator');
    }

    // initialize fields
    this._minimum = null;
    this._size = 0;
  }

  /**
   * Attach type information
   */
  FibonacciHeap.prototype.type = 'FibonacciHeap';
  FibonacciHeap.prototype.isFibonacciHeap = true;

  /**
   * Inserts a new data element into the heap. No heap consolidation is
   * performed at this time, the new node is simply inserted into the root
   * list of this heap. Running time: O(1) actual.
   * @memberof FibonacciHeap
   */
  FibonacciHeap.prototype.insert = function (key, value) {
    // create node
    var node = {
      key,
      value,
      degree: 0
    };
    // check we have a node in the minimum
    if (this._minimum) {
      // minimum node
      var minimum = this._minimum;
      // update left & right of node
      node.left = minimum;
      node.right = minimum.right;
      minimum.right = node;
      node.right.left = node;
      // update minimum node in heap if needed
      if (smaller(key, minimum.key)) {
        // node has a smaller key, use it as minimum
        this._minimum = node;
      }
    } else {
      // set left & right
      node.left = node;
      node.right = node;
      // this is the first node
      this._minimum = node;
    }
    // increment number of nodes in heap
    this._size++;
    // return node
    return node;
  };

  /**
   * Returns the number of nodes in heap. Running time: O(1) actual.
   * @memberof FibonacciHeap
   */
  FibonacciHeap.prototype.size = function () {
    return this._size;
  };

  /**
   * Removes all elements from this heap.
   * @memberof FibonacciHeap
   */
  FibonacciHeap.prototype.clear = function () {
    this._minimum = null;
    this._size = 0;
  };

  /**
   * Returns true if the heap is empty, otherwise false.
   * @memberof FibonacciHeap
   */
  FibonacciHeap.prototype.isEmpty = function () {
    return this._size === 0;
  };

  /**
   * Extracts the node with minimum key from heap. Amortized running
   * time: O(log n).
   * @memberof FibonacciHeap
   */
  FibonacciHeap.prototype.extractMinimum = function () {
    // node to remove
    var node = this._minimum;
    // check we have a minimum
    if (node === null) {
      return node;
    }
    // current minimum
    var minimum = this._minimum;
    // get number of children
    var numberOfChildren = node.degree;
    // pointer to the first child
    var x = node.child;
    // for each child of node do...
    while (numberOfChildren > 0) {
      // store node in right side
      var tempRight = x.right;
      // remove x from child list
      x.left.right = x.right;
      x.right.left = x.left;
      // add x to root list of heap
      x.left = minimum;
      x.right = minimum.right;
      minimum.right = x;
      x.right.left = x;
      // set Parent[x] to null
      x.parent = null;
      x = tempRight;
      numberOfChildren--;
    }
    // remove node from root list of heap
    node.left.right = node.right;
    node.right.left = node.left;
    // update minimum
    if (node === node.right) {
      // empty
      minimum = null;
    } else {
      // update minimum
      minimum = node.right;
      // we need to update the pointer to the root with minimum key
      minimum = _findMinimumNode(minimum, this._size);
    }
    // decrement size of heap
    this._size--;
    // update minimum
    this._minimum = minimum;
    // return node
    return node;
  };

  /**
   * Removes a node from the heap given the reference to the node. The trees
   * in the heap will be consolidated, if necessary. This operation may fail
   * to remove the correct element if there are nodes with key value -Infinity.
   * Running time: O(log n) amortized.
   * @memberof FibonacciHeap
   */
  FibonacciHeap.prototype.remove = function (node) {
    // decrease key value
    this._minimum = _decreaseKey(this._minimum, node, -1);
    // remove the smallest
    this.extractMinimum();
  };

  /**
   * Decreases the key value for a heap node, given the new value to take on.
   * The structure of the heap may be changed and will not be consolidated.
   * Running time: O(1) amortized.
   * @memberof FibonacciHeap
   */
  function _decreaseKey(minimum, node, key) {
    // set node key
    node.key = key;
    // get parent node
    var parent = node.parent;
    if (parent && smaller(node.key, parent.key)) {
      // remove node from parent
      _cut(minimum, node, parent);
      // remove all nodes from parent to the root parent
      _cascadingCut(minimum, parent);
    }
    // update minimum node if needed
    if (smaller(node.key, minimum.key)) {
      minimum = node;
    }
    // return minimum
    return minimum;
  }

  /**
   * The reverse of the link operation: removes node from the child list of parent.
   * This method assumes that min is non-null. Running time: O(1).
   * @memberof FibonacciHeap
   */
  function _cut(minimum, node, parent) {
    // remove node from parent children and decrement Degree[parent]
    node.left.right = node.right;
    node.right.left = node.left;
    parent.degree--;
    // reset y.child if necessary
    if (parent.child === node) {
      parent.child = node.right;
    }
    // remove child if degree is 0
    if (parent.degree === 0) {
      parent.child = null;
    }
    // add node to root list of heap
    node.left = minimum;
    node.right = minimum.right;
    minimum.right = node;
    node.right.left = node;
    // set parent[node] to null
    node.parent = null;
    // set mark[node] to false
    node.mark = false;
  }

  /**
   * Performs a cascading cut operation. This cuts node from its parent and then
   * does the same for its parent, and so on up the tree.
   * Running time: O(log n); O(1) excluding the recursion.
   * @memberof FibonacciHeap
   */
  function _cascadingCut(minimum, node) {
    // store parent node
    var parent = node.parent;
    // if there's a parent...
    if (!parent) {
      return;
    }
    // if node is unmarked, set it marked
    if (!node.mark) {
      node.mark = true;
    } else {
      // it's marked, cut it from parent
      _cut(minimum, node, parent);
      // cut its parent as well
      _cascadingCut(parent);
    }
  }

  /**
   * Make the first node a child of the second one. Running time: O(1) actual.
   * @memberof FibonacciHeap
   */
  var _linkNodes = function _linkNodes(node, parent) {
    // remove node from root list of heap
    node.left.right = node.right;
    node.right.left = node.left;
    // make node a Child of parent
    node.parent = parent;
    if (!parent.child) {
      parent.child = node;
      node.right = node;
      node.left = node;
    } else {
      node.left = parent.child;
      node.right = parent.child.right;
      parent.child.right = node;
      node.right.left = node;
    }
    // increase degree[parent]
    parent.degree++;
    // set mark[node] false
    node.mark = false;
  };
  function _findMinimumNode(minimum, size) {
    // to find trees of the same degree efficiently we use an array of length O(log n) in which we keep a pointer to one root of each degree
    var arraySize = Math.floor(Math.log(size) * oneOverLogPhi) + 1;
    // create list with initial capacity
    var array = new Array(arraySize);
    // find the number of root nodes.
    var numRoots = 0;
    var x = minimum;
    if (x) {
      numRoots++;
      x = x.right;
      while (x !== minimum) {
        numRoots++;
        x = x.right;
      }
    }
    // vars
    var y;
    // For each node in root list do...
    while (numRoots > 0) {
      // access this node's degree..
      var d = x.degree;
      // get next node
      var next = x.right;
      // check if there is a node already in array with the same degree
      while (true) {
        // get node with the same degree is any
        y = array[d];
        if (!y) {
          break;
        }
        // make one node with the same degree a child of the other, do this based on the key value.
        if (larger(x.key, y.key)) {
          var temp = y;
          y = x;
          x = temp;
        }
        // make y a child of x
        _linkNodes(y, x);
        // we have handled this degree, go to next one.
        array[d] = null;
        d++;
      }
      // save this node for later when we might encounter another of the same degree.
      array[d] = x;
      // move forward through list.
      x = next;
      numRoots--;
    }
    // Set min to null (effectively losing the root list) and reconstruct the root list from the array entries in array[].
    minimum = null;
    // loop nodes in array
    for (var i = 0; i < arraySize; i++) {
      // get current node
      y = array[i];
      if (!y) {
        continue;
      }
      // check if we have a linked list
      if (minimum) {
        // First remove node from root list.
        y.left.right = y.right;
        y.right.left = y.left;
        // now add to root list, again.
        y.left = minimum;
        y.right = minimum.right;
        minimum.right = y;
        y.right.left = y;
        // check if this is a new min.
        if (smaller(y.key, minimum.key)) {
          minimum = y;
        }
      } else {
        minimum = y;
      }
    }
    return minimum;
  }
  return FibonacciHeap;
}, {
  isClass: true
});

var name$2p = 'Spa';
var dependencies$2p = ['addScalar', 'equalScalar', 'FibonacciHeap'];
var createSpaClass = /* #__PURE__ */factory(name$2p, dependencies$2p, _ref => {
  var {
    addScalar,
    equalScalar,
    FibonacciHeap
  } = _ref;
  /**
   * An ordered Sparse Accumulator is a representation for a sparse vector that includes a dense array
   * of the vector elements and an ordered list of non-zero elements.
   */
  function Spa() {
    if (!(this instanceof Spa)) {
      throw new SyntaxError('Constructor must be called with the new operator');
    }

    // allocate vector, TODO use typed arrays
    this._values = [];
    this._heap = new FibonacciHeap();
  }

  /**
   * Attach type information
   */
  Spa.prototype.type = 'Spa';
  Spa.prototype.isSpa = true;

  /**
   * Set the value for index i.
   *
   * @param {number} i                       The index
   * @param {number | BigNumber | Complex}   The value at index i
   */
  Spa.prototype.set = function (i, v) {
    // check we have a value @ i
    if (!this._values[i]) {
      // insert in heap
      var node = this._heap.insert(i, v);
      // set the value @ i
      this._values[i] = node;
    } else {
      // update the value @ i
      this._values[i].value = v;
    }
  };
  Spa.prototype.get = function (i) {
    var node = this._values[i];
    if (node) {
      return node.value;
    }
    return 0;
  };
  Spa.prototype.accumulate = function (i, v) {
    // node @ i
    var node = this._values[i];
    if (!node) {
      // insert in heap
      node = this._heap.insert(i, v);
      // initialize value
      this._values[i] = node;
    } else {
      // accumulate value
      node.value = addScalar(node.value, v);
    }
  };
  Spa.prototype.forEach = function (from, to, callback) {
    // references
    var heap = this._heap;
    var values = this._values;
    // nodes
    var nodes = [];
    // node with minimum key, save it
    var node = heap.extractMinimum();
    if (node) {
      nodes.push(node);
    }
    // extract nodes from heap (ordered)
    while (node && node.key <= to) {
      // check it is in range
      if (node.key >= from) {
        // check value is not zero
        if (!equalScalar(node.value, 0)) {
          // invoke callback
          callback(node.key, node.value, this);
        }
      }
      // extract next node, save it
      node = heap.extractMinimum();
      if (node) {
        nodes.push(node);
      }
    }
    // reinsert all nodes in heap
    for (var i = 0; i < nodes.length; i++) {
      // current node
      var n = nodes[i];
      // insert node in heap
      node = heap.insert(n.key, n.value);
      // update values
      values[node.key] = node;
    }
  };
  Spa.prototype.swap = function (i, j) {
    // node @ i and j
    var nodei = this._values[i];
    var nodej = this._values[j];
    // check we need to insert indeces
    if (!nodei && nodej) {
      // insert in heap
      nodei = this._heap.insert(i, nodej.value);
      // remove from heap
      this._heap.remove(nodej);
      // set values
      this._values[i] = nodei;
      this._values[j] = undefined;
    } else if (nodei && !nodej) {
      // insert in heap
      nodej = this._heap.insert(j, nodei.value);
      // remove from heap
      this._heap.remove(nodei);
      // set values
      this._values[j] = nodej;
      this._values[i] = undefined;
    } else if (nodei && nodej) {
      // swap values
      var v = nodei.value;
      nodei.value = nodej.value;
      nodej.value = v;
    }
  };
  return Spa;
}, {
  isClass: true
});

/**
 * Calculate BigNumber e
 * @param {function} BigNumber   BigNumber constructor
 * @returns {BigNumber} Returns e
 */
var createBigNumberE = memoize(function (BigNumber) {
  return new BigNumber(1).exp();
}, {
  hasher
});

/**
 * Calculate BigNumber golden ratio, phi = (1+sqrt(5))/2
 * @param {function} BigNumber   BigNumber constructor
 * @returns {BigNumber} Returns phi
 */
var createBigNumberPhi = memoize(function (BigNumber) {
  return new BigNumber(1).plus(new BigNumber(5).sqrt()).div(2);
}, {
  hasher
});

/**
 * Calculate BigNumber pi.
 * @param {function} BigNumber   BigNumber constructor
 * @returns {BigNumber} Returns pi
 */
var createBigNumberPi = memoize(function (BigNumber) {
  return BigNumber.acos(-1);
}, {
  hasher
});

/**
 * Calculate BigNumber tau, tau = 2 * pi
 * @param {function} BigNumber   BigNumber constructor
 * @returns {BigNumber} Returns tau
 */
var createBigNumberTau = memoize(function (BigNumber) {
  return createBigNumberPi(BigNumber).times(2);
}, {
  hasher
});

/**
 * Create a hash for a BigNumber constructor function. The created has is
 * the configured precision
 * @param {Array} args         Supposed to contain a single entry with
 *                             a BigNumber constructor
 * @return {number} precision
 * @private
 */
function hasher(args) {
  return args[0].precision;
}

function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var name$2o = 'Unit';
var dependencies$2o = ['?on', 'config', 'addScalar', 'subtractScalar', 'multiplyScalar', 'divideScalar', 'pow', 'abs', 'fix', 'round', 'equal', 'isNumeric', 'format', 'number', 'Complex', 'BigNumber', 'Fraction'];
var createUnitClass = /* #__PURE__ */factory(name$2o, dependencies$2o, _ref => {
  var {
    on,
    config,
    addScalar,
    subtractScalar,
    multiplyScalar,
    divideScalar,
    pow,
    abs,
    fix,
    round,
    equal,
    isNumeric,
    format,
    number: _number,
    Complex,
    BigNumber: _BigNumber,
    Fraction: _Fraction
  } = _ref;
  var toNumber = _number;
  /**
   * A unit can be constructed in the following ways:
   *
   *     const a = new Unit(value, valuelessUnit)
   *     const b = new Unit(null, valuelessUnit)
   *     const c = Unit.parse(str)
   *
   * Example usage:
   *
   *     const a = new Unit(5, 'cm')               // 50 mm
   *     const b = Unit.parse('23 kg')             // 23 kg
   *     const c = math.in(a, new Unit(null, 'm')  // 0.05 m
   *     const d = new Unit(9.81, "m/s^2")         // 9.81 m/s^2
   *
   * @class Unit
   * @constructor Unit
   * @param {number | BigNumber | Fraction | Complex | boolean} [value]  A value like 5.2
   * @param {string | Unit} valuelessUnit   A unit without value. Can have prefix, like "cm"
   */
  function Unit(value, valuelessUnit) {
    if (!(this instanceof Unit)) {
      throw new Error('Constructor must be called with the new operator');
    }
    if (!(value === null || value === undefined || isNumeric(value) || isComplex(value))) {
      throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined');
    }
    this.fixPrefix = false; // if true, function format will not search for the
    // best prefix but leave it as initially provided.
    // fixPrefix is set true by the method Unit.to

    // The justification behind this is that if the constructor is explicitly called,
    // the caller wishes the units to be returned exactly as supplied.
    this.skipAutomaticSimplification = true;
    if (valuelessUnit === undefined) {
      this.units = [];
      this.dimensions = BASE_DIMENSIONS.map(x => 0);
    } else if (typeof valuelessUnit === 'string') {
      var u = Unit.parse(valuelessUnit);
      this.units = u.units;
      this.dimensions = u.dimensions;
    } else if (isUnit(valuelessUnit) && valuelessUnit.value === null) {
      // clone from valuelessUnit
      this.fixPrefix = valuelessUnit.fixPrefix;
      this.skipAutomaticSimplification = valuelessUnit.skipAutomaticSimplification;
      this.dimensions = valuelessUnit.dimensions.slice(0);
      this.units = valuelessUnit.units.map(u => _extends$1({}, u));
    } else {
      throw new TypeError('Second parameter in Unit constructor must be a string or valueless Unit');
    }
    this.value = this._normalize(value);
  }

  /**
   * Attach type information
   */
  Object.defineProperty(Unit, 'name', {
    value: 'Unit'
  });
  Unit.prototype.constructor = Unit;
  Unit.prototype.type = 'Unit';
  Unit.prototype.isUnit = true;

  // private variables and functions for the Unit parser
  var text, index, c;
  function skipWhitespace() {
    while (c === ' ' || c === '\t') {
      next();
    }
  }
  function isDigitDot(c) {
    return c >= '0' && c <= '9' || c === '.';
  }
  function isDigit(c) {
    return c >= '0' && c <= '9';
  }
  function next() {
    index++;
    c = text.charAt(index);
  }
  function revert(oldIndex) {
    index = oldIndex;
    c = text.charAt(index);
  }
  function parseNumber() {
    var number = '';
    var oldIndex = index;
    if (c === '+') {
      next();
    } else if (c === '-') {
      number += c;
      next();
    }
    if (!isDigitDot(c)) {
      // a + or - must be followed by a digit
      revert(oldIndex);
      return null;
    }

    // get number, can have a single dot
    if (c === '.') {
      number += c;
      next();
      if (!isDigit(c)) {
        // this is no legal number, it is just a dot
        revert(oldIndex);
        return null;
      }
    } else {
      while (isDigit(c)) {
        number += c;
        next();
      }
      if (c === '.') {
        number += c;
        next();
      }
    }
    while (isDigit(c)) {
      number += c;
      next();
    }

    // check for exponential notation like "2.3e-4" or "1.23e50"
    if (c === 'E' || c === 'e') {
      // 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"

      var tentativeNumber = '';
      var tentativeIndex = index;
      tentativeNumber += c;
      next();
      if (c === '+' || c === '-') {
        tentativeNumber += c;
        next();
      }

      // Scientific notation MUST be followed by an exponent (otherwise we assume it is not scientific notation)
      if (!isDigit(c)) {
        // The e or E must belong to something else, so return the number without the e or E.
        revert(tentativeIndex);
        return number;
      }

      // We can now safely say that this is scientific notation.
      number = number + tentativeNumber;
      while (isDigit(c)) {
        number += c;
        next();
      }
    }
    return number;
  }
  function parseUnit() {
    var unitName = '';

    // Alphanumeric characters only; matches [a-zA-Z0-9]
    while (isDigit(c) || Unit.isValidAlpha(c)) {
      unitName += c;
      next();
    }

    // Must begin with [a-zA-Z]
    var firstC = unitName.charAt(0);
    if (Unit.isValidAlpha(firstC)) {
      return unitName;
    } else {
      return null;
    }
  }
  function parseCharacter(toFind) {
    if (c === toFind) {
      next();
      return toFind;
    } else {
      return null;
    }
  }

  /**
   * Parse a string into a unit. The value of the unit is parsed as number,
   * BigNumber, or Fraction depending on the math.js config setting `number`.
   *
   * Throws an exception if the provided string does not contain a valid unit or
   * cannot be parsed.
   * @memberof Unit
   * @param {string} str        A string like "5.2 inch", "4e2 cm/s^2"
   * @return {Unit} unit
   */
  Unit.parse = function (str, options) {
    options = options || {};
    text = str;
    index = -1;
    c = '';
    if (typeof text !== 'string') {
      throw new TypeError('Invalid argument in Unit.parse, string expected');
    }
    var unit = new Unit();
    unit.units = [];
    var powerMultiplierCurrent = 1;
    var expectingUnit = false;

    // A unit should follow this pattern:
    // [number] ...[ [*/] unit[^number] ]
    // unit[^number] ... [ [*/] unit[^number] ]

    // Rules:
    // number is any floating point number.
    // 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!
    // The string may optionally begin with a number.
    // Each unit may optionally be followed by ^number.
    // Whitespace or a forward slash is recommended between consecutive units, although the following technically is parseable:
    //   2m^2kg/s^2
    // it is not good form. If a unit starts with e, then it could be confused as a floating point number:
    //   4erg

    next();
    skipWhitespace();

    // Optional number at the start of the string
    var valueStr = parseNumber();
    var value = null;
    if (valueStr) {
      if (config.number === 'BigNumber') {
        value = new _BigNumber(valueStr);
      } else if (config.number === 'Fraction') {
        try {
          // not all numbers can be turned in Fractions, for example very small numbers not
          value = new _Fraction(valueStr);
        } catch (err) {
          value = parseFloat(valueStr);
        }
      } else {
        // number
        value = parseFloat(valueStr);
      }
      skipWhitespace(); // Whitespace is not required here

      // handle multiplication or division right after the value, like '1/s'
      if (parseCharacter('*')) {
        powerMultiplierCurrent = 1;
        expectingUnit = true;
      } else if (parseCharacter('/')) {
        powerMultiplierCurrent = -1;
        expectingUnit = true;
      }
    }

    // Stack to keep track of powerMultipliers applied to each parentheses group
    var powerMultiplierStack = [];

    // Running product of all elements in powerMultiplierStack
    var powerMultiplierStackProduct = 1;
    while (true) {
      skipWhitespace();

      // Check for and consume opening parentheses, pushing powerMultiplierCurrent to the stack
      // A '(' will always appear directly before a unit.
      while (c === '(') {
        powerMultiplierStack.push(powerMultiplierCurrent);
        powerMultiplierStackProduct *= powerMultiplierCurrent;
        powerMultiplierCurrent = 1;
        next();
        skipWhitespace();
      }

      // Is there something here?
      var uStr = void 0;
      if (c) {
        var oldC = c;
        uStr = parseUnit();
        if (uStr === null) {
          throw new SyntaxError('Unexpected "' + oldC + '" in "' + text + '" at index ' + index.toString());
        }
      } else {
        // End of input.
        break;
      }

      // Verify the unit exists and get the prefix (if any)
      var res = _findUnit(uStr);
      if (res === null) {
        // Unit not found.
        throw new SyntaxError('Unit "' + uStr + '" not found.');
      }
      var power = powerMultiplierCurrent * powerMultiplierStackProduct;
      // Is there a "^ number"?
      skipWhitespace();
      if (parseCharacter('^')) {
        skipWhitespace();
        var p = parseNumber();
        if (p === null) {
          // No valid number found for the power!
          throw new SyntaxError('In "' + str + '", "^" must be followed by a floating-point number');
        }
        power *= p;
      }

      // Add the unit to the list
      unit.units.push({
        unit: res.unit,
        prefix: res.prefix,
        power
      });
      for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
        unit.dimensions[i] += (res.unit.dimensions[i] || 0) * power;
      }

      // Check for and consume closing parentheses, popping from the stack.
      // A ')' will always follow a unit.
      skipWhitespace();
      while (c === ')') {
        if (powerMultiplierStack.length === 0) {
          throw new SyntaxError('Unmatched ")" in "' + text + '" at index ' + index.toString());
        }
        powerMultiplierStackProduct /= powerMultiplierStack.pop();
        next();
        skipWhitespace();
      }

      // "*" and "/" should mean we are expecting something to come next.
      // Is there a forward slash? If so, negate powerMultiplierCurrent. The next unit or paren group is in the denominator.
      expectingUnit = false;
      if (parseCharacter('*')) {
        // explicit multiplication
        powerMultiplierCurrent = 1;
        expectingUnit = true;
      } else if (parseCharacter('/')) {
        // division
        powerMultiplierCurrent = -1;
        expectingUnit = true;
      } else {
        // implicit multiplication
        powerMultiplierCurrent = 1;
      }

      // Replace the unit into the auto unit system
      if (res.unit.base) {
        var baseDim = res.unit.base.key;
        UNIT_SYSTEMS.auto[baseDim] = {
          unit: res.unit,
          prefix: res.prefix
        };
      }
    }

    // Has the string been entirely consumed?
    skipWhitespace();
    if (c) {
      throw new SyntaxError('Could not parse: "' + str + '"');
    }

    // Is there a trailing slash?
    if (expectingUnit) {
      throw new SyntaxError('Trailing characters: "' + str + '"');
    }

    // Is the parentheses stack empty?
    if (powerMultiplierStack.length !== 0) {
      throw new SyntaxError('Unmatched "(" in "' + text + '"');
    }

    // Are there any units at all?
    if (unit.units.length === 0 && !options.allowNoUnits) {
      throw new SyntaxError('"' + str + '" contains no units');
    }
    unit.value = value !== undefined ? unit._normalize(value) : null;
    return unit;
  };

  /**
   * create a copy of this unit
   * @memberof Unit
   * @return {Unit} Returns a cloned version of the unit
   */
  Unit.prototype.clone = function () {
    var unit = new Unit();
    unit.fixPrefix = this.fixPrefix;
    unit.skipAutomaticSimplification = this.skipAutomaticSimplification;
    unit.value = clone$2(this.value);
    unit.dimensions = this.dimensions.slice(0);
    unit.units = [];
    for (var i = 0; i < this.units.length; i++) {
      unit.units[i] = {};
      for (var p in this.units[i]) {
        if (hasOwnProperty(this.units[i], p)) {
          unit.units[i][p] = this.units[i][p];
        }
      }
    }
    return unit;
  };

  /**
   * Return the type of the value of this unit
   *
   * @memberof Unit
   * @ return {string} type of the value of the unit
   */
  Unit.prototype.valueType = function () {
    return typeOf(this.value);
  };

  /**
   * Return whether the unit is derived (such as m/s, or cm^2, but not N)
   * @memberof Unit
   * @return {boolean} True if the unit is derived
   */
  Unit.prototype._isDerived = function () {
    if (this.units.length === 0) {
      return false;
    }
    return this.units.length > 1 || Math.abs(this.units[0].power - 1.0) > 1e-15;
  };

  /**
   * Normalize a value, based on its currently set unit(s)
   * @memberof Unit
   * @param {number | BigNumber | Fraction | boolean} value
   * @return {number | BigNumber | Fraction | boolean} normalized value
   * @private
   */
  Unit.prototype._normalize = function (value) {
    if (value === null || value === undefined || this.units.length === 0) {
      return value;
    }
    var res = value;
    var convert = Unit._getNumberConverter(typeOf(value)); // convert to Fraction or BigNumber if needed

    for (var i = 0; i < this.units.length; i++) {
      var unitValue = convert(this.units[i].unit.value);
      var unitPrefixValue = convert(this.units[i].prefix.value);
      var unitPower = convert(this.units[i].power);
      res = multiplyScalar(res, pow(multiplyScalar(unitValue, unitPrefixValue), unitPower));
    }
    return res;
  };

  /**
   * Denormalize a value, based on its currently set unit(s)
   * @memberof Unit
   * @param {number} value
   * @param {number} [prefixValue]    Optional prefix value to be used (ignored if this is a derived unit)
   * @return {number} denormalized value
   * @private
   */
  Unit.prototype._denormalize = function (value, prefixValue) {
    if (value === null || value === undefined || this.units.length === 0) {
      return value;
    }
    var res = value;
    var convert = Unit._getNumberConverter(typeOf(value)); // convert to Fraction or BigNumber if needed

    for (var i = 0; i < this.units.length; i++) {
      var unitValue = convert(this.units[i].unit.value);
      var unitPrefixValue = convert(this.units[i].prefix.value);
      var unitPower = convert(this.units[i].power);
      res = divideScalar(res, pow(multiplyScalar(unitValue, unitPrefixValue), unitPower));
    }
    return res;
  };

  /**
   * Find a unit from a string
   * @memberof Unit
   * @param {string} str              A string like 'cm' or 'inch'
   * @returns {Object | null} result  When found, an object with fields unit and
   *                                  prefix is returned. Else, null is returned.
   * @private
   */
  var _findUnit = memoize(str => {
    // First, match units names exactly. For example, a user could define 'mm' as 10^-4 m, which is silly, but then we would want 'mm' to match the user-defined unit.
    if (hasOwnProperty(UNITS, str)) {
      var unit = UNITS[str];
      var prefix = unit.prefixes[''];
      return {
        unit,
        prefix
      };
    }
    for (var _name in UNITS) {
      if (hasOwnProperty(UNITS, _name)) {
        if (endsWith(str, _name)) {
          var _unit = UNITS[_name];
          var prefixLen = str.length - _name.length;
          var prefixName = str.substring(0, prefixLen);
          var _prefix = hasOwnProperty(_unit.prefixes, prefixName) ? _unit.prefixes[prefixName] : undefined;
          if (_prefix !== undefined) {
            // store unit, prefix, and value
            return {
              unit: _unit,
              prefix: _prefix
            };
          }
        }
      }
    }
    return null;
  }, {
    hasher: args => args[0],
    limit: 100
  });

  /**
   * Test if the given expression is a unit.
   * The unit can have a prefix but cannot have a value.
   * @memberof Unit
   * @param {string} name   A string to be tested whether it is a value less unit.
   *                        The unit can have prefix, like "cm"
   * @return {boolean}      true if the given string is a unit
   */
  Unit.isValuelessUnit = function (name) {
    return _findUnit(name) !== null;
  };

  /**
   * check if this unit has given base unit
   * If this unit is a derived unit, this will ALWAYS return false, since by definition base units are not derived.
   * @memberof Unit
   * @param {BASE_UNITS | string | undefined} base
   */
  Unit.prototype.hasBase = function (base) {
    if (typeof base === 'string') {
      base = BASE_UNITS[base];
    }
    if (!base) {
      return false;
    }

    // All dimensions must be the same
    for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
      if (Math.abs((this.dimensions[i] || 0) - (base.dimensions[i] || 0)) > 1e-12) {
        return false;
      }
    }
    return true;
  };

  /**
   * Check if this unit has a base or bases equal to another base or bases
   * For derived units, the exponent on each base also must match
   * @memberof Unit
   * @param {Unit} other
   * @return {boolean} true if equal base
   */
  Unit.prototype.equalBase = function (other) {
    // All dimensions must be the same
    for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
      if (Math.abs((this.dimensions[i] || 0) - (other.dimensions[i] || 0)) > 1e-12) {
        return false;
      }
    }
    return true;
  };

  /**
   * Check if this unit equals another unit
   * @memberof Unit
   * @param {Unit} other
   * @return {boolean} true if both units are equal
   */
  Unit.prototype.equals = function (other) {
    return this.equalBase(other) && equal(this.value, other.value);
  };

  /**
   * Multiply this unit with another one or with a scalar
   * @memberof Unit
   * @param {Unit} other
   * @return {Unit} product of this unit and the other unit
   */
  Unit.prototype.multiply = function (_other) {
    var res = this.clone();
    var other = isUnit(_other) ? _other : new Unit(_other);
    for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
      // Dimensions arrays may be of different lengths. Default to 0.
      res.dimensions[i] = (this.dimensions[i] || 0) + (other.dimensions[i] || 0);
    }

    // Append other's units list onto res
    for (var _i = 0; _i < other.units.length; _i++) {
      // Make a shallow copy of every unit
      var inverted = _objectSpread$1({}, other.units[_i]);
      res.units.push(inverted);
    }

    // If at least one operand has a value, then the result should also have a value
    if (this.value !== null || other.value !== null) {
      var valThis = this.value === null ? this._normalize(1) : this.value;
      var valOther = other.value === null ? other._normalize(1) : other.value;
      res.value = multiplyScalar(valThis, valOther);
    } else {
      res.value = null;
    }
    if (isUnit(_other)) {
      res.skipAutomaticSimplification = false;
    }
    return getNumericIfUnitless(res);
  };

  /**
   * Divide a number by this unit
   *
   * @memberof Unit
   * @param {numeric} numerator
   * @param {unit} result of dividing numerator by this unit
   */
  Unit.prototype.divideInto = function (numerator) {
    return new Unit(numerator).divide(this);
  };

  /**
   * Divide this unit by another one
   * @memberof Unit
   * @param {Unit | numeric} other
   * @return {Unit} result of dividing this unit by the other unit
   */
  Unit.prototype.divide = function (_other) {
    var res = this.clone();
    var other = isUnit(_other) ? _other : new Unit(_other);
    for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
      // Dimensions arrays may be of different lengths. Default to 0.
      res.dimensions[i] = (this.dimensions[i] || 0) - (other.dimensions[i] || 0);
    }

    // Invert and append other's units list onto res
    for (var _i2 = 0; _i2 < other.units.length; _i2++) {
      // Make a shallow copy of every unit
      var inverted = _objectSpread$1(_objectSpread$1({}, other.units[_i2]), {}, {
        power: -other.units[_i2].power
      });
      res.units.push(inverted);
    }

    // If at least one operand has a value, the result should have a value
    if (this.value !== null || other.value !== null) {
      var valThis = this.value === null ? this._normalize(1) : this.value;
      var valOther = other.value === null ? other._normalize(1) : other.value;
      res.value = divideScalar(valThis, valOther);
    } else {
      res.value = null;
    }
    if (isUnit(_other)) {
      res.skipAutomaticSimplification = false;
    }
    return getNumericIfUnitless(res);
  };

  /**
   * Calculate the power of a unit
   * @memberof Unit
   * @param {number | Fraction | BigNumber} p
   * @returns {Unit}      The result: this^p
   */
  Unit.prototype.pow = function (p) {
    var res = this.clone();
    for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
      // Dimensions arrays may be of different lengths. Default to 0.
      res.dimensions[i] = (this.dimensions[i] || 0) * p;
    }

    // Adjust the power of each unit in the list
    for (var _i3 = 0; _i3 < res.units.length; _i3++) {
      res.units[_i3].power *= p;
    }
    if (res.value !== null) {
      res.value = pow(res.value, p);

      // only allow numeric output, we don't want to return a Complex number
      // if (!isNumeric(res.value)) {
      //  res.value = NaN
      // }
      // Update: Complex supported now
    } else {
      res.value = null;
    }
    res.skipAutomaticSimplification = false;
    return getNumericIfUnitless(res);
  };

  /**
   * Return the numeric value of this unit if it is dimensionless, has a value, and config.predictable == false; or the original unit otherwise
   * @param {Unit} unit
   * @returns {number | Fraction | BigNumber | Unit}  The numeric value of the unit if conditions are met, or the original unit otherwise
   */
  function getNumericIfUnitless(unit) {
    if (unit.equalBase(BASE_UNITS.NONE) && unit.value !== null && !config.predictable) {
      return unit.value;
    } else {
      return unit;
    }
  }

  /**
   * Calculate the absolute value of a unit
   * @memberof Unit
   * @param {number | Fraction | BigNumber} x
   * @returns {Unit}      The result: |x|, absolute value of x
   */
  Unit.prototype.abs = function () {
    var ret = this.clone();
    if (ret.value !== null) {
      if (ret._isDerived() || ret.units.length === 0 || ret.units[0].unit.offset === 0) {
        ret.value = abs(ret.value);
      } else {
        // To give the correct, but unexpected, results for units with an offset.
        // For example, abs(-283.15 degC) = -263.15 degC !!!
        // We must take the offset into consideration here
        var convert = ret._numberConverter(); // convert to Fraction or BigNumber if needed
        var unitValue = convert(ret.units[0].unit.value);
        var nominalOffset = convert(ret.units[0].unit.offset);
        var unitOffset = multiplyScalar(unitValue, nominalOffset);
        ret.value = subtractScalar(abs(addScalar(ret.value, unitOffset)), unitOffset);
      }
    }
    for (var i in ret.units) {
      if (ret.units[i].unit.name === 'VA' || ret.units[i].unit.name === 'VAR') {
        ret.units[i].unit = UNITS.W;
      }
    }
    return ret;
  };

  /**
   * Convert the unit to a specific unit name.
   * @memberof Unit
   * @param {string | Unit} valuelessUnit   A unit without value. Can have prefix, like "cm"
   * @returns {Unit} Returns a clone of the unit with a fixed prefix and unit.
   */
  Unit.prototype.to = function (valuelessUnit) {
    var value = this.value === null ? this._normalize(1) : this.value;
    var other;
    if (typeof valuelessUnit === 'string') {
      other = Unit.parse(valuelessUnit);
    } else if (isUnit(valuelessUnit)) {
      other = valuelessUnit.clone();
    } else {
      throw new Error('String or Unit expected as parameter');
    }
    if (!this.equalBase(other)) {
      throw new Error("Units do not match ('".concat(other.toString(), "' != '").concat(this.toString(), "')"));
    }
    if (other.value !== null) {
      throw new Error('Cannot convert to a unit with a value');
    }
    if (this.value === null || this._isDerived() || this.units.length === 0 || other.units.length === 0 || this.units[0].unit.offset === other.units[0].unit.offset) {
      other.value = clone$2(value);
    } else {
      /* Need to adjust value by difference in offset to convert */
      var convert = Unit._getNumberConverter(typeOf(value)); // convert to Fraction or BigNumber if needed

      var thisUnitValue = this.units[0].unit.value;
      var thisNominalOffset = this.units[0].unit.offset;
      var thisUnitOffset = multiplyScalar(thisUnitValue, thisNominalOffset);
      var otherUnitValue = other.units[0].unit.value;
      var otherNominalOffset = other.units[0].unit.offset;
      var otherUnitOffset = multiplyScalar(otherUnitValue, otherNominalOffset);
      other.value = addScalar(value, convert(subtractScalar(thisUnitOffset, otherUnitOffset)));
    }
    other.fixPrefix = true;
    other.skipAutomaticSimplification = true;
    return other;
  };

  /**
   * Return the value of the unit when represented with given valueless unit
   * @memberof Unit
   * @param {string | Unit} valuelessUnit    For example 'cm' or 'inch'
   * @return {number} Returns the unit value as number.
   */
  // TODO: deprecate Unit.toNumber? It's always better to use toNumeric
  Unit.prototype.toNumber = function (valuelessUnit) {
    return toNumber(this.toNumeric(valuelessUnit));
  };

  /**
   * Return the value of the unit in the original numeric type
   * @memberof Unit
   * @param {string | Unit} valuelessUnit    For example 'cm' or 'inch'
   * @return {number | BigNumber | Fraction} Returns the unit value
   */
  Unit.prototype.toNumeric = function (valuelessUnit) {
    var other;
    if (valuelessUnit) {
      // Allow getting the numeric value without converting to a different unit
      other = this.to(valuelessUnit);
    } else {
      other = this.clone();
    }
    if (other._isDerived() || other.units.length === 0) {
      return other._denormalize(other.value);
    } else {
      return other._denormalize(other.value, other.units[0].prefix.value);
    }
  };

  /**
   * Get a string representation of the unit.
   * @memberof Unit
   * @return {string}
   */
  Unit.prototype.toString = function () {
    return this.format();
  };

  /**
   * Get a JSON representation of the unit
   * @memberof Unit
   * @returns {Object} Returns a JSON object structured as:
   *                   `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}`
   */
  Unit.prototype.toJSON = function () {
    return {
      mathjs: 'Unit',
      value: this._denormalize(this.value),
      unit: this.units.length > 0 ? this.formatUnits() : null,
      fixPrefix: this.fixPrefix
    };
  };

  /**
   * Instantiate a Unit from a JSON object
   * @memberof Unit
   * @param {Object} json  A JSON object structured as:
   *                       `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}`
   * @return {Unit}
   */
  Unit.fromJSON = function (json) {
    var _json$unit;
    var unit = new Unit(json.value, (_json$unit = json.unit) !== null && _json$unit !== void 0 ? _json$unit : undefined);
    unit.fixPrefix = json.fixPrefix || false;
    return unit;
  };

  /**
   * Returns the string representation of the unit.
   * @memberof Unit
   * @return {string}
   */
  Unit.prototype.valueOf = Unit.prototype.toString;

  /**
   * Simplify this Unit's unit list and return a new Unit with the simplified list.
   * The returned Unit will contain a list of the "best" units for formatting.
   */
  Unit.prototype.simplify = function () {
    var ret = this.clone();
    var proposedUnitList = [];

    // Search for a matching base
    var matchingBase;
    for (var key in currentUnitSystem) {
      if (hasOwnProperty(currentUnitSystem, key)) {
        if (ret.hasBase(BASE_UNITS[key])) {
          matchingBase = key;
          break;
        }
      }
    }
    if (matchingBase === 'NONE') {
      ret.units = [];
    } else {
      var matchingUnit;
      if (matchingBase) {
        // Does the unit system have a matching unit?
        if (hasOwnProperty(currentUnitSystem, matchingBase)) {
          matchingUnit = currentUnitSystem[matchingBase];
        }
      }
      if (matchingUnit) {
        ret.units = [{
          unit: matchingUnit.unit,
          prefix: matchingUnit.prefix,
          power: 1.0
        }];
      } else {
        // Multiple units or units with powers are formatted like this:
        // 5 (kg m^2) / (s^3 mol)
        // Build an representation from the base units of the current unit system
        var missingBaseDim = false;
        for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
          var baseDim = BASE_DIMENSIONS[i];
          if (Math.abs(ret.dimensions[i] || 0) > 1e-12) {
            if (hasOwnProperty(currentUnitSystem, baseDim)) {
              proposedUnitList.push({
                unit: currentUnitSystem[baseDim].unit,
                prefix: currentUnitSystem[baseDim].prefix,
                power: ret.dimensions[i] || 0
              });
            } else {
              missingBaseDim = true;
            }
          }
        }

        // Is the proposed unit list "simpler" than the existing one?
        if (proposedUnitList.length < ret.units.length && !missingBaseDim) {
          // Replace this unit list with the proposed list
          ret.units = proposedUnitList;
        }
      }
    }
    return ret;
  };

  /**
   * Returns a new Unit in the SI system with the same value as this one
   */
  Unit.prototype.toSI = function () {
    var ret = this.clone();
    var proposedUnitList = [];

    // Multiple units or units with powers are formatted like this:
    // 5 (kg m^2) / (s^3 mol)
    // Build an representation from the base units of the SI unit system
    for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
      var baseDim = BASE_DIMENSIONS[i];
      if (Math.abs(ret.dimensions[i] || 0) > 1e-12) {
        if (hasOwnProperty(UNIT_SYSTEMS.si, baseDim)) {
          proposedUnitList.push({
            unit: UNIT_SYSTEMS.si[baseDim].unit,
            prefix: UNIT_SYSTEMS.si[baseDim].prefix,
            power: ret.dimensions[i] || 0
          });
        } else {
          throw new Error('Cannot express custom unit ' + baseDim + ' in SI units');
        }
      }
    }

    // Replace this unit list with the proposed list
    ret.units = proposedUnitList;
    ret.fixPrefix = true;
    ret.skipAutomaticSimplification = true;
    if (this.value !== null) {
      ret.value = null;
      return this.to(ret);
    }
    return ret;
  };

  /**
   * Get a string representation of the units of this Unit, without the value. The unit list is formatted as-is without first being simplified.
   * @memberof Unit
   * @return {string}
   */
  Unit.prototype.formatUnits = function () {
    var strNum = '';
    var strDen = '';
    var nNum = 0;
    var nDen = 0;
    for (var i = 0; i < this.units.length; i++) {
      if (this.units[i].power > 0) {
        nNum++;
        strNum += ' ' + this.units[i].prefix.name + this.units[i].unit.name;
        if (Math.abs(this.units[i].power - 1.0) > 1e-15) {
          strNum += '^' + this.units[i].power;
        }
      } else if (this.units[i].power < 0) {
        nDen++;
      }
    }
    if (nDen > 0) {
      for (var _i4 = 0; _i4 < this.units.length; _i4++) {
        if (this.units[_i4].power < 0) {
          if (nNum > 0) {
            strDen += ' ' + this.units[_i4].prefix.name + this.units[_i4].unit.name;
            if (Math.abs(this.units[_i4].power + 1.0) > 1e-15) {
              strDen += '^' + -this.units[_i4].power;
            }
          } else {
            strDen += ' ' + this.units[_i4].prefix.name + this.units[_i4].unit.name;
            strDen += '^' + this.units[_i4].power;
          }
        }
      }
    }
    // Remove leading " "
    strNum = strNum.substr(1);
    strDen = strDen.substr(1);

    // Add parans for better copy/paste back into evaluate, for example, or for better pretty print formatting
    if (nNum > 1 && nDen > 0) {
      strNum = '(' + strNum + ')';
    }
    if (nDen > 1 && nNum > 0) {
      strDen = '(' + strDen + ')';
    }
    var str = strNum;
    if (nNum > 0 && nDen > 0) {
      str += ' / ';
    }
    str += strDen;
    return str;
  };

  /**
   * Get a string representation of the Unit, with optional formatting options.
   * @memberof Unit
   * @param {Object | number | Function} [options]  Formatting options. See
   *                                                lib/utils/number:format for a
   *                                                description of the available
   *                                                options.
   * @return {string}
   */
  Unit.prototype.format = function (options) {
    // Simplfy the unit list, unless it is valueless or was created directly in the
    // constructor or as the result of to or toSI
    var simp = this.skipAutomaticSimplification || this.value === null ? this.clone() : this.simplify();

    // Apply some custom logic for handling VA and VAR. The goal is to express the value of the unit as a real value, if possible. Otherwise, use a real-valued unit instead of a complex-valued one.
    var isImaginary = false;
    if (typeof simp.value !== 'undefined' && simp.value !== null && isComplex(simp.value)) {
      // TODO: Make this better, for example, use relative magnitude of re and im rather than absolute
      isImaginary = Math.abs(simp.value.re) < 1e-14;
    }
    for (var i in simp.units) {
      if (hasOwnProperty(simp.units, i)) {
        if (simp.units[i].unit) {
          if (simp.units[i].unit.name === 'VA' && isImaginary) {
            simp.units[i].unit = UNITS.VAR;
          } else if (simp.units[i].unit.name === 'VAR' && !isImaginary) {
            simp.units[i].unit = UNITS.VA;
          }
        }
      }
    }

    // Now apply the best prefix
    // Units must have only one unit and not have the fixPrefix flag set
    if (simp.units.length === 1 && !simp.fixPrefix) {
      // Units must have integer powers, otherwise the prefix will change the
      // outputted value by not-an-integer-power-of-ten
      if (Math.abs(simp.units[0].power - Math.round(simp.units[0].power)) < 1e-14) {
        // Apply the best prefix
        simp.units[0].prefix = simp._bestPrefix();
      }
    }
    var value = simp._denormalize(simp.value);
    var str = simp.value !== null ? format(value, options || {}) : '';
    var unitStr = simp.formatUnits();
    if (simp.value && isComplex(simp.value)) {
      str = '(' + str + ')'; // Surround complex values with ( ) to enable better parsing
    }
    if (unitStr.length > 0 && str.length > 0) {
      str += ' ';
    }
    str += unitStr;
    return str;
  };

  /**
   * Calculate the best prefix using current value.
   * @memberof Unit
   * @returns {Object} prefix
   * @private
   */
  Unit.prototype._bestPrefix = function () {
    if (this.units.length !== 1) {
      throw new Error('Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!');
    }
    if (Math.abs(this.units[0].power - Math.round(this.units[0].power)) >= 1e-14) {
      throw new Error('Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!');
    }

    // find the best prefix value (resulting in the value of which
    // the absolute value of the log10 is closest to zero,
    // though with a little offset of 1.2 for nicer values: you get a
    // sequence 1mm 100mm 500mm 0.6m 1m 10m 100m 500m 0.6km 1km ...

    // Note: the units value can be any numeric type, but to find the best
    // prefix it's enough to work with limited precision of a regular number
    // Update: using mathjs abs since we also allow complex numbers
    var absValue = this.value !== null ? abs(this.value) : 0;
    var absUnitValue = abs(this.units[0].unit.value);
    var bestPrefix = this.units[0].prefix;
    if (absValue === 0) {
      return bestPrefix;
    }
    var power = this.units[0].power;
    var bestDiff = Math.log(absValue / Math.pow(bestPrefix.value * absUnitValue, power)) / Math.LN10 - 1.2;
    if (bestDiff > -2.200001 && bestDiff < 1.800001) return bestPrefix; // Allow the original prefix
    bestDiff = Math.abs(bestDiff);
    var prefixes = this.units[0].unit.prefixes;
    for (var p in prefixes) {
      if (hasOwnProperty(prefixes, p)) {
        var prefix = prefixes[p];
        if (prefix.scientific) {
          var diff = Math.abs(Math.log(absValue / Math.pow(prefix.value * absUnitValue, power)) / Math.LN10 - 1.2);
          if (diff < bestDiff || diff === bestDiff && prefix.name.length < bestPrefix.name.length) {
            // choose the prefix with the smallest diff, or if equal, choose the one
            // with the shortest name (can happen with SHORTLONG for example)
            bestPrefix = prefix;
            bestDiff = diff;
          }
        }
      }
    }
    return bestPrefix;
  };

  /**
   * Returns an array of units whose sum is equal to this unit
   * @memberof Unit
   * @param {Array} [parts] An array of strings or valueless units.
   *
   *   Example:
   *
   *   const u = new Unit(1, 'm')
   *   u.splitUnit(['feet', 'inch'])
   *     [ 3 feet, 3.3700787401575 inch ]
   *
   * @return {Array} An array of units.
   */
  Unit.prototype.splitUnit = function (parts) {
    var x = this.clone();
    var ret = [];
    for (var i = 0; i < parts.length; i++) {
      // Convert x to the requested unit
      x = x.to(parts[i]);
      if (i === parts.length - 1) break;

      // Get the numeric value of this unit
      var xNumeric = x.toNumeric();

      // Check to see if xNumeric is nearly equal to an integer,
      // since fix can incorrectly round down if there is round-off error
      var xRounded = round(xNumeric);
      var xFixed = void 0;
      var isNearlyEqual = equal(xRounded, xNumeric);
      if (isNearlyEqual) {
        xFixed = xRounded;
      } else {
        xFixed = fix(x.toNumeric());
      }
      var y = new Unit(xFixed, parts[i].toString());
      ret.push(y);
      x = subtractScalar(x, y);
    }

    // This little bit fixes a bug where the remainder should be 0 but is a little bit off.
    // But instead of comparing x, the remainder, with zero--we will compare the sum of
    // all the parts so far with the original value. If they are nearly equal,
    // we set the remainder to 0.
    var testSum = 0;
    for (var _i5 = 0; _i5 < ret.length; _i5++) {
      testSum = addScalar(testSum, ret[_i5].value);
    }
    if (equal(testSum, this.value)) {
      x.value = 0;
    }
    ret.push(x);
    return ret;
  };
  var PREFIXES = {
    NONE: {
      '': {
        name: '',
        value: 1,
        scientific: true
      }
    },
    SHORT: {
      '': {
        name: '',
        value: 1,
        scientific: true
      },
      da: {
        name: 'da',
        value: 1e1,
        scientific: false
      },
      h: {
        name: 'h',
        value: 1e2,
        scientific: false
      },
      k: {
        name: 'k',
        value: 1e3,
        scientific: true
      },
      M: {
        name: 'M',
        value: 1e6,
        scientific: true
      },
      G: {
        name: 'G',
        value: 1e9,
        scientific: true
      },
      T: {
        name: 'T',
        value: 1e12,
        scientific: true
      },
      P: {
        name: 'P',
        value: 1e15,
        scientific: true
      },
      E: {
        name: 'E',
        value: 1e18,
        scientific: true
      },
      Z: {
        name: 'Z',
        value: 1e21,
        scientific: true
      },
      Y: {
        name: 'Y',
        value: 1e24,
        scientific: true
      },
      R: {
        name: 'R',
        value: 1e27,
        scientific: true
      },
      Q: {
        name: 'Q',
        value: 1e30,
        scientific: true
      },
      d: {
        name: 'd',
        value: 1e-1,
        scientific: false
      },
      c: {
        name: 'c',
        value: 1e-2,
        scientific: false
      },
      m: {
        name: 'm',
        value: 1e-3,
        scientific: true
      },
      u: {
        name: 'u',
        value: 1e-6,
        scientific: true
      },
      n: {
        name: 'n',
        value: 1e-9,
        scientific: true
      },
      p: {
        name: 'p',
        value: 1e-12,
        scientific: true
      },
      f: {
        name: 'f',
        value: 1e-15,
        scientific: true
      },
      a: {
        name: 'a',
        value: 1e-18,
        scientific: true
      },
      z: {
        name: 'z',
        value: 1e-21,
        scientific: true
      },
      y: {
        name: 'y',
        value: 1e-24,
        scientific: true
      },
      r: {
        name: 'r',
        value: 1e-27,
        scientific: true
      },
      q: {
        name: 'q',
        value: 1e-30,
        scientific: true
      }
    },
    LONG: {
      '': {
        name: '',
        value: 1,
        scientific: true
      },
      deca: {
        name: 'deca',
        value: 1e1,
        scientific: false
      },
      hecto: {
        name: 'hecto',
        value: 1e2,
        scientific: false
      },
      kilo: {
        name: 'kilo',
        value: 1e3,
        scientific: true
      },
      mega: {
        name: 'mega',
        value: 1e6,
        scientific: true
      },
      giga: {
        name: 'giga',
        value: 1e9,
        scientific: true
      },
      tera: {
        name: 'tera',
        value: 1e12,
        scientific: true
      },
      peta: {
        name: 'peta',
        value: 1e15,
        scientific: true
      },
      exa: {
        name: 'exa',
        value: 1e18,
        scientific: true
      },
      zetta: {
        name: 'zetta',
        value: 1e21,
        scientific: true
      },
      yotta: {
        name: 'yotta',
        value: 1e24,
        scientific: true
      },
      ronna: {
        name: 'ronna',
        value: 1e27,
        scientific: true
      },
      quetta: {
        name: 'quetta',
        value: 1e30,
        scientific: true
      },
      deci: {
        name: 'deci',
        value: 1e-1,
        scientific: false
      },
      centi: {
        name: 'centi',
        value: 1e-2,
        scientific: false
      },
      milli: {
        name: 'milli',
        value: 1e-3,
        scientific: true
      },
      micro: {
        name: 'micro',
        value: 1e-6,
        scientific: true
      },
      nano: {
        name: 'nano',
        value: 1e-9,
        scientific: true
      },
      pico: {
        name: 'pico',
        value: 1e-12,
        scientific: true
      },
      femto: {
        name: 'femto',
        value: 1e-15,
        scientific: true
      },
      atto: {
        name: 'atto',
        value: 1e-18,
        scientific: true
      },
      zepto: {
        name: 'zepto',
        value: 1e-21,
        scientific: true
      },
      yocto: {
        name: 'yocto',
        value: 1e-24,
        scientific: true
      },
      ronto: {
        name: 'ronto',
        value: 1e-27,
        scientific: true
      },
      quecto: {
        name: 'quecto',
        value: 1e-30,
        scientific: true
      }
    },
    SQUARED: {
      '': {
        name: '',
        value: 1,
        scientific: true
      },
      da: {
        name: 'da',
        value: 1e2,
        scientific: false
      },
      h: {
        name: 'h',
        value: 1e4,
        scientific: false
      },
      k: {
        name: 'k',
        value: 1e6,
        scientific: true
      },
      M: {
        name: 'M',
        value: 1e12,
        scientific: true
      },
      G: {
        name: 'G',
        value: 1e18,
        scientific: true
      },
      T: {
        name: 'T',
        value: 1e24,
        scientific: true
      },
      P: {
        name: 'P',
        value: 1e30,
        scientific: true
      },
      E: {
        name: 'E',
        value: 1e36,
        scientific: true
      },
      Z: {
        name: 'Z',
        value: 1e42,
        scientific: true
      },
      Y: {
        name: 'Y',
        value: 1e48,
        scientific: true
      },
      R: {
        name: 'R',
        value: 1e54,
        scientific: true
      },
      Q: {
        name: 'Q',
        value: 1e60,
        scientific: true
      },
      d: {
        name: 'd',
        value: 1e-2,
        scientific: false
      },
      c: {
        name: 'c',
        value: 1e-4,
        scientific: false
      },
      m: {
        name: 'm',
        value: 1e-6,
        scientific: true
      },
      u: {
        name: 'u',
        value: 1e-12,
        scientific: true
      },
      n: {
        name: 'n',
        value: 1e-18,
        scientific: true
      },
      p: {
        name: 'p',
        value: 1e-24,
        scientific: true
      },
      f: {
        name: 'f',
        value: 1e-30,
        scientific: true
      },
      a: {
        name: 'a',
        value: 1e-36,
        scientific: true
      },
      z: {
        name: 'z',
        value: 1e-42,
        scientific: true
      },
      y: {
        name: 'y',
        value: 1e-48,
        scientific: true
      },
      r: {
        name: 'r',
        value: 1e-54,
        scientific: true
      },
      q: {
        name: 'q',
        value: 1e-60,
        scientific: true
      }
    },
    CUBIC: {
      '': {
        name: '',
        value: 1,
        scientific: true
      },
      da: {
        name: 'da',
        value: 1e3,
        scientific: false
      },
      h: {
        name: 'h',
        value: 1e6,
        scientific: false
      },
      k: {
        name: 'k',
        value: 1e9,
        scientific: true
      },
      M: {
        name: 'M',
        value: 1e18,
        scientific: true
      },
      G: {
        name: 'G',
        value: 1e27,
        scientific: true
      },
      T: {
        name: 'T',
        value: 1e36,
        scientific: true
      },
      P: {
        name: 'P',
        value: 1e45,
        scientific: true
      },
      E: {
        name: 'E',
        value: 1e54,
        scientific: true
      },
      Z: {
        name: 'Z',
        value: 1e63,
        scientific: true
      },
      Y: {
        name: 'Y',
        value: 1e72,
        scientific: true
      },
      R: {
        name: 'R',
        value: 1e81,
        scientific: true
      },
      Q: {
        name: 'Q',
        value: 1e90,
        scientific: true
      },
      d: {
        name: 'd',
        value: 1e-3,
        scientific: false
      },
      c: {
        name: 'c',
        value: 1e-6,
        scientific: false
      },
      m: {
        name: 'm',
        value: 1e-9,
        scientific: true
      },
      u: {
        name: 'u',
        value: 1e-18,
        scientific: true
      },
      n: {
        name: 'n',
        value: 1e-27,
        scientific: true
      },
      p: {
        name: 'p',
        value: 1e-36,
        scientific: true
      },
      f: {
        name: 'f',
        value: 1e-45,
        scientific: true
      },
      a: {
        name: 'a',
        value: 1e-54,
        scientific: true
      },
      z: {
        name: 'z',
        value: 1e-63,
        scientific: true
      },
      y: {
        name: 'y',
        value: 1e-72,
        scientific: true
      },
      r: {
        name: 'r',
        value: 1e-81,
        scientific: true
      },
      q: {
        name: 'q',
        value: 1e-90,
        scientific: true
      }
    },
    BINARY_SHORT_SI: {
      '': {
        name: '',
        value: 1,
        scientific: true
      },
      k: {
        name: 'k',
        value: 1e3,
        scientific: true
      },
      M: {
        name: 'M',
        value: 1e6,
        scientific: true
      },
      G: {
        name: 'G',
        value: 1e9,
        scientific: true
      },
      T: {
        name: 'T',
        value: 1e12,
        scientific: true
      },
      P: {
        name: 'P',
        value: 1e15,
        scientific: true
      },
      E: {
        name: 'E',
        value: 1e18,
        scientific: true
      },
      Z: {
        name: 'Z',
        value: 1e21,
        scientific: true
      },
      Y: {
        name: 'Y',
        value: 1e24,
        scientific: true
      }
    },
    BINARY_SHORT_IEC: {
      '': {
        name: '',
        value: 1,
        scientific: true
      },
      Ki: {
        name: 'Ki',
        value: 1024,
        scientific: true
      },
      Mi: {
        name: 'Mi',
        value: Math.pow(1024, 2),
        scientific: true
      },
      Gi: {
        name: 'Gi',
        value: Math.pow(1024, 3),
        scientific: true
      },
      Ti: {
        name: 'Ti',
        value: Math.pow(1024, 4),
        scientific: true
      },
      Pi: {
        name: 'Pi',
        value: Math.pow(1024, 5),
        scientific: true
      },
      Ei: {
        name: 'Ei',
        value: Math.pow(1024, 6),
        scientific: true
      },
      Zi: {
        name: 'Zi',
        value: Math.pow(1024, 7),
        scientific: true
      },
      Yi: {
        name: 'Yi',
        value: Math.pow(1024, 8),
        scientific: true
      }
    },
    BINARY_LONG_SI: {
      '': {
        name: '',
        value: 1,
        scientific: true
      },
      kilo: {
        name: 'kilo',
        value: 1e3,
        scientific: true
      },
      mega: {
        name: 'mega',
        value: 1e6,
        scientific: true
      },
      giga: {
        name: 'giga',
        value: 1e9,
        scientific: true
      },
      tera: {
        name: 'tera',
        value: 1e12,
        scientific: true
      },
      peta: {
        name: 'peta',
        value: 1e15,
        scientific: true
      },
      exa: {
        name: 'exa',
        value: 1e18,
        scientific: true
      },
      zetta: {
        name: 'zetta',
        value: 1e21,
        scientific: true
      },
      yotta: {
        name: 'yotta',
        value: 1e24,
        scientific: true
      }
    },
    BINARY_LONG_IEC: {
      '': {
        name: '',
        value: 1,
        scientific: true
      },
      kibi: {
        name: 'kibi',
        value: 1024,
        scientific: true
      },
      mebi: {
        name: 'mebi',
        value: Math.pow(1024, 2),
        scientific: true
      },
      gibi: {
        name: 'gibi',
        value: Math.pow(1024, 3),
        scientific: true
      },
      tebi: {
        name: 'tebi',
        value: Math.pow(1024, 4),
        scientific: true
      },
      pebi: {
        name: 'pebi',
        value: Math.pow(1024, 5),
        scientific: true
      },
      exi: {
        name: 'exi',
        value: Math.pow(1024, 6),
        scientific: true
      },
      zebi: {
        name: 'zebi',
        value: Math.pow(1024, 7),
        scientific: true
      },
      yobi: {
        name: 'yobi',
        value: Math.pow(1024, 8),
        scientific: true
      }
    },
    BTU: {
      '': {
        name: '',
        value: 1,
        scientific: true
      },
      MM: {
        name: 'MM',
        value: 1e6,
        scientific: true
      }
    }
  };
  PREFIXES.SHORTLONG = _extends$1({}, PREFIXES.SHORT, PREFIXES.LONG);
  PREFIXES.BINARY_SHORT = _extends$1({}, PREFIXES.BINARY_SHORT_SI, PREFIXES.BINARY_SHORT_IEC);
  PREFIXES.BINARY_LONG = _extends$1({}, PREFIXES.BINARY_LONG_SI, PREFIXES.BINARY_LONG_IEC);

  /* Internally, each unit is represented by a value and a dimension array. The elements of the dimensions array have the following meaning:
   * Index  Dimension
   * -----  ---------
   *   0    Length
   *   1    Mass
   *   2    Time
   *   3    Current
   *   4    Temperature
   *   5    Luminous intensity
   *   6    Amount of substance
   *   7    Angle
   *   8    Bit (digital)
   * 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].
   *
   */

  var BASE_DIMENSIONS = ['MASS', 'LENGTH', 'TIME', 'CURRENT', 'TEMPERATURE', 'LUMINOUS_INTENSITY', 'AMOUNT_OF_SUBSTANCE', 'ANGLE', 'BIT'];
  var BASE_UNITS = {
    NONE: {
      dimensions: [0, 0, 0, 0, 0, 0, 0, 0, 0]
    },
    MASS: {
      dimensions: [1, 0, 0, 0, 0, 0, 0, 0, 0]
    },
    LENGTH: {
      dimensions: [0, 1, 0, 0, 0, 0, 0, 0, 0]
    },
    TIME: {
      dimensions: [0, 0, 1, 0, 0, 0, 0, 0, 0]
    },
    CURRENT: {
      dimensions: [0, 0, 0, 1, 0, 0, 0, 0, 0]
    },
    TEMPERATURE: {
      dimensions: [0, 0, 0, 0, 1, 0, 0, 0, 0]
    },
    LUMINOUS_INTENSITY: {
      dimensions: [0, 0, 0, 0, 0, 1, 0, 0, 0]
    },
    AMOUNT_OF_SUBSTANCE: {
      dimensions: [0, 0, 0, 0, 0, 0, 1, 0, 0]
    },
    FORCE: {
      dimensions: [1, 1, -2, 0, 0, 0, 0, 0, 0]
    },
    SURFACE: {
      dimensions: [0, 2, 0, 0, 0, 0, 0, 0, 0]
    },
    VOLUME: {
      dimensions: [0, 3, 0, 0, 0, 0, 0, 0, 0]
    },
    ENERGY: {
      dimensions: [1, 2, -2, 0, 0, 0, 0, 0, 0]
    },
    POWER: {
      dimensions: [1, 2, -3, 0, 0, 0, 0, 0, 0]
    },
    PRESSURE: {
      dimensions: [1, -1, -2, 0, 0, 0, 0, 0, 0]
    },
    ELECTRIC_CHARGE: {
      dimensions: [0, 0, 1, 1, 0, 0, 0, 0, 0]
    },
    ELECTRIC_CAPACITANCE: {
      dimensions: [-1, -2, 4, 2, 0, 0, 0, 0, 0]
    },
    ELECTRIC_POTENTIAL: {
      dimensions: [1, 2, -3, -1, 0, 0, 0, 0, 0]
    },
    ELECTRIC_RESISTANCE: {
      dimensions: [1, 2, -3, -2, 0, 0, 0, 0, 0]
    },
    ELECTRIC_INDUCTANCE: {
      dimensions: [1, 2, -2, -2, 0, 0, 0, 0, 0]
    },
    ELECTRIC_CONDUCTANCE: {
      dimensions: [-1, -2, 3, 2, 0, 0, 0, 0, 0]
    },
    MAGNETIC_FLUX: {
      dimensions: [1, 2, -2, -1, 0, 0, 0, 0, 0]
    },
    MAGNETIC_FLUX_DENSITY: {
      dimensions: [1, 0, -2, -1, 0, 0, 0, 0, 0]
    },
    FREQUENCY: {
      dimensions: [0, 0, -1, 0, 0, 0, 0, 0, 0]
    },
    ANGLE: {
      dimensions: [0, 0, 0, 0, 0, 0, 0, 1, 0]
    },
    BIT: {
      dimensions: [0, 0, 0, 0, 0, 0, 0, 0, 1]
    }
  };
  for (var key in BASE_UNITS) {
    if (hasOwnProperty(BASE_UNITS, key)) {
      BASE_UNITS[key].key = key;
    }
  }
  var BASE_UNIT_NONE = {};
  var UNIT_NONE = {
    name: '',
    base: BASE_UNIT_NONE,
    value: 1,
    offset: 0,
    dimensions: BASE_DIMENSIONS.map(x => 0)
  };
  var UNITS = {
    // length
    meter: {
      name: 'meter',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    inch: {
      name: 'inch',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 0.0254,
      offset: 0
    },
    foot: {
      name: 'foot',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 0.3048,
      offset: 0
    },
    yard: {
      name: 'yard',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 0.9144,
      offset: 0
    },
    mile: {
      name: 'mile',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 1609.344,
      offset: 0
    },
    link: {
      name: 'link',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 0.201168,
      offset: 0
    },
    rod: {
      name: 'rod',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 5.0292,
      offset: 0
    },
    chain: {
      name: 'chain',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 20.1168,
      offset: 0
    },
    angstrom: {
      name: 'angstrom',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 1e-10,
      offset: 0
    },
    m: {
      name: 'm',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    in: {
      name: 'in',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 0.0254,
      offset: 0
    },
    ft: {
      name: 'ft',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 0.3048,
      offset: 0
    },
    yd: {
      name: 'yd',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 0.9144,
      offset: 0
    },
    mi: {
      name: 'mi',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 1609.344,
      offset: 0
    },
    li: {
      name: 'li',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 0.201168,
      offset: 0
    },
    rd: {
      name: 'rd',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 5.029210,
      offset: 0
    },
    ch: {
      name: 'ch',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 20.1168,
      offset: 0
    },
    mil: {
      name: 'mil',
      base: BASE_UNITS.LENGTH,
      prefixes: PREFIXES.NONE,
      value: 0.0000254,
      offset: 0
    },
    // 1/1000 inch

    // Surface
    m2: {
      name: 'm2',
      base: BASE_UNITS.SURFACE,
      prefixes: PREFIXES.SQUARED,
      value: 1,
      offset: 0
    },
    sqin: {
      name: 'sqin',
      base: BASE_UNITS.SURFACE,
      prefixes: PREFIXES.NONE,
      value: 0.00064516,
      offset: 0
    },
    // 645.16 mm2
    sqft: {
      name: 'sqft',
      base: BASE_UNITS.SURFACE,
      prefixes: PREFIXES.NONE,
      value: 0.09290304,
      offset: 0
    },
    // 0.09290304 m2
    sqyd: {
      name: 'sqyd',
      base: BASE_UNITS.SURFACE,
      prefixes: PREFIXES.NONE,
      value: 0.83612736,
      offset: 0
    },
    // 0.83612736 m2
    sqmi: {
      name: 'sqmi',
      base: BASE_UNITS.SURFACE,
      prefixes: PREFIXES.NONE,
      value: 2589988.110336,
      offset: 0
    },
    // 2.589988110336 km2
    sqrd: {
      name: 'sqrd',
      base: BASE_UNITS.SURFACE,
      prefixes: PREFIXES.NONE,
      value: 25.29295,
      offset: 0
    },
    // 25.29295 m2
    sqch: {
      name: 'sqch',
      base: BASE_UNITS.SURFACE,
      prefixes: PREFIXES.NONE,
      value: 404.6873,
      offset: 0
    },
    // 404.6873 m2
    sqmil: {
      name: 'sqmil',
      base: BASE_UNITS.SURFACE,
      prefixes: PREFIXES.NONE,
      value: 6.4516e-10,
      offset: 0
    },
    // 6.4516 * 10^-10 m2
    acre: {
      name: 'acre',
      base: BASE_UNITS.SURFACE,
      prefixes: PREFIXES.NONE,
      value: 4046.86,
      offset: 0
    },
    // 4046.86 m2
    hectare: {
      name: 'hectare',
      base: BASE_UNITS.SURFACE,
      prefixes: PREFIXES.NONE,
      value: 10000,
      offset: 0
    },
    // 10000 m2

    // Volume
    m3: {
      name: 'm3',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.CUBIC,
      value: 1,
      offset: 0
    },
    L: {
      name: 'L',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.SHORT,
      value: 0.001,
      offset: 0
    },
    // litre
    l: {
      name: 'l',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.SHORT,
      value: 0.001,
      offset: 0
    },
    // litre
    litre: {
      name: 'litre',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.LONG,
      value: 0.001,
      offset: 0
    },
    cuin: {
      name: 'cuin',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 1.6387064e-5,
      offset: 0
    },
    // 1.6387064e-5 m3
    cuft: {
      name: 'cuft',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.028316846592,
      offset: 0
    },
    // 28.316 846 592 L
    cuyd: {
      name: 'cuyd',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.764554857984,
      offset: 0
    },
    // 764.554 857 984 L
    teaspoon: {
      name: 'teaspoon',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.000005,
      offset: 0
    },
    // 5 mL
    tablespoon: {
      name: 'tablespoon',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.000015,
      offset: 0
    },
    // 15 mL
    // {name: 'cup', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.000240, offset: 0}, // 240 mL  // not possible, we have already another cup
    drop: {
      name: 'drop',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 5e-8,
      offset: 0
    },
    // 0.05 mL = 5e-8 m3
    gtt: {
      name: 'gtt',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 5e-8,
      offset: 0
    },
    // 0.05 mL = 5e-8 m3

    // Liquid volume
    minim: {
      name: 'minim',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.00000006161152,
      offset: 0
    },
    // 0.06161152 mL
    fluiddram: {
      name: 'fluiddram',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.0000036966911,
      offset: 0
    },
    // 3.696691 mL
    fluidounce: {
      name: 'fluidounce',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.00002957353,
      offset: 0
    },
    // 29.57353 mL
    gill: {
      name: 'gill',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.0001182941,
      offset: 0
    },
    // 118.2941 mL
    cc: {
      name: 'cc',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 1e-6,
      offset: 0
    },
    // 1e-6 L
    cup: {
      name: 'cup',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.0002365882,
      offset: 0
    },
    // 236.5882 mL
    pint: {
      name: 'pint',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.0004731765,
      offset: 0
    },
    // 473.1765 mL
    quart: {
      name: 'quart',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.0009463529,
      offset: 0
    },
    // 946.3529 mL
    gallon: {
      name: 'gallon',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.003785412,
      offset: 0
    },
    // 3.785412 L
    beerbarrel: {
      name: 'beerbarrel',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.1173478,
      offset: 0
    },
    // 117.3478 L
    oilbarrel: {
      name: 'oilbarrel',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.1589873,
      offset: 0
    },
    // 158.9873 L
    hogshead: {
      name: 'hogshead',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.2384810,
      offset: 0
    },
    // 238.4810 L

    // {name: 'min', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.00000006161152, offset: 0}, // 0.06161152 mL // min is already in use as minute
    fldr: {
      name: 'fldr',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.0000036966911,
      offset: 0
    },
    // 3.696691 mL
    floz: {
      name: 'floz',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.00002957353,
      offset: 0
    },
    // 29.57353 mL
    gi: {
      name: 'gi',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.0001182941,
      offset: 0
    },
    // 118.2941 mL
    cp: {
      name: 'cp',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.0002365882,
      offset: 0
    },
    // 236.5882 mL
    pt: {
      name: 'pt',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.0004731765,
      offset: 0
    },
    // 473.1765 mL
    qt: {
      name: 'qt',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.0009463529,
      offset: 0
    },
    // 946.3529 mL
    gal: {
      name: 'gal',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.003785412,
      offset: 0
    },
    // 3.785412 L
    bbl: {
      name: 'bbl',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.1173478,
      offset: 0
    },
    // 117.3478 L
    obl: {
      name: 'obl',
      base: BASE_UNITS.VOLUME,
      prefixes: PREFIXES.NONE,
      value: 0.1589873,
      offset: 0
    },
    // 158.9873 L
    // {name: 'hogshead', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.2384810, offset: 0}, // 238.4810 L // TODO: hh?

    // Mass
    g: {
      name: 'g',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.SHORT,
      value: 0.001,
      offset: 0
    },
    gram: {
      name: 'gram',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.LONG,
      value: 0.001,
      offset: 0
    },
    ton: {
      name: 'ton',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.SHORT,
      value: 907.18474,
      offset: 0
    },
    t: {
      name: 't',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.SHORT,
      value: 1000,
      offset: 0
    },
    tonne: {
      name: 'tonne',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.LONG,
      value: 1000,
      offset: 0
    },
    grain: {
      name: 'grain',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.NONE,
      value: 64.79891e-6,
      offset: 0
    },
    dram: {
      name: 'dram',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.NONE,
      value: 1.7718451953125e-3,
      offset: 0
    },
    ounce: {
      name: 'ounce',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.NONE,
      value: 28.349523125e-3,
      offset: 0
    },
    poundmass: {
      name: 'poundmass',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.NONE,
      value: 453.59237e-3,
      offset: 0
    },
    hundredweight: {
      name: 'hundredweight',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.NONE,
      value: 45.359237,
      offset: 0
    },
    stick: {
      name: 'stick',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.NONE,
      value: 115e-3,
      offset: 0
    },
    stone: {
      name: 'stone',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.NONE,
      value: 6.35029318,
      offset: 0
    },
    gr: {
      name: 'gr',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.NONE,
      value: 64.79891e-6,
      offset: 0
    },
    dr: {
      name: 'dr',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.NONE,
      value: 1.7718451953125e-3,
      offset: 0
    },
    oz: {
      name: 'oz',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.NONE,
      value: 28.349523125e-3,
      offset: 0
    },
    lbm: {
      name: 'lbm',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.NONE,
      value: 453.59237e-3,
      offset: 0
    },
    cwt: {
      name: 'cwt',
      base: BASE_UNITS.MASS,
      prefixes: PREFIXES.NONE,
      value: 45.359237,
      offset: 0
    },
    // Time
    s: {
      name: 's',
      base: BASE_UNITS.TIME,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    min: {
      name: 'min',
      base: BASE_UNITS.TIME,
      prefixes: PREFIXES.NONE,
      value: 60,
      offset: 0
    },
    h: {
      name: 'h',
      base: BASE_UNITS.TIME,
      prefixes: PREFIXES.NONE,
      value: 3600,
      offset: 0
    },
    second: {
      name: 'second',
      base: BASE_UNITS.TIME,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    sec: {
      name: 'sec',
      base: BASE_UNITS.TIME,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    minute: {
      name: 'minute',
      base: BASE_UNITS.TIME,
      prefixes: PREFIXES.NONE,
      value: 60,
      offset: 0
    },
    hour: {
      name: 'hour',
      base: BASE_UNITS.TIME,
      prefixes: PREFIXES.NONE,
      value: 3600,
      offset: 0
    },
    day: {
      name: 'day',
      base: BASE_UNITS.TIME,
      prefixes: PREFIXES.NONE,
      value: 86400,
      offset: 0
    },
    week: {
      name: 'week',
      base: BASE_UNITS.TIME,
      prefixes: PREFIXES.NONE,
      value: 7 * 86400,
      offset: 0
    },
    month: {
      name: 'month',
      base: BASE_UNITS.TIME,
      prefixes: PREFIXES.NONE,
      value: 2629800,
      // 1/12th of Julian year
      offset: 0
    },
    year: {
      name: 'year',
      base: BASE_UNITS.TIME,
      prefixes: PREFIXES.NONE,
      value: 31557600,
      // Julian year
      offset: 0
    },
    decade: {
      name: 'decade',
      base: BASE_UNITS.TIME,
      prefixes: PREFIXES.NONE,
      value: 315576000,
      // Julian decade
      offset: 0
    },
    century: {
      name: 'century',
      base: BASE_UNITS.TIME,
      prefixes: PREFIXES.NONE,
      value: 3155760000,
      // Julian century
      offset: 0
    },
    millennium: {
      name: 'millennium',
      base: BASE_UNITS.TIME,
      prefixes: PREFIXES.NONE,
      value: 31557600000,
      // Julian millennium
      offset: 0
    },
    // Frequency
    hertz: {
      name: 'Hertz',
      base: BASE_UNITS.FREQUENCY,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0,
      reciprocal: true
    },
    Hz: {
      name: 'Hz',
      base: BASE_UNITS.FREQUENCY,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0,
      reciprocal: true
    },
    // Angle
    rad: {
      name: 'rad',
      base: BASE_UNITS.ANGLE,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    radian: {
      name: 'radian',
      base: BASE_UNITS.ANGLE,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    // deg = rad / (2*pi) * 360 = rad / 0.017453292519943295769236907684888
    deg: {
      name: 'deg',
      base: BASE_UNITS.ANGLE,
      prefixes: PREFIXES.SHORT,
      value: null,
      // will be filled in by calculateAngleValues()
      offset: 0
    },
    degree: {
      name: 'degree',
      base: BASE_UNITS.ANGLE,
      prefixes: PREFIXES.LONG,
      value: null,
      // will be filled in by calculateAngleValues()
      offset: 0
    },
    // grad = rad / (2*pi) * 400  = rad / 0.015707963267948966192313216916399
    grad: {
      name: 'grad',
      base: BASE_UNITS.ANGLE,
      prefixes: PREFIXES.SHORT,
      value: null,
      // will be filled in by calculateAngleValues()
      offset: 0
    },
    gradian: {
      name: 'gradian',
      base: BASE_UNITS.ANGLE,
      prefixes: PREFIXES.LONG,
      value: null,
      // will be filled in by calculateAngleValues()
      offset: 0
    },
    // cycle = rad / (2*pi) = rad / 6.2831853071795864769252867665793
    cycle: {
      name: 'cycle',
      base: BASE_UNITS.ANGLE,
      prefixes: PREFIXES.NONE,
      value: null,
      // will be filled in by calculateAngleValues()
      offset: 0
    },
    // arcsec = rad / (3600 * (360 / 2 * pi)) = rad / 0.0000048481368110953599358991410235795
    arcsec: {
      name: 'arcsec',
      base: BASE_UNITS.ANGLE,
      prefixes: PREFIXES.NONE,
      value: null,
      // will be filled in by calculateAngleValues()
      offset: 0
    },
    // arcmin = rad / (60 * (360 / 2 * pi)) = rad / 0.00029088820866572159615394846141477
    arcmin: {
      name: 'arcmin',
      base: BASE_UNITS.ANGLE,
      prefixes: PREFIXES.NONE,
      value: null,
      // will be filled in by calculateAngleValues()
      offset: 0
    },
    // Electric current
    A: {
      name: 'A',
      base: BASE_UNITS.CURRENT,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    ampere: {
      name: 'ampere',
      base: BASE_UNITS.CURRENT,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    // Temperature
    // K(C) = °C + 273.15
    // K(F) = (°F + 459.67) * (5 / 9)
    // K(R) = °R * (5 / 9)
    K: {
      name: 'K',
      base: BASE_UNITS.TEMPERATURE,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    degC: {
      name: 'degC',
      base: BASE_UNITS.TEMPERATURE,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 273.15
    },
    degF: {
      name: 'degF',
      base: BASE_UNITS.TEMPERATURE,
      prefixes: PREFIXES.SHORT,
      value: new _Fraction(5, 9),
      offset: 459.67
    },
    degR: {
      name: 'degR',
      base: BASE_UNITS.TEMPERATURE,
      prefixes: PREFIXES.SHORT,
      value: new _Fraction(5, 9),
      offset: 0
    },
    kelvin: {
      name: 'kelvin',
      base: BASE_UNITS.TEMPERATURE,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    celsius: {
      name: 'celsius',
      base: BASE_UNITS.TEMPERATURE,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 273.15
    },
    fahrenheit: {
      name: 'fahrenheit',
      base: BASE_UNITS.TEMPERATURE,
      prefixes: PREFIXES.LONG,
      value: new _Fraction(5, 9),
      offset: 459.67
    },
    rankine: {
      name: 'rankine',
      base: BASE_UNITS.TEMPERATURE,
      prefixes: PREFIXES.LONG,
      value: new _Fraction(5, 9),
      offset: 0
    },
    // amount of substance
    mol: {
      name: 'mol',
      base: BASE_UNITS.AMOUNT_OF_SUBSTANCE,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    mole: {
      name: 'mole',
      base: BASE_UNITS.AMOUNT_OF_SUBSTANCE,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    // luminous intensity
    cd: {
      name: 'cd',
      base: BASE_UNITS.LUMINOUS_INTENSITY,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    candela: {
      name: 'candela',
      base: BASE_UNITS.LUMINOUS_INTENSITY,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    // TODO: units STERADIAN
    // {name: 'sr', base: BASE_UNITS.STERADIAN, prefixes: PREFIXES.NONE, value: 1, offset: 0},
    // {name: 'steradian', base: BASE_UNITS.STERADIAN, prefixes: PREFIXES.NONE, value: 1, offset: 0},

    // Force
    N: {
      name: 'N',
      base: BASE_UNITS.FORCE,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    newton: {
      name: 'newton',
      base: BASE_UNITS.FORCE,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    dyn: {
      name: 'dyn',
      base: BASE_UNITS.FORCE,
      prefixes: PREFIXES.SHORT,
      value: 0.00001,
      offset: 0
    },
    dyne: {
      name: 'dyne',
      base: BASE_UNITS.FORCE,
      prefixes: PREFIXES.LONG,
      value: 0.00001,
      offset: 0
    },
    lbf: {
      name: 'lbf',
      base: BASE_UNITS.FORCE,
      prefixes: PREFIXES.NONE,
      value: 4.4482216152605,
      offset: 0
    },
    poundforce: {
      name: 'poundforce',
      base: BASE_UNITS.FORCE,
      prefixes: PREFIXES.NONE,
      value: 4.4482216152605,
      offset: 0
    },
    kip: {
      name: 'kip',
      base: BASE_UNITS.FORCE,
      prefixes: PREFIXES.LONG,
      value: 4448.2216,
      offset: 0
    },
    kilogramforce: {
      name: 'kilogramforce',
      base: BASE_UNITS.FORCE,
      prefixes: PREFIXES.NONE,
      value: 9.80665,
      offset: 0
    },
    // Energy
    J: {
      name: 'J',
      base: BASE_UNITS.ENERGY,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    joule: {
      name: 'joule',
      base: BASE_UNITS.ENERGY,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    erg: {
      name: 'erg',
      base: BASE_UNITS.ENERGY,
      prefixes: PREFIXES.SHORTLONG,
      // Both kiloerg and kerg are acceptable
      value: 1e-7,
      offset: 0
    },
    Wh: {
      name: 'Wh',
      base: BASE_UNITS.ENERGY,
      prefixes: PREFIXES.SHORT,
      value: 3600,
      offset: 0
    },
    BTU: {
      name: 'BTU',
      base: BASE_UNITS.ENERGY,
      prefixes: PREFIXES.BTU,
      value: 1055.05585262,
      offset: 0
    },
    eV: {
      name: 'eV',
      base: BASE_UNITS.ENERGY,
      prefixes: PREFIXES.SHORT,
      value: 1.602176565e-19,
      offset: 0
    },
    electronvolt: {
      name: 'electronvolt',
      base: BASE_UNITS.ENERGY,
      prefixes: PREFIXES.LONG,
      value: 1.602176565e-19,
      offset: 0
    },
    // Power
    W: {
      name: 'W',
      base: BASE_UNITS.POWER,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    watt: {
      name: 'watt',
      base: BASE_UNITS.POWER,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    hp: {
      name: 'hp',
      base: BASE_UNITS.POWER,
      prefixes: PREFIXES.NONE,
      value: 745.6998715386,
      offset: 0
    },
    // Electrical power units
    VAR: {
      name: 'VAR',
      base: BASE_UNITS.POWER,
      prefixes: PREFIXES.SHORT,
      value: Complex.I,
      offset: 0
    },
    VA: {
      name: 'VA',
      base: BASE_UNITS.POWER,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    // Pressure
    Pa: {
      name: 'Pa',
      base: BASE_UNITS.PRESSURE,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    psi: {
      name: 'psi',
      base: BASE_UNITS.PRESSURE,
      prefixes: PREFIXES.NONE,
      value: 6894.75729276459,
      offset: 0
    },
    atm: {
      name: 'atm',
      base: BASE_UNITS.PRESSURE,
      prefixes: PREFIXES.NONE,
      value: 101325,
      offset: 0
    },
    bar: {
      name: 'bar',
      base: BASE_UNITS.PRESSURE,
      prefixes: PREFIXES.SHORTLONG,
      value: 100000,
      offset: 0
    },
    torr: {
      name: 'torr',
      base: BASE_UNITS.PRESSURE,
      prefixes: PREFIXES.NONE,
      value: 133.322,
      offset: 0
    },
    mmHg: {
      name: 'mmHg',
      base: BASE_UNITS.PRESSURE,
      prefixes: PREFIXES.NONE,
      value: 133.322,
      offset: 0
    },
    mmH2O: {
      name: 'mmH2O',
      base: BASE_UNITS.PRESSURE,
      prefixes: PREFIXES.NONE,
      value: 9.80665,
      offset: 0
    },
    cmH2O: {
      name: 'cmH2O',
      base: BASE_UNITS.PRESSURE,
      prefixes: PREFIXES.NONE,
      value: 98.0665,
      offset: 0
    },
    // Electric charge
    coulomb: {
      name: 'coulomb',
      base: BASE_UNITS.ELECTRIC_CHARGE,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    C: {
      name: 'C',
      base: BASE_UNITS.ELECTRIC_CHARGE,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    // Electric capacitance
    farad: {
      name: 'farad',
      base: BASE_UNITS.ELECTRIC_CAPACITANCE,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    F: {
      name: 'F',
      base: BASE_UNITS.ELECTRIC_CAPACITANCE,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    // Electric potential
    volt: {
      name: 'volt',
      base: BASE_UNITS.ELECTRIC_POTENTIAL,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    V: {
      name: 'V',
      base: BASE_UNITS.ELECTRIC_POTENTIAL,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    // Electric resistance
    ohm: {
      name: 'ohm',
      base: BASE_UNITS.ELECTRIC_RESISTANCE,
      prefixes: PREFIXES.SHORTLONG,
      // Both Mohm and megaohm are acceptable
      value: 1,
      offset: 0
    },
    /*
     * Unicode breaks in browsers if charset is not specified
    Ω: {
      name: 'Ω',
      base: BASE_UNITS.ELECTRIC_RESISTANCE,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    */
    // Electric inductance
    henry: {
      name: 'henry',
      base: BASE_UNITS.ELECTRIC_INDUCTANCE,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    H: {
      name: 'H',
      base: BASE_UNITS.ELECTRIC_INDUCTANCE,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    // Electric conductance
    siemens: {
      name: 'siemens',
      base: BASE_UNITS.ELECTRIC_CONDUCTANCE,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    S: {
      name: 'S',
      base: BASE_UNITS.ELECTRIC_CONDUCTANCE,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    // Magnetic flux
    weber: {
      name: 'weber',
      base: BASE_UNITS.MAGNETIC_FLUX,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    Wb: {
      name: 'Wb',
      base: BASE_UNITS.MAGNETIC_FLUX,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    // Magnetic flux density
    tesla: {
      name: 'tesla',
      base: BASE_UNITS.MAGNETIC_FLUX_DENSITY,
      prefixes: PREFIXES.LONG,
      value: 1,
      offset: 0
    },
    T: {
      name: 'T',
      base: BASE_UNITS.MAGNETIC_FLUX_DENSITY,
      prefixes: PREFIXES.SHORT,
      value: 1,
      offset: 0
    },
    // Binary
    b: {
      name: 'b',
      base: BASE_UNITS.BIT,
      prefixes: PREFIXES.BINARY_SHORT,
      value: 1,
      offset: 0
    },
    bits: {
      name: 'bits',
      base: BASE_UNITS.BIT,
      prefixes: PREFIXES.BINARY_LONG,
      value: 1,
      offset: 0
    },
    B: {
      name: 'B',
      base: BASE_UNITS.BIT,
      prefixes: PREFIXES.BINARY_SHORT,
      value: 8,
      offset: 0
    },
    bytes: {
      name: 'bytes',
      base: BASE_UNITS.BIT,
      prefixes: PREFIXES.BINARY_LONG,
      value: 8,
      offset: 0
    }
  };

  // aliases (formerly plurals)
  // note that ALIASES is only used at creation to create more entries in UNITS by copying the aliased units
  var ALIASES = {
    meters: 'meter',
    inches: 'inch',
    feet: 'foot',
    yards: 'yard',
    miles: 'mile',
    links: 'link',
    rods: 'rod',
    chains: 'chain',
    angstroms: 'angstrom',
    lt: 'l',
    litres: 'litre',
    liter: 'litre',
    liters: 'litre',
    teaspoons: 'teaspoon',
    tablespoons: 'tablespoon',
    minims: 'minim',
    fluiddrams: 'fluiddram',
    fluidounces: 'fluidounce',
    gills: 'gill',
    cups: 'cup',
    pints: 'pint',
    quarts: 'quart',
    gallons: 'gallon',
    beerbarrels: 'beerbarrel',
    oilbarrels: 'oilbarrel',
    hogsheads: 'hogshead',
    gtts: 'gtt',
    grams: 'gram',
    tons: 'ton',
    tonnes: 'tonne',
    grains: 'grain',
    drams: 'dram',
    ounces: 'ounce',
    poundmasses: 'poundmass',
    hundredweights: 'hundredweight',
    sticks: 'stick',
    lb: 'lbm',
    lbs: 'lbm',
    kips: 'kip',
    kgf: 'kilogramforce',
    acres: 'acre',
    hectares: 'hectare',
    sqfeet: 'sqft',
    sqyard: 'sqyd',
    sqmile: 'sqmi',
    sqmiles: 'sqmi',
    mmhg: 'mmHg',
    mmh2o: 'mmH2O',
    cmh2o: 'cmH2O',
    seconds: 'second',
    secs: 'second',
    minutes: 'minute',
    mins: 'minute',
    hours: 'hour',
    hr: 'hour',
    hrs: 'hour',
    days: 'day',
    weeks: 'week',
    months: 'month',
    years: 'year',
    decades: 'decade',
    centuries: 'century',
    millennia: 'millennium',
    hertz: 'hertz',
    radians: 'radian',
    degrees: 'degree',
    gradians: 'gradian',
    cycles: 'cycle',
    arcsecond: 'arcsec',
    arcseconds: 'arcsec',
    arcminute: 'arcmin',
    arcminutes: 'arcmin',
    BTUs: 'BTU',
    watts: 'watt',
    joules: 'joule',
    amperes: 'ampere',
    amps: 'ampere',
    amp: 'ampere',
    coulombs: 'coulomb',
    volts: 'volt',
    ohms: 'ohm',
    farads: 'farad',
    webers: 'weber',
    teslas: 'tesla',
    electronvolts: 'electronvolt',
    moles: 'mole',
    bit: 'bits',
    byte: 'bytes'
  };

  /**
   * Calculate the values for the angle units.
   * Value is calculated as number or BigNumber depending on the configuration
   * @param {{number: 'number' | 'BigNumber'}} config
   */
  function calculateAngleValues(config) {
    if (config.number === 'BigNumber') {
      var pi = createBigNumberPi(_BigNumber);
      UNITS.rad.value = new _BigNumber(1);
      UNITS.deg.value = pi.div(180); // 2 * pi / 360
      UNITS.grad.value = pi.div(200); // 2 * pi / 400
      UNITS.cycle.value = pi.times(2); // 2 * pi
      UNITS.arcsec.value = pi.div(648000); // 2 * pi / 360 / 3600
      UNITS.arcmin.value = pi.div(10800); // 2 * pi / 360 / 60
    } else {
      // number
      UNITS.rad.value = 1;
      UNITS.deg.value = Math.PI / 180; // 2 * pi / 360
      UNITS.grad.value = Math.PI / 200; // 2 * pi / 400
      UNITS.cycle.value = Math.PI * 2; // 2 * pi
      UNITS.arcsec.value = Math.PI / 648000; // 2 * pi / 360 / 3600
      UNITS.arcmin.value = Math.PI / 10800; // 2 * pi / 360 / 60
    }

    // copy to the full names of the angles
    UNITS.radian.value = UNITS.rad.value;
    UNITS.degree.value = UNITS.deg.value;
    UNITS.gradian.value = UNITS.grad.value;
  }

  // apply the angle values now
  calculateAngleValues(config);
  if (on) {
    // recalculate the values on change of configuration
    on('config', function (curr, prev) {
      if (curr.number !== prev.number) {
        calculateAngleValues(curr);
      }
    });
  }

  /**
   * 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.
   * A user perhaps could issue a command to select a preferred unit system, or use the default (see below).
   * 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.
   */
  var UNIT_SYSTEMS = {
    si: {
      // Base units
      NONE: {
        unit: UNIT_NONE,
        prefix: PREFIXES.NONE['']
      },
      LENGTH: {
        unit: UNITS.m,
        prefix: PREFIXES.SHORT['']
      },
      MASS: {
        unit: UNITS.g,
        prefix: PREFIXES.SHORT.k
      },
      TIME: {
        unit: UNITS.s,
        prefix: PREFIXES.SHORT['']
      },
      CURRENT: {
        unit: UNITS.A,
        prefix: PREFIXES.SHORT['']
      },
      TEMPERATURE: {
        unit: UNITS.K,
        prefix: PREFIXES.SHORT['']
      },
      LUMINOUS_INTENSITY: {
        unit: UNITS.cd,
        prefix: PREFIXES.SHORT['']
      },
      AMOUNT_OF_SUBSTANCE: {
        unit: UNITS.mol,
        prefix: PREFIXES.SHORT['']
      },
      ANGLE: {
        unit: UNITS.rad,
        prefix: PREFIXES.SHORT['']
      },
      BIT: {
        unit: UNITS.bits,
        prefix: PREFIXES.SHORT['']
      },
      // Derived units
      FORCE: {
        unit: UNITS.N,
        prefix: PREFIXES.SHORT['']
      },
      ENERGY: {
        unit: UNITS.J,
        prefix: PREFIXES.SHORT['']
      },
      POWER: {
        unit: UNITS.W,
        prefix: PREFIXES.SHORT['']
      },
      PRESSURE: {
        unit: UNITS.Pa,
        prefix: PREFIXES.SHORT['']
      },
      ELECTRIC_CHARGE: {
        unit: UNITS.C,
        prefix: PREFIXES.SHORT['']
      },
      ELECTRIC_CAPACITANCE: {
        unit: UNITS.F,
        prefix: PREFIXES.SHORT['']
      },
      ELECTRIC_POTENTIAL: {
        unit: UNITS.V,
        prefix: PREFIXES.SHORT['']
      },
      ELECTRIC_RESISTANCE: {
        unit: UNITS.ohm,
        prefix: PREFIXES.SHORT['']
      },
      ELECTRIC_INDUCTANCE: {
        unit: UNITS.H,
        prefix: PREFIXES.SHORT['']
      },
      ELECTRIC_CONDUCTANCE: {
        unit: UNITS.S,
        prefix: PREFIXES.SHORT['']
      },
      MAGNETIC_FLUX: {
        unit: UNITS.Wb,
        prefix: PREFIXES.SHORT['']
      },
      MAGNETIC_FLUX_DENSITY: {
        unit: UNITS.T,
        prefix: PREFIXES.SHORT['']
      },
      FREQUENCY: {
        unit: UNITS.Hz,
        prefix: PREFIXES.SHORT['']
      }
    }
  };

  // Clone to create the other unit systems
  UNIT_SYSTEMS.cgs = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si));
  UNIT_SYSTEMS.cgs.LENGTH = {
    unit: UNITS.m,
    prefix: PREFIXES.SHORT.c
  };
  UNIT_SYSTEMS.cgs.MASS = {
    unit: UNITS.g,
    prefix: PREFIXES.SHORT['']
  };
  UNIT_SYSTEMS.cgs.FORCE = {
    unit: UNITS.dyn,
    prefix: PREFIXES.SHORT['']
  };
  UNIT_SYSTEMS.cgs.ENERGY = {
    unit: UNITS.erg,
    prefix: PREFIXES.NONE['']
  };
  // there are wholly 4 unique cgs systems for electricity and magnetism,
  // so let's not worry about it unless somebody complains

  UNIT_SYSTEMS.us = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si));
  UNIT_SYSTEMS.us.LENGTH = {
    unit: UNITS.ft,
    prefix: PREFIXES.NONE['']
  };
  UNIT_SYSTEMS.us.MASS = {
    unit: UNITS.lbm,
    prefix: PREFIXES.NONE['']
  };
  UNIT_SYSTEMS.us.TEMPERATURE = {
    unit: UNITS.degF,
    prefix: PREFIXES.NONE['']
  };
  UNIT_SYSTEMS.us.FORCE = {
    unit: UNITS.lbf,
    prefix: PREFIXES.NONE['']
  };
  UNIT_SYSTEMS.us.ENERGY = {
    unit: UNITS.BTU,
    prefix: PREFIXES.BTU['']
  };
  UNIT_SYSTEMS.us.POWER = {
    unit: UNITS.hp,
    prefix: PREFIXES.NONE['']
  };
  UNIT_SYSTEMS.us.PRESSURE = {
    unit: UNITS.psi,
    prefix: PREFIXES.NONE['']
  };

  // Add additional unit systems here.

  // Choose a unit system to seed the auto unit system.
  UNIT_SYSTEMS.auto = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si));

  // Set the current unit system
  var currentUnitSystem = UNIT_SYSTEMS.auto;

  /**
   * Set a unit system for formatting derived units.
   * @param {string} [name] The name of the unit system.
   */
  Unit.setUnitSystem = function (name) {
    if (hasOwnProperty(UNIT_SYSTEMS, name)) {
      currentUnitSystem = UNIT_SYSTEMS[name];
    } else {
      throw new Error('Unit system ' + name + ' does not exist. Choices are: ' + Object.keys(UNIT_SYSTEMS).join(', '));
    }
  };

  /**
   * Return the current unit system.
   * @return {string} The current unit system.
   */
  Unit.getUnitSystem = function () {
    for (var _key in UNIT_SYSTEMS) {
      if (hasOwnProperty(UNIT_SYSTEMS, _key)) {
        if (UNIT_SYSTEMS[_key] === currentUnitSystem) {
          return _key;
        }
      }
    }
  };

  /**
   * Converters to convert from number to an other numeric type like BigNumber
   * or Fraction
   */
  Unit.typeConverters = {
    BigNumber: function BigNumber(x) {
      if (x !== null && x !== void 0 && x.isFraction) return new _BigNumber(x.n).div(x.d).times(x.s);
      return new _BigNumber(x + ''); // stringify to prevent constructor error
    },
    Fraction: function Fraction(x) {
      return new _Fraction(x);
    },
    Complex: function Complex(x) {
      return x;
    },
    number: function number(x) {
      if (x !== null && x !== void 0 && x.isFraction) return _number(x);
      return x;
    }
  };

  /**
   * Retrieve the right converter function corresponding with this unit's
   * value
   *
   * @memberof Unit
   * @return {Function}
   */
  Unit.prototype._numberConverter = function () {
    var convert = Unit.typeConverters[this.valueType()];
    if (convert) {
      return convert;
    }
    throw new TypeError('Unsupported Unit value type "' + this.valueType() + '"');
  };

  /**
   * Retrieve the right convertor function corresponding with the type
   * of provided exampleValue.
   *
   * @param {string} type   A string 'number', 'BigNumber', or 'Fraction'
   *                        In case of an unknown type,
   * @return {Function}
   */
  Unit._getNumberConverter = function (type) {
    if (!Unit.typeConverters[type]) {
      throw new TypeError('Unsupported type "' + type + '"');
    }
    return Unit.typeConverters[type];
  };

  // Add dimensions to each built-in unit
  for (var _key2 in UNITS) {
    if (hasOwnProperty(UNITS, _key2)) {
      var unit = UNITS[_key2];
      unit.dimensions = unit.base.dimensions;
    }
  }

  // Create aliases
  for (var _name2 in ALIASES) {
    if (hasOwnProperty(ALIASES, _name2)) {
      var _unit2 = UNITS[ALIASES[_name2]];
      var alias = {};
      for (var _key3 in _unit2) {
        if (hasOwnProperty(_unit2, _key3)) {
          alias[_key3] = _unit2[_key3];
        }
      }
      alias.name = _name2;
      UNITS[_name2] = alias;
    }
  }

  /**
   * Checks if a character is a valid latin letter (upper or lower case).
   * Note that this function can be overridden, for example to allow support of other alphabets.
   * @param {string} c Tested character
   */
  Unit.isValidAlpha = function isValidAlpha(c) {
    return /^[a-zA-Z]$/.test(c);
  };
  function assertUnitNameIsValid(name) {
    for (var i = 0; i < name.length; i++) {
      c = name.charAt(i);
      if (i === 0 && !Unit.isValidAlpha(c)) {
        throw new Error('Invalid unit name (must begin with alpha character): "' + name + '"');
      }
      if (i > 0 && !(Unit.isValidAlpha(c) || isDigit(c))) {
        throw new Error('Invalid unit name (only alphanumeric characters are allowed): "' + name + '"');
      }
    }
  }

  /**
   * Wrapper around createUnitSingle.
   * Example:
   *  createUnit({
   *    foo: { },
   *    bar: {
   *      definition: 'kg/foo',
   *      aliases: ['ba', 'barr', 'bars'],
   *      offset: 200
   *    },
   *    baz: '4 bar'
   *  },
   *  {
   *    override: true
   *  })
   * @param {object} obj      Object map. Each key becomes a unit which is defined by its value.
   * @param {object} options
   */
  Unit.createUnit = function (obj, options) {
    if (typeof obj !== 'object') {
      throw new TypeError("createUnit expects first parameter to be of type 'Object'");
    }

    // Remove all units and aliases we are overriding
    if (options && options.override) {
      for (var _key4 in obj) {
        if (hasOwnProperty(obj, _key4)) {
          Unit.deleteUnit(_key4);
        }
        if (obj[_key4].aliases) {
          for (var i = 0; i < obj[_key4].aliases.length; i++) {
            Unit.deleteUnit(obj[_key4].aliases[i]);
          }
        }
      }
    }

    // TODO: traverse multiple times until all units have been added
    var lastUnit;
    for (var _key5 in obj) {
      if (hasOwnProperty(obj, _key5)) {
        lastUnit = Unit.createUnitSingle(_key5, obj[_key5]);
      }
    }
    return lastUnit;
  };

  /**
   * Create a user-defined unit and register it with the Unit type.
   * Example:
   *  createUnitSingle('knot', '0.514444444 m/s')
   *  createUnitSingle('acre', new Unit(43560, 'ft^2'))
   *
   * @param {string} name      The name of the new unit. Must be unique. Example: 'knot'
   * @param {string, Unit, Object} definition      Definition of the unit in terms
   * of existing units. For example, '0.514444444 m / s'. Can be a Unit, a string,
   * or an Object. If an Object, may have the following properties:
   *   - definition {string|Unit} The definition of this unit.
   *   - prefixes {string} "none", "short", "long", "binary_short", or "binary_long".
   *     The default is "none".
   *   - aliases {Array} Array of strings. Example: ['knots', 'kt', 'kts']
   *   - 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.
   *   - baseName {string} If the unit's dimension does not match that of any other
   *     base unit, the name of the newly create base unit. Otherwise, this property
   *     has no effect.
   *
   * @return {Unit}
   */
  Unit.createUnitSingle = function (name, obj) {
    if (typeof obj === 'undefined' || obj === null) {
      obj = {};
    }
    if (typeof name !== 'string') {
      throw new TypeError("createUnitSingle expects first parameter to be of type 'string'");
    }

    // Check collisions with existing units
    if (hasOwnProperty(UNITS, name)) {
      throw new Error('Cannot create unit "' + name + '": a unit with that name already exists');
    }

    // 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.

    assertUnitNameIsValid(name);
    var defUnit = null; // The Unit from which the new unit will be created.
    var aliases = [];
    var offset = 0;
    var definition;
    var prefixes;
    var baseName;
    if (obj && obj.type === 'Unit') {
      defUnit = obj.clone();
    } else if (typeof obj === 'string') {
      if (obj !== '') {
        definition = obj;
      }
    } else if (typeof obj === 'object') {
      definition = obj.definition;
      prefixes = obj.prefixes;
      offset = obj.offset;
      baseName = obj.baseName;
      if (obj.aliases) {
        aliases = obj.aliases.valueOf(); // aliases could be a Matrix, so convert to Array
      }
    } else {
      throw new TypeError('Cannot create unit "' + name + '" from "' + obj.toString() + '": expecting "string" or "Unit" or "Object"');
    }
    if (aliases) {
      for (var i = 0; i < aliases.length; i++) {
        if (hasOwnProperty(UNITS, aliases[i])) {
          throw new Error('Cannot create alias "' + aliases[i] + '": a unit with that name already exists');
        }
      }
    }
    if (definition && typeof definition === 'string' && !defUnit) {
      try {
        defUnit = Unit.parse(definition, {
          allowNoUnits: true
        });
      } catch (ex) {
        ex.message = 'Could not create unit "' + name + '" from "' + definition + '": ' + ex.message;
        throw ex;
      }
    } else if (definition && definition.type === 'Unit') {
      defUnit = definition.clone();
    }
    aliases = aliases || [];
    offset = offset || 0;
    if (prefixes && prefixes.toUpperCase) {
      prefixes = PREFIXES[prefixes.toUpperCase()] || PREFIXES.NONE;
    } else {
      prefixes = PREFIXES.NONE;
    }

    // If defUnit is null, it is because the user did not
    // specify a defintion. So create a new base dimension.
    var newUnit = {};
    if (!defUnit) {
      // Add a new base dimension
      baseName = baseName || name + '_STUFF'; // foo --> foo_STUFF, or the essence of foo
      if (BASE_DIMENSIONS.indexOf(baseName) >= 0) {
        throw new Error('Cannot create new base unit "' + name + '": a base unit with that name already exists (and cannot be overridden)');
      }
      BASE_DIMENSIONS.push(baseName);

      // Push 0 onto existing base units
      for (var b in BASE_UNITS) {
        if (hasOwnProperty(BASE_UNITS, b)) {
          BASE_UNITS[b].dimensions[BASE_DIMENSIONS.length - 1] = 0;
        }
      }

      // Add the new base unit
      var newBaseUnit = {
        dimensions: []
      };
      for (var _i6 = 0; _i6 < BASE_DIMENSIONS.length; _i6++) {
        newBaseUnit.dimensions[_i6] = 0;
      }
      newBaseUnit.dimensions[BASE_DIMENSIONS.length - 1] = 1;
      newBaseUnit.key = baseName;
      BASE_UNITS[baseName] = newBaseUnit;
      newUnit = {
        name,
        value: 1,
        dimensions: BASE_UNITS[baseName].dimensions.slice(0),
        prefixes,
        offset,
        base: BASE_UNITS[baseName]
      };
      currentUnitSystem[baseName] = {
        unit: newUnit,
        prefix: PREFIXES.NONE['']
      };
    } else {
      newUnit = {
        name,
        value: defUnit.value,
        dimensions: defUnit.dimensions.slice(0),
        prefixes,
        offset
      };

      // Create a new base if no matching base exists
      var anyMatch = false;
      for (var _i7 in BASE_UNITS) {
        if (hasOwnProperty(BASE_UNITS, _i7)) {
          var match = true;
          for (var j = 0; j < BASE_DIMENSIONS.length; j++) {
            if (Math.abs((newUnit.dimensions[j] || 0) - (BASE_UNITS[_i7].dimensions[j] || 0)) > 1e-12) {
              match = false;
              break;
            }
          }
          if (match) {
            anyMatch = true;
            newUnit.base = BASE_UNITS[_i7];
            break;
          }
        }
      }
      if (!anyMatch) {
        baseName = baseName || name + '_STUFF'; // foo --> foo_STUFF, or the essence of foo
        // Add the new base unit
        var _newBaseUnit = {
          dimensions: defUnit.dimensions.slice(0)
        };
        _newBaseUnit.key = baseName;
        BASE_UNITS[baseName] = _newBaseUnit;
        currentUnitSystem[baseName] = {
          unit: newUnit,
          prefix: PREFIXES.NONE['']
        };
        newUnit.base = BASE_UNITS[baseName];
      }
    }
    Unit.UNITS[name] = newUnit;
    for (var _i8 = 0; _i8 < aliases.length; _i8++) {
      var aliasName = aliases[_i8];
      var _alias = {};
      for (var _key6 in newUnit) {
        if (hasOwnProperty(newUnit, _key6)) {
          _alias[_key6] = newUnit[_key6];
        }
      }
      _alias.name = aliasName;
      Unit.UNITS[aliasName] = _alias;
    }

    // delete the memoization cache because we created a new unit
    delete _findUnit.cache;
    return new Unit(null, name);
  };
  Unit.deleteUnit = function (name) {
    delete Unit.UNITS[name];

    // delete the memoization cache because we deleted a unit
    delete _findUnit.cache;
  };

  // expose arrays with prefixes, dimensions, units, systems
  Unit.PREFIXES = PREFIXES;
  Unit.BASE_DIMENSIONS = BASE_DIMENSIONS;
  Unit.BASE_UNITS = BASE_UNITS;
  Unit.UNIT_SYSTEMS = UNIT_SYSTEMS;
  Unit.UNITS = UNITS;
  return Unit;
}, {
  isClass: true
});

var name$2n = 'unit';
var dependencies$2n = ['typed', 'Unit'];

// This function is named createUnitFunction to prevent a naming conflict with createUnit
var createUnitFunction = /* #__PURE__ */factory(name$2n, dependencies$2n, _ref => {
  var {
    typed,
    Unit
  } = _ref;
  /**
   * Create a unit. Depending on the passed arguments, the function
   * will create and return a new math.Unit object.
   * When a matrix is provided, all elements will be converted to units.
   *
   * Syntax:
   *
   *     math.unit(unit : string)
   *     math.unit(value : number, valuelessUnit : Unit)
   *     math.unit(value : number, valuelessUnit : string)
   *
   * Examples:
   *
   *    const kph = math.unit('km/h')   // returns Unit km/h (valueless)
   *    const v = math.unit(25, kph)    // returns Unit 25 km/h
   *    const a = math.unit(5, 'cm')    // returns Unit 50 mm
   *    const b = math.unit('23 kg')    // returns Unit 23 kg
   *    a.to('m')                       // returns Unit 0.05 m
   *
   * See also:
   *
   *    bignumber, boolean, complex, index, matrix, number, string, createUnit
   *
   * @param {* | Array | Matrix} args   A number and unit.
   * @return {Unit | Array | Matrix}    The created unit
   */

  return typed(name$2n, {
    Unit: function Unit(x) {
      return x.clone();
    },
    string: function string(x) {
      if (Unit.isValuelessUnit(x)) {
        return new Unit(null, x); // a pure unit
      }
      return Unit.parse(x, {
        allowNoUnits: true
      }); // a unit with value, like '5cm'
    },
    'number | BigNumber | Fraction | Complex, string | Unit': function numberBigNumberFractionComplexStringUnit(value, unit) {
      return new Unit(value, unit);
    },
    'number | BigNumber | Fraction': function numberBigNumberFraction(value) {
      // dimensionless
      return new Unit(value);
    },
    'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self))
  });
});

var name$2m = 'sparse';
var dependencies$2m = ['typed', 'SparseMatrix'];
var createSparse = /* #__PURE__ */factory(name$2m, dependencies$2m, _ref => {
  var {
    typed,
    SparseMatrix
  } = _ref;
  /**
   * Create a Sparse Matrix. The function creates a new `math.Matrix` object from
   * an `Array`. A Matrix has utility functions to manipulate the data in the
   * matrix, like getting the size and getting or setting values in the matrix.
   * Note that a Sparse Matrix is always 2-dimensional, so for example if
   * you create one from a plain array of _n_ numbers, you get an _n_ by 1
   * Sparse "column vector".
   *
   * Syntax:
   *
   *    math.sparse()               // creates an empty sparse matrix.
   *    math.sparse(data)           // creates a sparse matrix with initial data.
   *    math.sparse(data, 'number') // creates a sparse matrix with initial data, number datatype.
   *
   * Examples:
   *
   *    let m = math.sparse([[1, 2], [3, 4]])
   *    m.size()                        // Array [2, 2]
   *    m.resize([3, 2], 5)
   *    m.valueOf()                     // Array [[1, 2], [3, 4], [5, 5]]
   *    m.get([1, 0])                    // number 3
   *    let v = math.sparse([0, 0, 1])
   *    v.size()                        // Array [3, 1]
   *    v.get([2, 0])                   // number 1
   *
   * See also:
   *
   *    bignumber, boolean, complex, index, number, string, unit, matrix
   *
   * @param {Array | Matrix} [data]    A two dimensional array
   *
   * @return {Matrix} The created matrix
   */
  return typed(name$2m, {
    '': function _() {
      return new SparseMatrix([]);
    },
    string: function string(datatype) {
      return new SparseMatrix([], datatype);
    },
    'Array | Matrix': function ArrayMatrix(data) {
      return new SparseMatrix(data);
    },
    'Array | Matrix, string': function ArrayMatrixString(data, datatype) {
      return new SparseMatrix(data, datatype);
    }
  });
});

var name$2l = 'createUnit';
var dependencies$2l = ['typed', 'Unit'];
var createCreateUnit = /* #__PURE__ */factory(name$2l, dependencies$2l, _ref => {
  var {
    typed,
    Unit
  } = _ref;
  /**
   * Create a user-defined unit and register it with the Unit type.
   *
   * Syntax:
   *
   *     math.createUnit({
   *       baseUnit1: {
   *         aliases: [string, ...]
   *         prefixes: object
   *       },
   *       unit2: {
   *         definition: string,
   *         aliases: [string, ...]
   *         prefixes: object,
   *         offset: number
   *       },
   *       unit3: string    // Shortcut
   *     })
   *
   *     // Another shortcut:
   *     math.createUnit(string, unit : string, [object])
   *
   * Examples:
   *
   *     math.createUnit('foo')
   *     math.createUnit('knot', {definition: '0.514444444 m/s', aliases: ['knots', 'kt', 'kts']})
   *     math.createUnit('mph', '1 mile/hour')
   *     math.createUnit('km', math.unit(1000, 'm'))
   *
   * @param {string} name      The name of the new unit. Must be unique. Example: 'knot'
   * @param {string, UnitDefinition, Unit} definition      Definition of the unit in terms of existing units. For example, '0.514444444 m / s'.
   * @param {Object} options   (optional) An object containing any of the following properties:
   *     - `prefixes {string}` "none", "short", "long", "binary_short", or "binary_long". The default is "none".
   *     - `aliases {Array}` Array of strings. Example: ['knots', 'kt', 'kts']
   *     - `offset {Numeric}` An offset to apply when converting from the unit. For example, the offset for celsius is 273.15. Default is 0.
   *
   * See also:
   *
   *     unit
   *
   * @return {Unit} The new unit
   */
  return typed(name$2l, {
    // 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.
    'Object, Object': function ObjectObject(obj, options) {
      return Unit.createUnit(obj, options);
    },
    // Same as above but without the options.
    Object: function Object(obj) {
      return Unit.createUnit(obj, {});
    },
    // Shortcut method for creating one unit.
    'string, Unit | string | Object, Object': function stringUnitStringObjectObject(name, def, options) {
      var obj = {};
      obj[name] = def;
      return Unit.createUnit(obj, options);
    },
    // Same as above but without the options.
    'string, Unit | string | Object': function stringUnitStringObject(name, def) {
      var obj = {};
      obj[name] = def;
      return Unit.createUnit(obj, {});
    },
    // Without a definition, creates a base unit.
    string: function string(name) {
      var obj = {};
      obj[name] = {};
      return Unit.createUnit(obj, {});
    }
  });
});

var name$2k = 'acos';
var dependencies$2k = ['typed', 'config', 'Complex'];
var createAcos = /* #__PURE__ */factory(name$2k, dependencies$2k, _ref => {
  var {
    typed,
    config,
    Complex
  } = _ref;
  /**
   * Calculate the inverse cosine of a value.
   *
   * To avoid confusion with the matrix arccosine, this function does not
   * apply to matrices.
   *
   * Syntax:
   *
   *    math.acos(x)
   *
   * Examples:
   *
   *    math.acos(0.5)           // returns number 1.0471975511965979
   *    math.acos(math.cos(1.5)) // returns number 1.5
   *
   *    math.acos(2)             // returns Complex 0 + 1.3169578969248166 i
   *
   * See also:
   *
   *    cos, atan, asin
   *
   * @param {number | BigNumber | Complex} x  Function input
   * @return {number | BigNumber | Complex} The arc cosine of x
   */
  return typed(name$2k, {
    number: function number(x) {
      if (x >= -1 && x <= 1 || config.predictable) {
        return Math.acos(x);
      } else {
        return new Complex(x, 0).acos();
      }
    },
    Complex: function Complex(x) {
      return x.acos();
    },
    BigNumber: function BigNumber(x) {
      return x.acos();
    }
  });
});

var name$2j = 'acosh';
var dependencies$2j = ['typed', 'config', 'Complex'];
var createAcosh = /* #__PURE__ */factory(name$2j, dependencies$2j, _ref => {
  var {
    typed,
    config,
    Complex
  } = _ref;
  /**
   * Calculate the hyperbolic arccos of a value,
   * defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.acosh(x)
   *
   * Examples:
   *
   *    math.acosh(1.5)       // returns 0.9624236501192069
   *
   * See also:
   *
   *    cosh, asinh, atanh
   *
   * @param {number | BigNumber | Complex} x  Function input
   * @return {number | BigNumber | Complex} Hyperbolic arccosine of x
   */
  return typed(name$2j, {
    number: function number(x) {
      if (x >= 1 || config.predictable) {
        return acoshNumber(x);
      }
      if (x <= -1) {
        return new Complex(Math.log(Math.sqrt(x * x - 1) - x), Math.PI);
      }
      return new Complex(x, 0).acosh();
    },
    Complex: function Complex(x) {
      return x.acosh();
    },
    BigNumber: function BigNumber(x) {
      return x.acosh();
    }
  });
});

var name$2i = 'acot';
var dependencies$2i = ['typed', 'BigNumber'];
var createAcot = /* #__PURE__ */factory(name$2i, dependencies$2i, _ref => {
  var {
    typed,
    BigNumber: _BigNumber
  } = _ref;
  /**
   * Calculate the inverse cotangent of a value, defined as `acot(x) = atan(1/x)`.
   *
   * To avoid confusion with the matrix arccotanget, this function does not
   * apply to matrices.
   *
   * Syntax:
   *
   *    math.acot(x)
   *
   * Examples:
   *
   *    math.acot(0.5)           // returns number 1.1071487177940904
   *    math.acot(2)             // returns number 0.4636476090008061
   *    math.acot(math.cot(1.5)) // returns number 1.5
   *
   * See also:
   *
   *    cot, atan
   *
   * @param {number | BigNumber| Complex} x   Function input
   * @return {number | BigNumber| Complex} The arc cotangent of x
   */
  return typed(name$2i, {
    number: acotNumber,
    Complex: function Complex(x) {
      return x.acot();
    },
    BigNumber: function BigNumber(x) {
      return new _BigNumber(1).div(x).atan();
    }
  });
});

var name$2h = 'acoth';
var dependencies$2h = ['typed', 'config', 'Complex', 'BigNumber'];
var createAcoth = /* #__PURE__ */factory(name$2h, dependencies$2h, _ref => {
  var {
    typed,
    config,
    Complex,
    BigNumber: _BigNumber
  } = _ref;
  /**
   * Calculate the hyperbolic arccotangent of a value,
   * defined as `acoth(x) = atanh(1/x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.
   *
   * To avoid confusion with the matrix hyperbolic arccotangent, this
   * function does not apply to matrices.
   *
   * Syntax:
   *
   *    math.acoth(x)
   *
   * Examples:
   *
   *    math.acoth(0.5)       // returns 0.8047189562170503
   *
   * See also:
   *
   *    acsch, asech
   *
   * @param {number | BigNumber | Complex} x  Function input
   * @return {number | BigNumber | Complex} Hyperbolic arccotangent of x
   */
  return typed(name$2h, {
    number: function number(x) {
      if (x >= 1 || x <= -1 || config.predictable) {
        return acothNumber(x);
      }
      return new Complex(x, 0).acoth();
    },
    Complex: function Complex(x) {
      return x.acoth();
    },
    BigNumber: function BigNumber(x) {
      return new _BigNumber(1).div(x).atanh();
    }
  });
});

var name$2g = 'acsc';
var dependencies$2g = ['typed', 'config', 'Complex', 'BigNumber'];
var createAcsc = /* #__PURE__ */factory(name$2g, dependencies$2g, _ref => {
  var {
    typed,
    config,
    Complex,
    BigNumber: _BigNumber
  } = _ref;
  /**
   * Calculate the inverse cosecant of a value, defined as `acsc(x) = asin(1/x)`.
   *
   * To avoid confusion with the matrix arccosecant, this function does not
   * apply to matrices.
   *
   * Syntax:
   *
   *    math.acsc(x)
   *
   * Examples:
   *
   *    math.acsc(2)             // returns 0.5235987755982989
   *    math.acsc(0.5)           // returns Complex 1.5707963267948966 -1.3169578969248166i
   *    math.acsc(math.csc(1.5)) // returns number ~1.5
   *
   * See also:
   *
   *    csc, asin, asec
   *
   * @param {number | BigNumber | Complex} x   Function input
   * @return {number | BigNumber | Complex} The arc cosecant of x
   */
  return typed(name$2g, {
    number: function number(x) {
      if (x <= -1 || x >= 1 || config.predictable) {
        return acscNumber(x);
      }
      return new Complex(x, 0).acsc();
    },
    Complex: function Complex(x) {
      return x.acsc();
    },
    BigNumber: function BigNumber(x) {
      return new _BigNumber(1).div(x).asin();
    }
  });
});

var name$2f = 'acsch';
var dependencies$2f = ['typed', 'BigNumber'];
var createAcsch = /* #__PURE__ */factory(name$2f, dependencies$2f, _ref => {
  var {
    typed,
    BigNumber: _BigNumber
  } = _ref;
  /**
   * Calculate the hyperbolic arccosecant of a value,
   * defined as `acsch(x) = asinh(1/x) = ln(1/x + sqrt(1/x^2 + 1))`.
   *
   * To avoid confusion with the matrix hyperbolic arccosecant, this function
   * does not apply to matrices.
   *
   * Syntax:
   *
   *    math.acsch(x)
   *
   * Examples:
   *
   *    math.acsch(0.5)       // returns 1.4436354751788103
   *
   * See also:
   *
   *    asech, acoth
   *
   * @param {number | BigNumber | Complex} x  Function input
   * @return {number | BigNumber | Complex} Hyperbolic arccosecant of x
   */
  return typed(name$2f, {
    number: acschNumber,
    Complex: function Complex(x) {
      return x.acsch();
    },
    BigNumber: function BigNumber(x) {
      return new _BigNumber(1).div(x).asinh();
    }
  });
});

var name$2e = 'asec';
var dependencies$2e = ['typed', 'config', 'Complex', 'BigNumber'];
var createAsec = /* #__PURE__ */factory(name$2e, dependencies$2e, _ref => {
  var {
    typed,
    config,
    Complex,
    BigNumber: _BigNumber
  } = _ref;
  /**
   * Calculate the inverse secant of a value. Defined as `asec(x) = acos(1/x)`.
   *
   * To avoid confusion with the matrix arcsecant, this function does not
   * apply to matrices.
   *
   * Syntax:
   *
   *    math.asec(x)
   *
   * Examples:
   *
   *    math.asec(2)             // returns 1.0471975511965979
   *    math.asec(math.sec(1.5)) // returns 1.5
   *
   *    math.asec(0.5)           // returns Complex 0 + 1.3169578969248166i
   *
   * See also:
   *
   *    acos, acot, acsc
   *
   * @param {number | BigNumber | Complex} x  Function input
   * @return {number | BigNumber | Complex} The arc secant of x
   */
  return typed(name$2e, {
    number: function number(x) {
      if (x <= -1 || x >= 1 || config.predictable) {
        return asecNumber(x);
      }
      return new Complex(x, 0).asec();
    },
    Complex: function Complex(x) {
      return x.asec();
    },
    BigNumber: function BigNumber(x) {
      return new _BigNumber(1).div(x).acos();
    }
  });
});

var name$2d = 'asech';
var dependencies$2d = ['typed', 'config', 'Complex', 'BigNumber'];
var createAsech = /* #__PURE__ */factory(name$2d, dependencies$2d, _ref => {
  var {
    typed,
    config,
    Complex,
    BigNumber: _BigNumber
  } = _ref;
  /**
   * Calculate the hyperbolic arcsecant of a value,
   * defined as `asech(x) = acosh(1/x) = ln(sqrt(1/x^2 - 1) + 1/x)`.
   *
   * To avoid confusion with the matrix hyperbolic arcsecant, this function
   * does not apply to matrices.
   *
   * Syntax:
   *
   *    math.asech(x)
   *
   * Examples:
   *
   *    math.asech(0.5)       // returns 1.3169578969248166
   *
   * See also:
   *
   *    acsch, acoth
   *
   * @param {number | BigNumber | Complex} x  Function input
   * @return {number | BigNumber | Complex} Hyperbolic arcsecant of x
   */
  return typed(name$2d, {
    number: function number(x) {
      if (x <= 1 && x >= -1 || config.predictable) {
        var xInv = 1 / x;
        if (xInv > 0 || config.predictable) {
          return asechNumber(x);
        }
        var ret = Math.sqrt(xInv * xInv - 1);
        return new Complex(Math.log(ret - xInv), Math.PI);
      }
      return new Complex(x, 0).asech();
    },
    Complex: function Complex(x) {
      return x.asech();
    },
    BigNumber: function BigNumber(x) {
      return new _BigNumber(1).div(x).acosh();
    }
  });
});

var name$2c = 'asin';
var dependencies$2c = ['typed', 'config', 'Complex'];
var createAsin = /* #__PURE__ */factory(name$2c, dependencies$2c, _ref => {
  var {
    typed,
    config,
    Complex
  } = _ref;
  /**
   * Calculate the inverse sine of a value.
   *
   * To avoid confusion with the matric arcsine, this function does not apply
   * to matrices.
   *
   * Syntax:
   *
   *    math.asin(x)
   *
   * Examples:
   *
   *    math.asin(0.5)           // returns number 0.5235987755982989
   *    math.asin(math.sin(1.5)) // returns number ~1.5
   *
   *    math.asin(2)             // returns Complex 1.5707963267948966 -1.3169578969248166i
   *
   * See also:
   *
   *    sin, atan, acos
   *
   * @param {number | BigNumber | Complex} x   Function input
   * @return {number | BigNumber | Complex} The arc sine of x
   */
  return typed(name$2c, {
    number: function number(x) {
      if (x >= -1 && x <= 1 || config.predictable) {
        return Math.asin(x);
      } else {
        return new Complex(x, 0).asin();
      }
    },
    Complex: function Complex(x) {
      return x.asin();
    },
    BigNumber: function BigNumber(x) {
      return x.asin();
    }
  });
});

var name$2b = 'asinh';
var dependencies$2b = ['typed'];
var createAsinh = /* #__PURE__ */factory(name$2b, dependencies$2b, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Calculate the hyperbolic arcsine of a value,
   * defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.
   *
   * To avoid confusion with the matrix hyperbolic arcsine, this function
   * does not apply to matrices.
   *
   * Syntax:
   *
   *    math.asinh(x)
   *
   * Examples:
   *
   *    math.asinh(0.5)       // returns 0.48121182505960347
   *
   * See also:
   *
   *    acosh, atanh
   *
   * @param {number | BigNumber | Complex} x  Function input
   * @return {number | BigNumber | Complex} Hyperbolic arcsine of x
   */
  return typed('asinh', {
    number: asinhNumber,
    Complex: function Complex(x) {
      return x.asinh();
    },
    BigNumber: function BigNumber(x) {
      return x.asinh();
    }
  });
});

var name$2a = 'atan';
var dependencies$2a = ['typed'];
var createAtan = /* #__PURE__ */factory(name$2a, dependencies$2a, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Calculate the inverse tangent of a value.
   *
   * To avoid confusion with matrix arctangent, this function does not apply
   * to matrices.
   *
   * Syntax:
   *
   *    math.atan(x)
   *
   * Examples:
   *
   *    math.atan(0.5)           // returns number 0.4636476090008061
   *    math.atan(2)             // returns number 1.1071487177940904
   *    math.atan(math.tan(1.5)) // returns number 1.5
   *
   * See also:
   *
   *    tan, asin, acos
   *
   * @param {number | BigNumber | Complex} x   Function input
   * @return {number | BigNumber | Complex} The arc tangent of x
   */
  return typed('atan', {
    number: function number(x) {
      return Math.atan(x);
    },
    Complex: function Complex(x) {
      return x.atan();
    },
    BigNumber: function BigNumber(x) {
      return x.atan();
    }
  });
});

var name$29 = 'atan2';
var dependencies$29 = ['typed', 'matrix', 'equalScalar', 'BigNumber', 'DenseMatrix', 'concat'];
var createAtan2 = /* #__PURE__ */factory(name$29, dependencies$29, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    BigNumber,
    DenseMatrix,
    concat
  } = _ref;
  var matAlgo02xDS0 = createMatAlgo02xDS0({
    typed,
    equalScalar
  });
  var matAlgo03xDSf = createMatAlgo03xDSf({
    typed
  });
  var matAlgo09xS0Sf = createMatAlgo09xS0Sf({
    typed,
    equalScalar
  });
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matAlgo12xSfs = createMatAlgo12xSfs({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });

  /**
   * Calculate the inverse tangent function with two arguments, y/x.
   * By providing two arguments, the right quadrant of the computed angle can be
   * determined.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.atan2(y, x)
   *
   * Examples:
   *
   *    math.atan2(2, 2) / math.pi       // returns number 0.25
   *
   *    const angle = math.unit(60, 'deg') // returns Unit 60 deg
   *    const x = math.cos(angle)
   *    const y = math.sin(angle)
   *
   *    math.atan(2)             // returns number 1.1071487177940904
   *
   * See also:
   *
   *    tan, atan, sin, cos
   *
   * @param {number | Array | Matrix} y  Second dimension
   * @param {number | Array | Matrix} x  First dimension
   * @return {number | Array | Matrix} Four-quadrant inverse tangent
   */
  return typed(name$29, {
    'number, number': Math.atan2,
    // Complex numbers doesn't seem to have a reasonable implementation of
    // atan2(). Even Matlab removed the support, after they only calculated
    // the atan only on base of the real part of the numbers and ignored
    // the imaginary.

    'BigNumber, BigNumber': (y, x) => BigNumber.atan2(y, x)
  }, matrixAlgorithmSuite({
    scalar: 'number | BigNumber',
    SS: matAlgo09xS0Sf,
    DS: matAlgo03xDSf,
    SD: matAlgo02xDS0,
    Ss: matAlgo11xS0s,
    sS: matAlgo12xSfs
  }));
});

var name$28 = 'atanh';
var dependencies$28 = ['typed', 'config', 'Complex'];
var createAtanh = /* #__PURE__ */factory(name$28, dependencies$28, _ref => {
  var {
    typed,
    config,
    Complex
  } = _ref;
  /**
   * Calculate the hyperbolic arctangent of a value,
   * defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.
   *
   * To avoid confusion with the matrix hyperbolic arctangent, this function
   * does not apply to matrices.
   *
   * Syntax:
   *
   *    math.atanh(x)
   *
   * Examples:
   *
   *    math.atanh(0.5)       // returns 0.5493061443340549
   *
   * See also:
   *
   *    acosh, asinh
   *
   * @param {number | BigNumber | Complex} x  Function input
   * @return {number | BigNumber | Complex} Hyperbolic arctangent of x
   */
  return typed(name$28, {
    number: function number(x) {
      if (x <= 1 && x >= -1 || config.predictable) {
        return atanhNumber(x);
      }
      return new Complex(x, 0).atanh();
    },
    Complex: function Complex(x) {
      return x.atanh();
    },
    BigNumber: function BigNumber(x) {
      return x.atanh();
    }
  });
});

var createTrigUnit = /* #__PURE__ */factory('trigUnit', ['typed'], _ref => {
  var {
    typed
  } = _ref;
  return {
    Unit: typed.referToSelf(self => x => {
      if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) {
        throw new TypeError('Unit in function cot is no angle');
      }
      return typed.find(self, x.valueType())(x.value);
    })
  };
});

var name$27 = 'cos';
var dependencies$27 = ['typed'];
var createCos = /* #__PURE__ */factory(name$27, dependencies$27, _ref => {
  var {
    typed
  } = _ref;
  var trigUnit = createTrigUnit({
    typed
  });

  /**
   * Calculate the cosine of a value.
   *
   * To avoid confusion with the matrix cosine, this function does not
   * apply to matrices.
   *
   * Syntax:
   *
   *    math.cos(x)
   *
   * Examples:
   *
   *    math.cos(2)                      // returns number -0.4161468365471422
   *    math.cos(math.pi / 4)            // returns number  0.7071067811865475
   *    math.cos(math.unit(180, 'deg'))  // returns number -1
   *    math.cos(math.unit(60, 'deg'))   // returns number  0.5
   *
   *    const angle = 0.2
   *    math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2) // returns number ~1
   *
   * See also:
   *
   *    cos, tan
   *
   * @param {number | BigNumber | Complex | Unit} x  Function input
   * @return {number | BigNumber | Complex} Cosine of x
   */
  return typed(name$27, {
    number: Math.cos,
    'Complex | BigNumber': x => x.cos()
  }, trigUnit);
});

var name$26 = 'cosh';
var dependencies$26 = ['typed'];
var createCosh = /* #__PURE__ */factory(name$26, dependencies$26, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Calculate the hyperbolic cosine of a value,
   * defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`.
   *
   * To avoid confusion with the matrix hyperbolic cosine, this function does
   * not apply to matrices.
   *
   * Syntax:
   *
   *    math.cosh(x)
   *
   * Examples:
   *
   *    math.cosh(0.5)       // returns number 1.1276259652063807
   *
   * See also:
   *
   *    sinh, tanh
   *
   * @param {number | BigNumber | Complex} x  Function input
   * @return {number | BigNumber | Complex} Hyperbolic cosine of x
   */
  return typed(name$26, {
    number: cosh$1,
    'Complex | BigNumber': x => x.cosh()
  });
});

var name$25 = 'cot';
var dependencies$25 = ['typed', 'BigNumber'];
var createCot = /* #__PURE__ */factory(name$25, dependencies$25, _ref => {
  var {
    typed,
    BigNumber: _BigNumber
  } = _ref;
  var trigUnit = createTrigUnit({
    typed
  });

  /**
   * Calculate the cotangent of a value. Defined as `cot(x) = 1 / tan(x)`.
   *
   * To avoid confusion with the matrix cotangent, this function does not
   * apply to matrices.
   *
   * Syntax:
   *
   *    math.cot(x)
   *
   * Examples:
   *
   *    math.cot(2)      // returns number -0.45765755436028577
   *    1 / math.tan(2)  // returns number -0.45765755436028577
   *
   * See also:
   *
   *    tan, sec, csc
   *
   * @param {number | Complex | Unit | Array | Matrix} x  Function input
   * @return {number | Complex | Array | Matrix} Cotangent of x
   */
  return typed(name$25, {
    number: cotNumber,
    Complex: x => x.cot(),
    BigNumber: x => new _BigNumber(1).div(x.tan())
  }, trigUnit);
});

var name$24 = 'coth';
var dependencies$24 = ['typed', 'BigNumber'];
var createCoth = /* #__PURE__ */factory(name$24, dependencies$24, _ref => {
  var {
    typed,
    BigNumber: _BigNumber
  } = _ref;
  /**
   * Calculate the hyperbolic cotangent of a value,
   * defined as `coth(x) = 1 / tanh(x)`.
   *
   * To avoid confusion with the matrix hyperbolic cotangent, this function
   * does not apply to matrices.
   *
   * Syntax:
   *
   *    math.coth(x)
   *
   * Examples:
   *
   *    // coth(x) = 1 / tanh(x)
   *    math.coth(2)         // returns 1.0373147207275482
   *    1 / math.tanh(2)     // returns 1.0373147207275482
   *
   * See also:
   *
   *    sinh, tanh, cosh
   *
   * @param {number | BigNumber | Complex} x  Function input
   * @return {number | BigNumber | Complex} Hyperbolic cotangent of x
   */
  return typed(name$24, {
    number: cothNumber,
    Complex: x => x.coth(),
    BigNumber: x => new _BigNumber(1).div(x.tanh())
  });
});

var name$23 = 'csc';
var dependencies$23 = ['typed', 'BigNumber'];
var createCsc = /* #__PURE__ */factory(name$23, dependencies$23, _ref => {
  var {
    typed,
    BigNumber: _BigNumber
  } = _ref;
  var trigUnit = createTrigUnit({
    typed
  });

  /**
   * Calculate the cosecant of a value, defined as `csc(x) = 1/sin(x)`.
   *
   * To avoid confusion with the matrix cosecant, this function does not
   * apply to matrices.
   *
   * Syntax:
   *
   *    math.csc(x)
   *
   * Examples:
   *
   *    math.csc(2)      // returns number 1.099750170294617
   *    1 / math.sin(2)  // returns number 1.099750170294617
   *
   * See also:
   *
   *    sin, sec, cot
   *
   * @param {number | BigNumber | Complex | Unit} x  Function input
   * @return {number | BigNumber | Complex} Cosecant of x
   */
  return typed(name$23, {
    number: cscNumber,
    Complex: x => x.csc(),
    BigNumber: x => new _BigNumber(1).div(x.sin())
  }, trigUnit);
});

var name$22 = 'csch';
var dependencies$22 = ['typed', 'BigNumber'];
var createCsch = /* #__PURE__ */factory(name$22, dependencies$22, _ref => {
  var {
    typed,
    BigNumber: _BigNumber
  } = _ref;
  /**
   * Calculate the hyperbolic cosecant of a value,
   * defined as `csch(x) = 1 / sinh(x)`.
   *
   * To avoid confusion with the matrix hyperbolic cosecant, this function
   * does not apply to matrices.
   *
   * Syntax:
   *
   *    math.csch(x)
   *
   * Examples:
   *
   *    // csch(x) = 1/ sinh(x)
   *    math.csch(0.5)       // returns 1.9190347513349437
   *    1 / math.sinh(0.5)   // returns 1.9190347513349437
   *
   * See also:
   *
   *    sinh, sech, coth
   *
   * @param {number | BigNumber | Complex} x  Function input
   * @return {number | BigNumber | Complex} Hyperbolic cosecant of x
   */
  return typed(name$22, {
    number: cschNumber,
    Complex: x => x.csch(),
    BigNumber: x => new _BigNumber(1).div(x.sinh())
  });
});

var name$21 = 'sec';
var dependencies$21 = ['typed', 'BigNumber'];
var createSec = /* #__PURE__ */factory(name$21, dependencies$21, _ref => {
  var {
    typed,
    BigNumber: _BigNumber
  } = _ref;
  var trigUnit = createTrigUnit({
    typed
  });

  /**
   * Calculate the secant of a value, defined as `sec(x) = 1/cos(x)`.
   *
   * To avoid confusion with the matrix secant, this function does not
   * apply to matrices.
   *
   * Syntax:
   *
   *    math.sec(x)
   *
   * Examples:
   *
   *    math.sec(2)      // returns number -2.4029979617223822
   *    1 / math.cos(2)  // returns number -2.4029979617223822
   *
   * See also:
   *
   *    cos, csc, cot
   *
   * @param {number | BigNumber | Complex | Unit} x  Function input
   * @return {number | BigNumber | Complex} Secant of x
   */
  return typed(name$21, {
    number: secNumber,
    Complex: x => x.sec(),
    BigNumber: x => new _BigNumber(1).div(x.cos())
  }, trigUnit);
});

var name$20 = 'sech';
var dependencies$20 = ['typed', 'BigNumber'];
var createSech = /* #__PURE__ */factory(name$20, dependencies$20, _ref => {
  var {
    typed,
    BigNumber: _BigNumber
  } = _ref;
  /**
   * Calculate the hyperbolic secant of a value,
   * defined as `sech(x) = 1 / cosh(x)`.
   *
   * To avoid confusion with the matrix hyperbolic secant, this function does
   * not apply to matrices.
   *
   * Syntax:
   *
   *    math.sech(x)
   *
   * Examples:
   *
   *    // sech(x) = 1/ cosh(x)
   *    math.sech(0.5)       // returns 0.886818883970074
   *    1 / math.cosh(0.5)   // returns 0.886818883970074
   *
   * See also:
   *
   *    cosh, csch, coth
   *
   * @param {number | BigNumber | Complex} x  Function input
   * @return {number | BigNumber | Complex} Hyperbolic secant of x
   */
  return typed(name$20, {
    number: sechNumber,
    Complex: x => x.sech(),
    BigNumber: x => new _BigNumber(1).div(x.cosh())
  });
});

var name$1$ = 'sin';
var dependencies$1$ = ['typed'];
var createSin = /* #__PURE__ */factory(name$1$, dependencies$1$, _ref => {
  var {
    typed
  } = _ref;
  var trigUnit = createTrigUnit({
    typed
  });

  /**
   * Calculate the sine of a value.
   *
   * To avoid confusion with the matrix sine, this function does not apply
   * to matrices.
   *
   * Syntax:
   *
   *    math.sin(x)
   *
   * Examples:
   *
   *    math.sin(2)                      // returns number 0.9092974268256813
   *    math.sin(math.pi / 4)            // returns number 0.7071067811865475
   *    math.sin(math.unit(90, 'deg'))   // returns number 1
   *    math.sin(math.unit(30, 'deg'))   // returns number 0.5
   *
   *    const angle = 0.2
   *    math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2) // returns number ~1
   *
   * See also:
   *
   *    cos, tan
   *
   * @param {number | BigNumber | Complex | Unit} x  Function input
   * @return {number | BigNumber | Complex} Sine of x
   */
  return typed(name$1$, {
    number: Math.sin,
    'Complex | BigNumber': x => x.sin()
  }, trigUnit);
});

var name$1_ = 'sinh';
var dependencies$1_ = ['typed'];
var createSinh = /* #__PURE__ */factory(name$1_, dependencies$1_, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Calculate the hyperbolic sine of a value,
   * defined as `sinh(x) = 1/2 * (exp(x) - exp(-x))`.
   *
   * To avoid confusion with the matrix hyperbolic sine, this function does
   * not apply to matrices.
   *
   * Syntax:
   *
   *    math.sinh(x)
   *
   * Examples:
   *
   *    math.sinh(0.5)       // returns number 0.5210953054937474
   *
   * See also:
   *
   *    cosh, tanh
   *
   * @param {number | BigNumber | Complex} x  Function input
   * @return {number | BigNumber | Complex} Hyperbolic sine of x
   */
  return typed(name$1_, {
    number: sinhNumber,
    'Complex | BigNumber': x => x.sinh()
  });
});

var name$1Z = 'tan';
var dependencies$1Z = ['typed'];
var createTan = /* #__PURE__ */factory(name$1Z, dependencies$1Z, _ref => {
  var {
    typed
  } = _ref;
  var trigUnit = createTrigUnit({
    typed
  });

  /**
   * Calculate the tangent of a value. `tan(x)` is equal to `sin(x) / cos(x)`.
   *
   * To avoid confusion with the matrix tangent, this function does not apply
   * to matrices.
   *
   * Syntax:
   *
   *    math.tan(x)
   *
   * Examples:
   *
   *    math.tan(0.5)                    // returns number 0.5463024898437905
   *    math.sin(0.5) / math.cos(0.5)    // returns number 0.5463024898437905
   *    math.tan(math.pi / 4)            // returns number 1
   *    math.tan(math.unit(45, 'deg'))   // returns number 1
   *
   * See also:
   *
   *    atan, sin, cos
   *
   * @param {number | BigNumber | Complex | Unit} x  Function input
   * @return {number | BigNumber | Complex} Tangent of x
   */
  return typed(name$1Z, {
    number: Math.tan,
    'Complex | BigNumber': x => x.tan()
  }, trigUnit);
});

var name$1Y = 'tanh';
var dependencies$1Y = ['typed'];
var createTanh = /* #__PURE__ */factory(name$1Y, dependencies$1Y, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Calculate the hyperbolic tangent of a value,
   * defined as `tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1)`.
   *
   * To avoid confusion with matrix hyperbolic tangent, this function does
   * not apply to matrices.
   *
   * Syntax:
   *
   *    math.tanh(x)
   *
   * Examples:
   *
   *    // tanh(x) = sinh(x) / cosh(x) = 1 / coth(x)
   *    math.tanh(0.5)                   // returns 0.46211715726000974
   *    math.sinh(0.5) / math.cosh(0.5)  // returns 0.46211715726000974
   *    1 / math.coth(0.5)               // returns 0.46211715726000974
   *
   * See also:
   *
   *    sinh, cosh, coth
   *
   * @param {number | BigNumber | Complex} x  Function input
   * @return {number | BigNumber | Complex} Hyperbolic tangent of x
   */
  return typed('tanh', {
    number: tanh$1,
    'Complex | BigNumber': x => x.tanh()
  });
});

var name$1X = 'setCartesian';
var dependencies$1X = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix'];
var createSetCartesian = /* #__PURE__ */factory(name$1X, dependencies$1X, _ref => {
  var {
    typed,
    size,
    subset,
    compareNatural,
    Index,
    DenseMatrix
  } = _ref;
  /**
   * Create the cartesian product of two (multi)sets.
   * Multi-dimension arrays will be converted to single-dimension arrays
   * and the values will be sorted in ascending order before the operation.
   *
   * Syntax:
   *
   *    math.setCartesian(set1, set2)
   *
   * Examples:
   *
   *    math.setCartesian([1, 2], [3, 4])        // returns [[1, 3], [1, 4], [2, 3], [2, 4]]
   *    math.setCartesian([4, 3], [2, 1])        // returns [[3, 1], [3, 2], [4, 1], [4, 2]]
   *
   * See also:
   *
   *    setUnion, setIntersect, setDifference, setPowerset
   *
   * @param {Array | Matrix}    a1  A (multi)set
   * @param {Array | Matrix}    a2  A (multi)set
   * @return {Array | Matrix}    The cartesian product of two (multi)sets
   */
  return typed(name$1X, {
    'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
      var result = [];
      if (subset(size(a1), new Index(0)) !== 0 && subset(size(a2), new Index(0)) !== 0) {
        // if any of them is empty, return empty
        var b1 = flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural);
        var b2 = flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural);
        result = [];
        for (var i = 0; i < b1.length; i++) {
          for (var j = 0; j < b2.length; j++) {
            result.push([b1[i], b2[j]]);
          }
        }
      }
      // return an array, if both inputs were arrays
      if (Array.isArray(a1) && Array.isArray(a2)) {
        return result;
      }
      // return a matrix otherwise
      return new DenseMatrix(result);
    }
  });
});

var name$1W = 'setDifference';
var dependencies$1W = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix'];
var createSetDifference = /* #__PURE__ */factory(name$1W, dependencies$1W, _ref => {
  var {
    typed,
    size,
    subset,
    compareNatural,
    Index,
    DenseMatrix
  } = _ref;
  /**
   * 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.
   *
   * Syntax:
   *
   *    math.setDifference(set1, set2)
   *
   * Examples:
   *
   *    math.setDifference([1, 2, 3, 4], [3, 4, 5, 6])            // returns [1, 2]
   *    math.setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])    // returns [1, 2]
   *
   * See also:
   *
   *    setUnion, setIntersect, setSymDifference
   *
   * @param {Array | Matrix}    a1  A (multi)set
   * @param {Array | Matrix}    a2  A (multi)set
   * @return {Array | Matrix}    The difference of two (multi)sets
   */
  return typed(name$1W, {
    'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
      var result;
      if (subset(size(a1), new Index(0)) === 0) {
        // empty-anything=empty
        result = [];
      } else if (subset(size(a2), new Index(0)) === 0) {
        // anything-empty=anything
        return flatten(a1.toArray());
      } else {
        var b1 = identify(flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural));
        var b2 = identify(flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural));
        result = [];
        var inb2;
        for (var i = 0; i < b1.length; i++) {
          inb2 = false;
          for (var j = 0; j < b2.length; j++) {
            if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) {
              // the identifier is always a decimal int
              inb2 = true;
              break;
            }
          }
          if (!inb2) {
            result.push(b1[i]);
          }
        }
      }
      // return an array, if both inputs were arrays
      if (Array.isArray(a1) && Array.isArray(a2)) {
        return generalize(result);
      }
      // return a matrix otherwise
      return new DenseMatrix(generalize(result));
    }
  });
});

var name$1V = 'setDistinct';
var dependencies$1V = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix'];
var createSetDistinct = /* #__PURE__ */factory(name$1V, dependencies$1V, _ref => {
  var {
    typed,
    size,
    subset,
    compareNatural,
    Index,
    DenseMatrix
  } = _ref;
  /**
   * Collect the distinct elements of a multiset.
   * A multi-dimension array will be converted to a single-dimension array before the operation.
   *
   * Syntax:
   *
   *    math.setDistinct(set)
   *
   * Examples:
   *
   *    math.setDistinct([1, 1, 1, 2, 2, 3])        // returns [1, 2, 3]
   *
   * See also:
   *
   *    setMultiplicity
   *
   * @param {Array | Matrix}    a  A multiset
   * @return {Array | Matrix}    A set containing the distinc elements of the multiset
   */
  return typed(name$1V, {
    'Array | Matrix': function ArrayMatrix(a) {
      var result;
      if (subset(size(a), new Index(0)) === 0) {
        // if empty, return empty
        result = [];
      } else {
        var b = flatten(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
        result = [];
        result.push(b[0]);
        for (var i = 1; i < b.length; i++) {
          if (compareNatural(b[i], b[i - 1]) !== 0) {
            result.push(b[i]);
          }
        }
      }
      // return an array, if the input was an array
      if (Array.isArray(a)) {
        return result;
      }
      // return a matrix otherwise
      return new DenseMatrix(result);
    }
  });
});

var name$1U = 'setIntersect';
var dependencies$1U = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix'];
var createSetIntersect = /* #__PURE__ */factory(name$1U, dependencies$1U, _ref => {
  var {
    typed,
    size,
    subset,
    compareNatural,
    Index,
    DenseMatrix
  } = _ref;
  /**
   * Create the intersection of two (multi)sets.
   * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
   *
   * Syntax:
   *
   *    math.setIntersect(set1, set2)
   *
   * Examples:
   *
   *    math.setIntersect([1, 2, 3, 4], [3, 4, 5, 6])            // returns [3, 4]
   *    math.setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]])    // returns [3, 4]
   *
   * See also:
   *
   *    setUnion, setDifference
   *
   * @param {Array | Matrix}    a1  A (multi)set
   * @param {Array | Matrix}    a2  A (multi)set
   * @return {Array | Matrix}    The intersection of two (multi)sets
   */
  return typed(name$1U, {
    'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
      var result;
      if (subset(size(a1), new Index(0)) === 0 || subset(size(a2), new Index(0)) === 0) {
        // of any of them is empty, return empty
        result = [];
      } else {
        var b1 = identify(flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural));
        var b2 = identify(flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural));
        result = [];
        for (var i = 0; i < b1.length; i++) {
          for (var j = 0; j < b2.length; j++) {
            if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) {
              // the identifier is always a decimal int
              result.push(b1[i]);
              break;
            }
          }
        }
      }
      // return an array, if both inputs were arrays
      if (Array.isArray(a1) && Array.isArray(a2)) {
        return generalize(result);
      }
      // return a matrix otherwise
      return new DenseMatrix(generalize(result));
    }
  });
});

var name$1T = 'setIsSubset';
var dependencies$1T = ['typed', 'size', 'subset', 'compareNatural', 'Index'];
var createSetIsSubset = /* #__PURE__ */factory(name$1T, dependencies$1T, _ref => {
  var {
    typed,
    size,
    subset,
    compareNatural,
    Index
  } = _ref;
  /**
   * 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.
   *
   * Syntax:
   *
   *    math.setIsSubset(set1, set2)
   *
   * Examples:
   *
   *    math.setIsSubset([1, 2], [3, 4, 5, 6])        // returns false
   *    math.setIsSubset([3, 4], [3, 4, 5, 6])        // returns true
   *
   * See also:
   *
   *    setUnion, setIntersect, setDifference
   *
   * @param {Array | Matrix}    a1  A (multi)set
   * @param {Array | Matrix}    a2  A (multi)set
   * @return {boolean} Returns true when a1 is a subset of a2, returns false otherwise
   */
  return typed(name$1T, {
    'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
      if (subset(size(a1), new Index(0)) === 0) {
        // empty is a subset of anything
        return true;
      } else if (subset(size(a2), new Index(0)) === 0) {
        // anything is not a subset of empty
        return false;
      }
      var b1 = identify(flatten(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural));
      var b2 = identify(flatten(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural));
      var inb2;
      for (var i = 0; i < b1.length; i++) {
        inb2 = false;
        for (var j = 0; j < b2.length; j++) {
          if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) {
            // the identifier is always a decimal int
            inb2 = true;
            break;
          }
        }
        if (inb2 === false) {
          return false;
        }
      }
      return true;
    }
  });
});

var name$1S = 'setMultiplicity';
var dependencies$1S = ['typed', 'size', 'subset', 'compareNatural', 'Index'];
var createSetMultiplicity = /* #__PURE__ */factory(name$1S, dependencies$1S, _ref => {
  var {
    typed,
    size,
    subset,
    compareNatural,
    Index
  } = _ref;
  /**
   * Count the multiplicity of an element in a multiset.
   * A multi-dimension array will be converted to a single-dimension array before the operation.
   *
   * Syntax:
   *
   *    math.setMultiplicity(element, set)
   *
   * Examples:
   *
   *    math.setMultiplicity(1, [1, 2, 2, 4])    // returns 1
   *    math.setMultiplicity(2, [1, 2, 2, 4])    // returns 2
   *
   * See also:
   *
   *    setDistinct, setSize
   *
   * @param {number | BigNumber | Fraction | Complex} e  An element in the multiset
   * @param {Array | Matrix}     a  A multiset
   * @return {number}            The number of how many times the multiset contains the element
   */
  return typed(name$1S, {
    'number | BigNumber | Fraction | Complex, Array | Matrix': function numberBigNumberFractionComplexArrayMatrix(e, a) {
      if (subset(size(a), new Index(0)) === 0) {
        // if empty, return 0
        return 0;
      }
      var b = flatten(Array.isArray(a) ? a : a.toArray());
      var count = 0;
      for (var i = 0; i < b.length; i++) {
        if (compareNatural(b[i], e) === 0) {
          count++;
        }
      }
      return count;
    }
  });
});

var name$1R = 'setPowerset';
var dependencies$1R = ['typed', 'size', 'subset', 'compareNatural', 'Index'];
var createSetPowerset = /* #__PURE__ */factory(name$1R, dependencies$1R, _ref => {
  var {
    typed,
    size,
    subset,
    compareNatural,
    Index
  } = _ref;
  /**
   * 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.
   *
   * Syntax:
   *
   *    math.setPowerset(set)
   *
   * Examples:
   *
   *    math.setPowerset([1, 2, 3])        // returns [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
   *
   * See also:
   *
   *    setCartesian
   *
   * @param {Array | Matrix}    a  A (multi)set
   * @return {Array}    The powerset of the (multi)set
   */
  return typed(name$1R, {
    'Array | Matrix': function ArrayMatrix(a) {
      if (subset(size(a), new Index(0)) === 0) {
        // if empty, return empty
        return [];
      }
      var b = flatten(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
      var result = [];
      var number = 0;
      while (number.toString(2).length <= b.length) {
        result.push(_subset(b, number.toString(2).split('').reverse()));
        number++;
      }
      // can not return a matrix, because of the different size of the subarrays
      return _sort(result);
    }
  });

  // create subset
  function _subset(array, bitarray) {
    var result = [];
    for (var i = 0; i < bitarray.length; i++) {
      if (bitarray[i] === '1') {
        result.push(array[i]);
      }
    }
    return result;
  }

  // sort subsests by length
  function _sort(array) {
    var temp = [];
    for (var i = array.length - 1; i > 0; i--) {
      for (var j = 0; j < i; j++) {
        if (array[j].length > array[j + 1].length) {
          temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
        }
      }
    }
    return array;
  }
});

var name$1Q = 'setSize';
var dependencies$1Q = ['typed', 'compareNatural'];
var createSetSize = /* #__PURE__ */factory(name$1Q, dependencies$1Q, _ref => {
  var {
    typed,
    compareNatural
  } = _ref;
  /**
   * Count the number of elements of a (multi)set. When a second parameter is 'true', count only the unique values.
   * A multi-dimension array will be converted to a single-dimension array before the operation.
   *
   * Syntax:
   *
   *    math.setSize(set)
   *    math.setSize(set, unique)
   *
   * Examples:
   *
   *    math.setSize([1, 2, 2, 4])          // returns 4
   *    math.setSize([1, 2, 2, 4], true)    // returns 3
   *
   * See also:
   *
   *    setUnion, setIntersect, setDifference
   *
   * @param {Array | Matrix} a  A multiset
   * @param {boolean} [unique]  If true, only the unique values are counted. False by default
   * @return {number}           The number of elements of the (multi)set
   */
  return typed(name$1Q, {
    'Array | Matrix': function ArrayMatrix(a) {
      return Array.isArray(a) ? flatten(a).length : flatten(a.toArray()).length;
    },
    'Array | Matrix, boolean': function ArrayMatrixBoolean(a, unique) {
      if (unique === false || a.length === 0) {
        return Array.isArray(a) ? flatten(a).length : flatten(a.toArray()).length;
      } else {
        var b = flatten(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
        var count = 1;
        for (var i = 1; i < b.length; i++) {
          if (compareNatural(b[i], b[i - 1]) !== 0) {
            count++;
          }
        }
        return count;
      }
    }
  });
});

var name$1P = 'setSymDifference';
var dependencies$1P = ['typed', 'size', 'concat', 'subset', 'setDifference', 'Index'];
var createSetSymDifference = /* #__PURE__ */factory(name$1P, dependencies$1P, _ref => {
  var {
    typed,
    size,
    concat,
    subset,
    setDifference,
    Index
  } = _ref;
  /**
   * Create the symmetric difference of two (multi)sets.
   * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
   *
   * Syntax:
   *
   *    math.setSymDifference(set1, set2)
   *
   * Examples:
   *
   *    math.setSymDifference([1, 2, 3, 4], [3, 4, 5, 6])            // returns [1, 2, 5, 6]
   *    math.setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])    // returns [1, 2, 5, 6]
   *
   * See also:
   *
   *    setUnion, setIntersect, setDifference
   *
   * @param {Array | Matrix}    a1  A (multi)set
   * @param {Array | Matrix}    a2  A (multi)set
   * @return {Array | Matrix}    The symmetric difference of two (multi)sets
   */
  return typed(name$1P, {
    'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
      if (subset(size(a1), new Index(0)) === 0) {
        // if any of them is empty, return the other one
        return flatten(a2);
      } else if (subset(size(a2), new Index(0)) === 0) {
        return flatten(a1);
      }
      var b1 = flatten(a1);
      var b2 = flatten(a2);
      return concat(setDifference(b1, b2), setDifference(b2, b1));
    }
  });
});

var name$1O = 'setUnion';
var dependencies$1O = ['typed', 'size', 'concat', 'subset', 'setIntersect', 'setSymDifference', 'Index'];
var createSetUnion = /* #__PURE__ */factory(name$1O, dependencies$1O, _ref => {
  var {
    typed,
    size,
    concat,
    subset,
    setIntersect,
    setSymDifference,
    Index
  } = _ref;
  /**
   * Create the union of two (multi)sets.
   * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
   *
   * Syntax:
   *
   *    math.setUnion(set1, set2)
   *
   * Examples:
   *
   *    math.setUnion([1, 2, 3, 4], [3, 4, 5, 6])            // returns [1, 2, 3, 4, 5, 6]
   *    math.setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]])    // returns [1, 2, 3, 4, 5, 6]
   *
   * See also:
   *
   *    setIntersect, setDifference
   *
   * @param {Array | Matrix}    a1  A (multi)set
   * @param {Array | Matrix}    a2  A (multi)set
   * @return {Array | Matrix}    The union of two (multi)sets
   */
  return typed(name$1O, {
    'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
      if (subset(size(a1), new Index(0)) === 0) {
        // if any of them is empty, return the other one
        return flatten(a2);
      } else if (subset(size(a2), new Index(0)) === 0) {
        return flatten(a1);
      }
      var b1 = flatten(a1);
      var b2 = flatten(a2);
      return concat(setSymDifference(b1, b2), setIntersect(b1, b2));
    }
  });
});

var name$1N = 'add';
var dependencies$1N = ['typed', 'matrix', 'addScalar', 'equalScalar', 'DenseMatrix', 'SparseMatrix', 'concat'];
var createAdd = /* #__PURE__ */factory(name$1N, dependencies$1N, _ref => {
  var {
    typed,
    matrix,
    addScalar,
    equalScalar,
    DenseMatrix,
    SparseMatrix,
    concat
  } = _ref;
  var matAlgo01xDSid = createMatAlgo01xDSid({
    typed
  });
  var matAlgo04xSidSid = createMatAlgo04xSidSid({
    typed,
    equalScalar
  });
  var matAlgo10xSids = createMatAlgo10xSids({
    typed,
    DenseMatrix
  });
  var matrixAlgorithmSuite = createMatrixAlgorithmSuite({
    typed,
    matrix,
    concat
  });
  /**
  * Add two or more values, `x + y`.
  * For matrices, the function is evaluated element wise.
  *
  * Syntax:
  *
  *    math.add(x, y)
  *    math.add(x, y, z, ...)
  *
  * Examples:
  *
  *    math.add(2, 3)               // returns number 5
  *    math.add(2, 3, 4)            // returns number 9
  *
  *    const a = math.complex(2, 3)
  *    const b = math.complex(-4, 1)
  *    math.add(a, b)               // returns Complex -2 + 4i
  *
  *    math.add([1, 2, 3], 4)       // returns Array [5, 6, 7]
  *
  *    const c = math.unit('5 cm')
  *    const d = math.unit('2.1 mm')
  *    math.add(c, d)               // returns Unit 52.1 mm
  *
  *    math.add("2.3", "4")         // returns number 6.3
  *
  * See also:
  *
  *    subtract, sum
  *
  * @param  {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} x First value to add
  * @param  {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} y Second value to add
  * @return {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} Sum of `x` and `y`
  */
  return typed(name$1N, {
    'any, any': addScalar,
    'any, any, ...any': typed.referToSelf(self => (x, y, rest) => {
      var result = self(x, y);
      for (var i = 0; i < rest.length; i++) {
        result = self(result, rest[i]);
      }
      return result;
    })
  }, matrixAlgorithmSuite({
    elop: addScalar,
    DS: matAlgo01xDSid,
    SS: matAlgo04xSidSid,
    Ss: matAlgo10xSids
  }));
});

var name$1M = 'hypot';
var dependencies$1M = ['typed', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'sqrt', 'smaller', 'isPositive'];
var createHypot = /* #__PURE__ */factory(name$1M, dependencies$1M, _ref => {
  var {
    typed,
    abs,
    addScalar,
    divideScalar,
    multiplyScalar,
    sqrt,
    smaller,
    isPositive
  } = _ref;
  /**
   * Calculate the hypotenusa of a list with values. The hypotenusa is defined as:
   *
   *     hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...)
   *
   * For matrix input, the hypotenusa is calculated for all values in the matrix.
   *
   * Syntax:
   *
   *     math.hypot(a, b, ...)
   *     math.hypot([a, b, c, ...])
   *
   * Examples:
   *
   *     math.hypot(3, 4)      // 5
   *     math.hypot(3, 4, 5)   // 7.0710678118654755
   *     math.hypot([3, 4, 5]) // 7.0710678118654755
   *     math.hypot(-2)        // 2
   *
   * See also:
   *
   *     abs, norm
   *
   * @param {... number | BigNumber | Array | Matrix} args    A list with numeric values or an Array or Matrix.
   *                                                          Matrix and Array input is flattened and returns a
   *                                                          single number for the whole matrix.
   * @return {number | BigNumber} Returns the hypothenusa of the input values.
   */
  return typed(name$1M, {
    '... number | BigNumber': _hypot,
    Array: _hypot,
    Matrix: M => _hypot(flatten(M.toArray()))
  });

  /**
   * Calculate the hypotenusa for an Array with values
   * @param {Array.<number | BigNumber>} args
   * @return {number | BigNumber} Returns the result
   * @private
   */
  function _hypot(args) {
    // code based on `hypot` from es6-shim:
    // https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1619-L1633
    var result = 0;
    var largest = 0;
    for (var i = 0; i < args.length; i++) {
      if (isComplex(args[i])) {
        throw new TypeError('Unexpected type of argument to hypot');
      }
      var value = abs(args[i]);
      if (smaller(largest, value)) {
        result = multiplyScalar(result, multiplyScalar(divideScalar(largest, value), divideScalar(largest, value)));
        result = addScalar(result, 1);
        largest = value;
      } else {
        result = addScalar(result, isPositive(value) ? multiplyScalar(divideScalar(value, largest), divideScalar(value, largest)) : value);
      }
    }
    return multiplyScalar(largest, sqrt(result));
  }
});

var name$1L = 'norm';
var dependencies$1L = ['typed', 'abs', 'add', 'pow', 'conj', 'sqrt', 'multiply', 'equalScalar', 'larger', 'smaller', 'matrix', 'ctranspose', 'eigs'];
var createNorm = /* #__PURE__ */factory(name$1L, dependencies$1L, _ref => {
  var {
    typed,
    abs,
    add,
    pow,
    conj,
    sqrt,
    multiply,
    equalScalar,
    larger,
    smaller,
    matrix,
    ctranspose,
    eigs
  } = _ref;
  /**
   * Calculate the norm of a number, vector or matrix.
   *
   * The second parameter p is optional. If not provided, it defaults to 2.
   *
   * Syntax:
   *
   *    math.norm(x)
   *    math.norm(x, p)
   *
   * Examples:
   *
   *    math.abs(-3.5)                         // returns 3.5
   *    math.norm(-3.5)                        // returns 3.5
   *
   *    math.norm(math.complex(3, -4))         // returns 5
   *
   *    math.norm([1, 2, -3], Infinity)        // returns 3
   *    math.norm([1, 2, -3], -Infinity)       // returns 1
   *
   *    math.norm([3, 4], 2)                   // returns 5
   *
   *    math.norm([[1, 2], [3, 4]], 1)          // returns 6
   *    math.norm([[1, 2], [3, 4]], 'inf')     // returns 7
   *    math.norm([[1, 2], [3, 4]], 'fro')     // returns 5.477225575051661
   *
   * See also:
   *
   *    abs, hypot
   *
   * @param  {number | BigNumber | Complex | Array | Matrix} x
   *            Value for which to calculate the norm
   * @param  {number | BigNumber | string} [p=2]
   *            Vector space.
   *            Supported numbers include Infinity and -Infinity.
   *            Supported strings are: 'inf', '-inf', and 'fro' (The Frobenius norm)
   * @return {number | BigNumber} the p-norm
   */
  return typed(name$1L, {
    number: Math.abs,
    Complex: function Complex(x) {
      return x.abs();
    },
    BigNumber: function BigNumber(x) {
      // norm(x) = abs(x)
      return x.abs();
    },
    boolean: function boolean(x) {
      // norm(x) = abs(x)
      return Math.abs(x);
    },
    Array: function Array(x) {
      return _norm(matrix(x), 2);
    },
    Matrix: function Matrix(x) {
      return _norm(x, 2);
    },
    'Array, number | BigNumber | string': function ArrayNumberBigNumberString(x, p) {
      return _norm(matrix(x), p);
    },
    'Matrix, number | BigNumber | string': function MatrixNumberBigNumberString(x, p) {
      return _norm(x, p);
    }
  });

  /**
   * Calculate the plus infinity norm for a vector
   * @param {Matrix} x
   * @returns {number} Returns the norm
   * @private
   */
  function _vectorNormPlusInfinity(x) {
    // norm(x, Infinity) = max(abs(x))
    var pinf = 0;
    // skip zeros since abs(0) === 0
    x.forEach(function (value) {
      var v = abs(value);
      if (larger(v, pinf)) {
        pinf = v;
      }
    }, true);
    return pinf;
  }

  /**
   * Calculate the minus infinity norm for a vector
   * @param {Matrix} x
   * @returns {number} Returns the norm
   * @private
   */
  function _vectorNormMinusInfinity(x) {
    // norm(x, -Infinity) = min(abs(x))
    var ninf;
    // skip zeros since abs(0) === 0
    x.forEach(function (value) {
      var v = abs(value);
      if (!ninf || smaller(v, ninf)) {
        ninf = v;
      }
    }, true);
    return ninf || 0;
  }

  /**
   * Calculate the norm for a vector
   * @param {Matrix} x
   * @param {number | string} p
   * @returns {number} Returns the norm
   * @private
   */
  function _vectorNorm(x, p) {
    // check p
    if (p === Number.POSITIVE_INFINITY || p === 'inf') {
      return _vectorNormPlusInfinity(x);
    }
    if (p === Number.NEGATIVE_INFINITY || p === '-inf') {
      return _vectorNormMinusInfinity(x);
    }
    if (p === 'fro') {
      return _norm(x, 2);
    }
    if (typeof p === 'number' && !isNaN(p)) {
      // check p != 0
      if (!equalScalar(p, 0)) {
        // norm(x, p) = sum(abs(xi) ^ p) ^ 1/p
        var n = 0;
        // skip zeros since abs(0) === 0
        x.forEach(function (value) {
          n = add(pow(abs(value), p), n);
        }, true);
        return pow(n, 1 / p);
      }
      return Number.POSITIVE_INFINITY;
    }
    // invalid parameter value
    throw new Error('Unsupported parameter value');
  }

  /**
   * Calculate the Frobenius norm for a matrix
   * @param {Matrix} x
   * @returns {number} Returns the norm
   * @private
   */
  function _matrixNormFrobenius(x) {
    // norm(x) = sqrt(sum(diag(x'x)))
    var fro = 0;
    x.forEach(function (value, index) {
      fro = add(fro, multiply(value, conj(value)));
    });
    return abs(sqrt(fro));
  }

  /**
   * Calculate the norm L1 for a matrix
   * @param {Matrix} x
   * @returns {number} Returns the norm
   * @private
   */
  function _matrixNormOne(x) {
    // norm(x) = the largest column sum
    var c = [];
    // result
    var maxc = 0;
    // skip zeros since abs(0) == 0
    x.forEach(function (value, index) {
      var j = index[1];
      var cj = add(c[j] || 0, abs(value));
      if (larger(cj, maxc)) {
        maxc = cj;
      }
      c[j] = cj;
    }, true);
    return maxc;
  }

  /**
   * Calculate the norm L2 for a matrix
   * @param {Matrix} x
   * @returns {number} Returns the norm
   * @private
   */
  function _matrixNormTwo(x) {
    // norm(x) = sqrt( max eigenvalue of A*.A)
    var sizeX = x.size();
    if (sizeX[0] !== sizeX[1]) {
      throw new RangeError('Invalid matrix dimensions');
    }
    var tx = ctranspose(x);
    var squaredX = multiply(tx, x);
    var eigenVals = eigs(squaredX).values.toArray();
    var rho = eigenVals[eigenVals.length - 1];
    return abs(sqrt(rho));
  }

  /**
   * Calculate the infinity norm for a matrix
   * @param {Matrix} x
   * @returns {number} Returns the norm
   * @private
   */
  function _matrixNormInfinity(x) {
    // norm(x) = the largest row sum
    var r = [];
    // result
    var maxr = 0;
    // skip zeros since abs(0) == 0
    x.forEach(function (value, index) {
      var i = index[0];
      var ri = add(r[i] || 0, abs(value));
      if (larger(ri, maxr)) {
        maxr = ri;
      }
      r[i] = ri;
    }, true);
    return maxr;
  }

  /**
   * Calculate the norm for a 2D Matrix (M*N)
   * @param {Matrix} x
   * @param {number | string} p
   * @returns {number} Returns the norm
   * @private
   */
  function _matrixNorm(x, p) {
    // check p
    if (p === 1) {
      return _matrixNormOne(x);
    }
    if (p === Number.POSITIVE_INFINITY || p === 'inf') {
      return _matrixNormInfinity(x);
    }
    if (p === 'fro') {
      return _matrixNormFrobenius(x);
    }
    if (p === 2) {
      return _matrixNormTwo(x);
    } // invalid parameter value

    throw new Error('Unsupported parameter value ' + p);
  }

  /**
   * Calculate the norm for an array
   * @param {Matrix} x
   * @param {number | string} p
   * @returns {number} Returns the norm
   * @private
   */
  function _norm(x, p) {
    // size
    var sizeX = x.size();

    // check if it is a vector
    if (sizeX.length === 1) {
      return _vectorNorm(x, p);
    }
    // MxN matrix
    if (sizeX.length === 2) {
      if (sizeX[0] && sizeX[1]) {
        return _matrixNorm(x, p);
      } else {
        throw new RangeError('Invalid matrix dimensions');
      }
    }
  }
});

var name$1K = 'dot';
var dependencies$1K = ['typed', 'addScalar', 'multiplyScalar', 'conj', 'size'];
var createDot = /* #__PURE__ */factory(name$1K, dependencies$1K, _ref => {
  var {
    typed,
    addScalar,
    multiplyScalar,
    conj,
    size
  } = _ref;
  /**
   * Calculate the dot product of two vectors. The dot product of
   * `A = [a1, a2, ..., an]` and `B = [b1, b2, ..., bn]` is defined as:
   *
   *    dot(A, B) = conj(a1) * b1 + conj(a2) * b2 + ... + conj(an) * bn
   *
   * Syntax:
   *
   *    math.dot(x, y)
   *
   * Examples:
   *
   *    math.dot([2, 4, 1], [2, 2, 3])       // returns number 15
   *    math.multiply([2, 4, 1], [2, 2, 3])  // returns number 15
   *
   * See also:
   *
   *    multiply, cross
   *
   * @param  {Array | Matrix} x     First vector
   * @param  {Array | Matrix} y     Second vector
   * @return {number}               Returns the dot product of `x` and `y`
   */
  return typed(name$1K, {
    'Array | DenseMatrix, Array | DenseMatrix': _denseDot,
    'SparseMatrix, SparseMatrix': _sparseDot
  });
  function _validateDim(x, y) {
    var xSize = _size(x);
    var ySize = _size(y);
    var xLen, yLen;
    if (xSize.length === 1) {
      xLen = xSize[0];
    } else if (xSize.length === 2 && xSize[1] === 1) {
      xLen = xSize[0];
    } else {
      throw new RangeError('Expected a column vector, instead got a matrix of size (' + xSize.join(', ') + ')');
    }
    if (ySize.length === 1) {
      yLen = ySize[0];
    } else if (ySize.length === 2 && ySize[1] === 1) {
      yLen = ySize[0];
    } else {
      throw new RangeError('Expected a column vector, instead got a matrix of size (' + ySize.join(', ') + ')');
    }
    if (xLen !== yLen) throw new RangeError('Vectors must have equal length (' + xLen + ' != ' + yLen + ')');
    if (xLen === 0) throw new RangeError('Cannot calculate the dot product of empty vectors');
    return xLen;
  }
  function _denseDot(a, b) {
    var N = _validateDim(a, b);
    var adata = isMatrix(a) ? a._data : a;
    var adt = isMatrix(a) ? a._datatype || a.getDataType() : undefined;
    var bdata = isMatrix(b) ? b._data : b;
    var bdt = isMatrix(b) ? b._datatype || b.getDataType() : undefined;

    // are these 2-dimensional column vectors? (as opposed to 1-dimensional vectors)
    var aIsColumn = _size(a).length === 2;
    var bIsColumn = _size(b).length === 2;
    var add = addScalar;
    var mul = multiplyScalar;

    // process data types
    if (adt && bdt && adt === bdt && typeof adt === 'string' && adt !== 'mixed') {
      var dt = adt;
      // find signatures that matches (dt, dt)
      add = typed.find(addScalar, [dt, dt]);
      mul = typed.find(multiplyScalar, [dt, dt]);
    }

    // both vectors 1-dimensional
    if (!aIsColumn && !bIsColumn) {
      var c = mul(conj(adata[0]), bdata[0]);
      for (var i = 1; i < N; i++) {
        c = add(c, mul(conj(adata[i]), bdata[i]));
      }
      return c;
    }

    // a is 1-dim, b is column
    if (!aIsColumn && bIsColumn) {
      var _c = mul(conj(adata[0]), bdata[0][0]);
      for (var _i = 1; _i < N; _i++) {
        _c = add(_c, mul(conj(adata[_i]), bdata[_i][0]));
      }
      return _c;
    }

    // a is column, b is 1-dim
    if (aIsColumn && !bIsColumn) {
      var _c2 = mul(conj(adata[0][0]), bdata[0]);
      for (var _i2 = 1; _i2 < N; _i2++) {
        _c2 = add(_c2, mul(conj(adata[_i2][0]), bdata[_i2]));
      }
      return _c2;
    }

    // both vectors are column
    if (aIsColumn && bIsColumn) {
      var _c3 = mul(conj(adata[0][0]), bdata[0][0]);
      for (var _i3 = 1; _i3 < N; _i3++) {
        _c3 = add(_c3, mul(conj(adata[_i3][0]), bdata[_i3][0]));
      }
      return _c3;
    }
  }
  function _sparseDot(x, y) {
    _validateDim(x, y);
    var xindex = x._index;
    var xvalues = x._values;
    var yindex = y._index;
    var yvalues = y._values;

    // TODO optimize add & mul using datatype
    var c = 0;
    var add = addScalar;
    var mul = multiplyScalar;
    var i = 0;
    var j = 0;
    while (i < xindex.length && j < yindex.length) {
      var I = xindex[i];
      var J = yindex[j];
      if (I < J) {
        i++;
        continue;
      }
      if (I > J) {
        j++;
        continue;
      }
      if (I === J) {
        c = add(c, mul(xvalues[i], yvalues[j]));
        i++;
        j++;
      }
    }
    return c;
  }

  // TODO remove this once #1771 is fixed
  function _size(x) {
    return isMatrix(x) ? x.size() : size(x);
  }
});

var name$1J = 'trace';
var dependencies$1J = ['typed', 'matrix', 'add'];
var createTrace = /* #__PURE__ */factory(name$1J, dependencies$1J, _ref => {
  var {
    typed,
    matrix,
    add
  } = _ref;
  /**
   * Calculate the trace of a matrix: the sum of the elements on the main
   * diagonal of a square matrix.
   *
   * Syntax:
   *
   *    math.trace(x)
   *
   * Examples:
   *
   *    math.trace([[1, 2], [3, 4]]) // returns 5
   *
   *    const A = [
   *      [1, 2, 3],
   *      [-1, 2, 3],
   *      [2, 0, 3]
   *    ]
   *    math.trace(A) // returns 6
   *
   * See also:
   *
   *    diag
   *
   * @param {Array | Matrix} x  A matrix
   *
   * @return {number} The trace of `x`
   */
  return typed('trace', {
    Array: function _arrayTrace(x) {
      // use dense matrix implementation
      return _denseTrace(matrix(x));
    },
    SparseMatrix: _sparseTrace,
    DenseMatrix: _denseTrace,
    any: clone$2
  });
  function _denseTrace(m) {
    // matrix size & data
    var size = m._size;
    var data = m._data;

    // process dimensions
    switch (size.length) {
      case 1:
        // vector
        if (size[0] === 1) {
          // return data[0]
          return clone$2(data[0]);
        }
        throw new RangeError('Matrix must be square (size: ' + format(size) + ')');
      case 2:
        {
          // two dimensional
          var rows = size[0];
          var cols = size[1];
          if (rows === cols) {
            // calulate sum
            var sum = 0;
            // loop diagonal
            for (var i = 0; i < rows; i++) {
              sum = add(sum, data[i][i]);
            }
            // return trace
            return sum;
          } else {
            throw new RangeError('Matrix must be square (size: ' + format(size) + ')');
          }
        }
      default:
        // multi dimensional
        throw new RangeError('Matrix must be two dimensional (size: ' + format(size) + ')');
    }
  }
  function _sparseTrace(m) {
    // matrix arrays
    var values = m._values;
    var index = m._index;
    var ptr = m._ptr;
    var size = m._size;
    // check dimensions
    var rows = size[0];
    var columns = size[1];
    // matrix must be square
    if (rows === columns) {
      // calulate sum
      var sum = 0;
      // check we have data (avoid looping columns)
      if (values.length > 0) {
        // loop columns
        for (var j = 0; j < columns; j++) {
          // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
          var k0 = ptr[j];
          var k1 = ptr[j + 1];
          // loop k within [k0, k1[
          for (var k = k0; k < k1; k++) {
            // row index
            var i = index[k];
            // check row
            if (i === j) {
              // accumulate value
              sum = add(sum, values[k]);
              // exit loop
              break;
            }
            if (i > j) {
              // exit loop, no value on the diagonal for column j
              break;
            }
          }
        }
      }
      // return trace
      return sum;
    }
    throw new RangeError('Matrix must be square (size: ' + format(size) + ')');
  }
});

var name$1I = 'index';
var dependencies$1I = ['typed', 'Index'];
var createIndex = /* #__PURE__ */factory(name$1I, dependencies$1I, _ref => {
  var {
    typed,
    Index
  } = _ref;
  /**
   * Create an index. An Index can store ranges having start, step, and end
   * for multiple dimensions.
   * Matrix.get, Matrix.set, and math.subset accept an Index as input.
   *
   * Syntax:
   *
   *     math.index(range1, range2, ...)
   *
   * Where each range can be any of:
   *
   * - A number
   * - A string for getting/setting an object property
   * - An instance of `Range`
   * - A one-dimensional Array or a Matrix with numbers or booleans
   *
   * Indexes must be zero-based, integer numbers.
   *
   * Examples:
   *
   *    const b = [1, 2, 3, 4, 5]
   *    math.subset(b, math.index([1, 2, 3]))                         // returns [2, 3, 4]
   *    math.subset(b, math.index([false, true, true, true, false]))  // returns [2, 3, 4]
   *
   *    const a = math.matrix([[1, 2], [3, 4]])
   *    a.subset(math.index(0, 1))             // returns 2
   *    a.subset(math.index(0, [false, true])) // returns 2
   *
   * See also:
   *
   *    bignumber, boolean, complex, matrix, number, string, unit
   *
   * @param {...*} ranges   Zero or more ranges or numbers.
   * @return {Index}        Returns the created index
   */
  return typed(name$1I, {
    '...number | string | BigNumber | Range | Array | Matrix': function numberStringBigNumberRangeArrayMatrix(args) {
      var ranges = args.map(function (arg) {
        if (isBigNumber(arg)) {
          return arg.toNumber(); // convert BigNumber to Number
        } else if (isArray(arg) || isMatrix(arg)) {
          return arg.map(function (elem) {
            // convert BigNumber to Number
            return isBigNumber(elem) ? elem.toNumber() : elem;
          });
        } else {
          return arg;
        }
      });
      var res = new Index();
      Index.apply(res, ranges);
      return res;
    }
  });
});

// Reserved keywords not allowed to use in the parser
var keywords = new Set(['end']);

var name$1H = 'Node';
var dependencies$1H = ['mathWithTransform'];
var createNode = /* #__PURE__ */factory(name$1H, dependencies$1H, _ref => {
  var {
    mathWithTransform
  } = _ref;
  /**
   * Validate the symbol names of a scope.
   * Throws an error when the scope contains an illegal symbol.
   * @param {Object} scope
   */
  function _validateScope(scope) {
    for (var symbol of [...keywords]) {
      if (scope.has(symbol)) {
        throw new Error('Scope contains an illegal symbol, "' + symbol + '" is a reserved keyword');
      }
    }
  }
  class Node {
    get type() {
      return 'Node';
    }
    get isNode() {
      return true;
    }

    /**
     * Evaluate the node
     * @param {Object} [scope]  Scope to read/write variables
     * @return {*}              Returns the result
     */
    evaluate(scope) {
      return this.compile().evaluate(scope);
    }

    /**
     * Compile the node into an optimized, evauatable JavaScript function
     * @return {{evaluate: function([Object])}} object
     *                Returns an object with a function 'evaluate',
     *                which can be invoked as expr.evaluate([scope: Object]),
     *                where scope is an optional object with
     *                variables.
     */
    compile() {
      var expr = this._compile(mathWithTransform, {});
      var args = {};
      var context = null;
      function evaluate(scope) {
        var s = createMap$1(scope);
        _validateScope(s);
        return expr(s, args, context);
      }
      return {
        evaluate
      };
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      throw new Error('Method _compile must be implemented by type ' + this.type);
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      // must be implemented by each of the Node implementations
      throw new Error('Cannot run forEach on a Node interface');
    }

    /**
     * Create a new Node whose children are the results of calling the
     * provided callback function for each child of the original node.
     * @param {function(child: Node, path: string, parent: Node): Node} callback
     * @returns {OperatorNode} Returns a transformed copy of the node
     */
    map(callback) {
      // must be implemented by each of the Node implementations
      throw new Error('Cannot run map on a Node interface');
    }

    /**
     * Validate whether an object is a Node, for use with map
     * @param {Node} node
     * @returns {Node} Returns the input if it's a node, else throws an Error
     * @protected
     */
    _ifNode(node) {
      if (!isNode(node)) {
        throw new TypeError('Callback function must return a Node');
      }
      return node;
    }

    /**
     * Recursively traverse all nodes in a node tree. Executes given callback for
     * this node and each of its child nodes.
     * @param {function(node: Node, path: string, parent: Node)} callback
     *          A callback called for every node in the node tree.
     */
    traverse(callback) {
      // execute callback for itself
      // eslint-disable-next-line
      callback(this, null, null);

      // recursively traverse over all children of a node
      function _traverse(node, callback) {
        node.forEach(function (child, path, parent) {
          callback(child, path, parent);
          _traverse(child, callback);
        });
      }
      _traverse(this, callback);
    }

    /**
     * Recursively transform a node tree via a transform function.
     *
     * For example, to replace all nodes of type SymbolNode having name 'x' with
     * a ConstantNode with value 2:
     *
     *     const res = Node.transform(function (node, path, parent) {
     *       if (node && node.isSymbolNode) && (node.name === 'x')) {
     *         return new ConstantNode(2)
     *       }
     *       else {
     *         return node
     *       }
     *     })
     *
     * @param {function(node: Node, path: string, parent: Node) : Node} callback
     *          A mapping function accepting a node, and returning
     *          a replacement for the node or the original node. The "signature"
     *          of the callback must be:
     *          callback(node: Node, index: string, parent: Node) : Node
     * @return {Node} Returns the original node or its replacement
     */
    transform(callback) {
      function _transform(child, path, parent) {
        var replacement = callback(child, path, parent);
        if (replacement !== child) {
          // stop iterating when the node is replaced
          return replacement;
        }
        return child.map(_transform);
      }
      return _transform(this, null, null);
    }

    /**
     * Find any node in the node tree matching given filter function. For
     * example, to find all nodes of type SymbolNode having name 'x':
     *
     *     const results = Node.filter(function (node) {
     *       return (node && node.isSymbolNode) && (node.name === 'x')
     *     })
     *
     * @param {function(node: Node, path: string, parent: Node) : Node} callback
     *            A test function returning true when a node matches, and false
     *            otherwise. Function signature:
     *            callback(node: Node, index: string, parent: Node) : boolean
     * @return {Node[]} nodes
     *            An array with nodes matching given filter criteria
     */
    filter(callback) {
      var nodes = [];
      this.traverse(function (node, path, parent) {
        if (callback(node, path, parent)) {
          nodes.push(node);
        }
      });
      return nodes;
    }

    /**
     * Create a shallow clone of this node
     * @return {Node}
     */
    clone() {
      // must be implemented by each of the Node implementations
      throw new Error('Cannot clone a Node interface');
    }

    /**
     * Create a deep clone of this node
     * @return {Node}
     */
    cloneDeep() {
      return this.map(function (node) {
        return node.cloneDeep();
      });
    }

    /**
     * Deep compare this node with another node.
     * @param {Node} other
     * @return {boolean} Returns true when both nodes are of the same type and
     *                   contain the same values (as do their childs)
     */
    equals(other) {
      return other ? this.type === other.type && deepStrictEqual(this, other) : false;
    }

    /**
     * Get string representation. (wrapper function)
     *
     * This function can get an object of the following form:
     * {
     *    handler: //This can be a callback function of the form
     *             // "function callback(node, options)"or
     *             // a map that maps function names (used in FunctionNodes)
     *             // to callbacks
     *    parenthesis: "keep" //the parenthesis option (This is optional)
     * }
     *
     * @param {Object} [options]
     * @return {string}
     */
    toString(options) {
      var customString = this._getCustomString(options);
      if (typeof customString !== 'undefined') {
        return customString;
      }
      return this._toString(options);
    }

    /**
     * Internal function to generate the string output.
     * This has to be implemented by every Node
     *
     * @throws {Error}
     */
    _toString() {
      // must be implemented by each of the Node implementations
      throw new Error('_toString not implemented for ' + this.type);
    }

    /**
     * Get a JSON representation of the node
     * Both .toJSON() and the static .fromJSON(json) should be implemented by all
     * implementations of Node
     * @returns {Object}
     */
    toJSON() {
      throw new Error('Cannot serialize object: toJSON not implemented by ' + this.type);
    }

    /**
     * Get HTML representation. (wrapper function)
     *
     * This function can get an object of the following form:
     * {
     *    handler: //This can be a callback function of the form
     *             // "function callback(node, options)" or
     *             // a map that maps function names (used in FunctionNodes)
     *             // to callbacks
     *    parenthesis: "keep" //the parenthesis option (This is optional)
     * }
     *
     * @param {Object} [options]
     * @return {string}
     */
    toHTML(options) {
      var customString = this._getCustomString(options);
      if (typeof customString !== 'undefined') {
        return customString;
      }
      return this._toHTML(options);
    }

    /**
     * Internal function to generate the HTML output.
     * This has to be implemented by every Node
     *
     * @throws {Error}
     */
    _toHTML() {
      // must be implemented by each of the Node implementations
      throw new Error('_toHTML not implemented for ' + this.type);
    }

    /**
     * Get LaTeX representation. (wrapper function)
     *
     * This function can get an object of the following form:
     * {
     *    handler: //This can be a callback function of the form
     *             // "function callback(node, options)"or
     *             // a map that maps function names (used in FunctionNodes)
     *             // to callbacks
     *    parenthesis: "keep" //the parenthesis option (This is optional)
     * }
     *
     * @param {Object} [options]
     * @return {string}
     */
    toTex(options) {
      var customString = this._getCustomString(options);
      if (typeof customString !== 'undefined') {
        return customString;
      }
      return this._toTex(options);
    }

    /**
     * Internal function to generate the LaTeX output.
     * This has to be implemented by every Node
     *
     * @param {Object} [options]
     * @throws {Error}
     */
    _toTex(options) {
      // must be implemented by each of the Node implementations
      throw new Error('_toTex not implemented for ' + this.type);
    }

    /**
     * Helper used by `to...` functions.
     */
    _getCustomString(options) {
      if (options && typeof options === 'object') {
        switch (typeof options.handler) {
          case 'object':
          case 'undefined':
            return;
          case 'function':
            return options.handler(this, options);
          default:
            throw new TypeError('Object or function expected as callback');
        }
      }
    }

    /**
     * Get identifier.
     * @return {string}
     */
    getIdentifier() {
      return this.type;
    }

    /**
     * Get the content of the current Node.
     * @return {Node} node
     **/
    getContent() {
      return this;
    }
  }
  return Node;
}, {
  isClass: true,
  isNode: true
});

/**
 * Transform zero-based indices to one-based indices in errors
 * @param {Error} err
 * @returns {Error | IndexError} Returns the transformed error
 */
function errorTransform(err) {
  if (err && err.isIndexError) {
    return new IndexError(err.index + 1, err.min + 1, err.max !== undefined ? err.max + 1 : undefined);
  }
  return err;
}

function accessFactory(_ref) {
  var {
    subset
  } = _ref;
  /**
   * Retrieve part of an object:
   *
   * - Retrieve a property from an object
   * - Retrieve a part of a string
   * - Retrieve a matrix subset
   *
   * @param {Object | Array | Matrix | string} object
   * @param {Index} index
   * @return {Object | Array | Matrix | string} Returns the subset
   */
  return function access(object, index) {
    try {
      if (Array.isArray(object)) {
        return subset(object, index);
      } else if (object && typeof object.subset === 'function') {
        // Matrix
        return object.subset(index);
      } else if (typeof object === 'string') {
        // TODO: move getStringSubset into a separate util file, use that
        return subset(object, index);
      } else if (typeof object === 'object') {
        if (!index.isObjectProperty()) {
          throw new TypeError('Cannot apply a numeric index as object property');
        }
        return getSafeProperty(object, index.getObjectProperty());
      } else {
        throw new TypeError('Cannot apply index: unsupported type of object');
      }
    } catch (err) {
      throw errorTransform(err);
    }
  };
}

var name$1G = 'AccessorNode';
var dependencies$1G = ['subset', 'Node'];
var createAccessorNode = /* #__PURE__ */factory(name$1G, dependencies$1G, _ref => {
  var {
    subset,
    Node
  } = _ref;
  var access = accessFactory({
    subset
  });

  /**
   * Are parenthesis needed?
   * @private
   */
  function needParenthesis(node) {
    // TODO: maybe make a method on the nodes which tells whether they need parenthesis?
    return !(isAccessorNode(node) || isArrayNode(node) || isConstantNode(node) || isFunctionNode(node) || isObjectNode(node) || isParenthesisNode(node) || isSymbolNode(node));
  }
  class AccessorNode extends Node {
    /**
     * @constructor AccessorNode
     * @extends {Node}
     * Access an object property or get a matrix subset
     *
     * @param {Node} object                 The object from which to retrieve
     *                                      a property or subset.
     * @param {IndexNode} index             IndexNode containing ranges
     */
    constructor(object, index) {
      super();
      if (!isNode(object)) {
        throw new TypeError('Node expected for parameter "object"');
      }
      if (!isIndexNode(index)) {
        throw new TypeError('IndexNode expected for parameter "index"');
      }
      this.object = object;
      this.index = index;
    }

    // readonly property name
    get name() {
      if (this.index) {
        return this.index.isObjectProperty() ? this.index.getObjectProperty() : '';
      } else {
        return this.object.name || '';
      }
    }
    get type() {
      return name$1G;
    }
    get isAccessorNode() {
      return true;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      var evalObject = this.object._compile(math, argNames);
      var evalIndex = this.index._compile(math, argNames);
      if (this.index.isObjectProperty()) {
        var prop = this.index.getObjectProperty();
        return function evalAccessorNode(scope, args, context) {
          // get a property from an object evaluated using the scope.
          return getSafeProperty(evalObject(scope, args, context), prop);
        };
      } else {
        return function evalAccessorNode(scope, args, context) {
          var object = evalObject(scope, args, context);
          // we pass just object here instead of context:
          var index = evalIndex(scope, args, object);
          return access(object, index);
        };
      }
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      callback(this.object, 'object', this);
      callback(this.index, 'index', this);
    }

    /**
     * Create a new AccessorNode whose children are the results of calling
     * the provided callback function for each child of the original node.
     * @param {function(child: Node, path: string, parent: Node): Node} callback
     * @returns {AccessorNode} Returns a transformed copy of the node
     */
    map(callback) {
      return new AccessorNode(this._ifNode(callback(this.object, 'object', this)), this._ifNode(callback(this.index, 'index', this)));
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {AccessorNode}
     */
    clone() {
      return new AccessorNode(this.object, this.index);
    }

    /**
     * Get string representation
     * @param {Object} options
     * @return {string}
     */
    _toString(options) {
      var object = this.object.toString(options);
      if (needParenthesis(this.object)) {
        object = '(' + object + ')';
      }
      return object + this.index.toString(options);
    }

    /**
     * Get HTML representation
     * @param {Object} options
     * @return {string}
     */
    _toHTML(options) {
      var object = this.object.toHTML(options);
      if (needParenthesis(this.object)) {
        object = '<span class="math-parenthesis math-round-parenthesis">(</span>' + object + '<span class="math-parenthesis math-round-parenthesis">)</span>';
      }
      return object + this.index.toHTML(options);
    }

    /**
     * Get LaTeX representation
     * @param {Object} options
     * @return {string}
     */
    _toTex(options) {
      var object = this.object.toTex(options);
      if (needParenthesis(this.object)) {
        object = '\\left(\' + object + \'\\right)';
      }
      return object + this.index.toTex(options);
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      return {
        mathjs: name$1G,
        object: this.object,
        index: this.index
      };
    }

    /**
     * Instantiate an AccessorNode from its JSON representation
     * @param {Object} json
     *     An object structured like
     *     `{"mathjs": "AccessorNode", object: ..., index: ...}`,
     *     where mathjs is optional
     * @returns {AccessorNode}
     */
    static fromJSON(json) {
      return new AccessorNode(json.object, json.index);
    }
  }
  _defineProperty(AccessorNode, "name", name$1G);
  return AccessorNode;
}, {
  isClass: true,
  isNode: true
});

var name$1F = 'ArrayNode';
var dependencies$1F = ['Node'];
var createArrayNode = /* #__PURE__ */factory(name$1F, dependencies$1F, _ref => {
  var {
    Node
  } = _ref;
  class ArrayNode extends Node {
    /**
     * @constructor ArrayNode
     * @extends {Node}
     * Holds an 1-dimensional array with items
     * @param {Node[]} [items]   1 dimensional array with items
     */
    constructor(items) {
      super();
      this.items = items || [];

      // validate input
      if (!Array.isArray(this.items) || !this.items.every(isNode)) {
        throw new TypeError('Array containing Nodes expected');
      }
    }
    get type() {
      return name$1F;
    }
    get isArrayNode() {
      return true;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      var evalItems = map(this.items, function (item) {
        return item._compile(math, argNames);
      });
      var asMatrix = math.config.matrix !== 'Array';
      if (asMatrix) {
        var matrix = math.matrix;
        return function evalArrayNode(scope, args, context) {
          return matrix(map(evalItems, function (evalItem) {
            return evalItem(scope, args, context);
          }));
        };
      } else {
        return function evalArrayNode(scope, args, context) {
          return map(evalItems, function (evalItem) {
            return evalItem(scope, args, context);
          });
        };
      }
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      for (var i = 0; i < this.items.length; i++) {
        var node = this.items[i];
        callback(node, 'items[' + i + ']', this);
      }
    }

    /**
     * Create a new ArrayNode whose children are the results of calling
     * the provided callback function for each child of the original node.
     * @param {function(child: Node, path: string, parent: Node): Node} callback
     * @returns {ArrayNode} Returns a transformed copy of the node
     */
    map(callback) {
      var items = [];
      for (var i = 0; i < this.items.length; i++) {
        items[i] = this._ifNode(callback(this.items[i], 'items[' + i + ']', this));
      }
      return new ArrayNode(items);
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {ArrayNode}
     */
    clone() {
      return new ArrayNode(this.items.slice(0));
    }

    /**
     * Get string representation
     * @param {Object} options
     * @return {string} str
     * @override
     */
    _toString(options) {
      var items = this.items.map(function (node) {
        return node.toString(options);
      });
      return '[' + items.join(', ') + ']';
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      return {
        mathjs: name$1F,
        items: this.items
      };
    }

    /**
     * Instantiate an ArrayNode from its JSON representation
     * @param {Object} json  An object structured like
     *                       `{"mathjs": "ArrayNode", items: [...]}`,
     *                       where mathjs is optional
     * @returns {ArrayNode}
     */
    static fromJSON(json) {
      return new ArrayNode(json.items);
    }

    /**
     * Get HTML representation
     * @param {Object} options
     * @return {string} str
     * @override
     */
    _toHTML(options) {
      var items = this.items.map(function (node) {
        return node.toHTML(options);
      });
      return '<span class="math-parenthesis math-square-parenthesis">[</span>' + items.join('<span class="math-separator">,</span>') + '<span class="math-parenthesis math-square-parenthesis">]</span>';
    }

    /**
     * Get LaTeX representation
     * @param {Object} options
     * @return {string} str
     */
    _toTex(options) {
      function itemsToTex(items, nested) {
        var mixedItems = items.some(isArrayNode) && !items.every(isArrayNode);
        var itemsFormRow = nested || mixedItems;
        var itemSep = itemsFormRow ? '&' : '\\\\';
        var itemsTex = items.map(function (node) {
          if (node.items) {
            return itemsToTex(node.items, !nested);
          } else {
            return node.toTex(options);
          }
        }).join(itemSep);
        return mixedItems || !itemsFormRow || itemsFormRow && !nested ? '\\begin{bmatrix}' + itemsTex + '\\end{bmatrix}' : itemsTex;
      }
      return itemsToTex(this.items, false);
    }
  }
  _defineProperty(ArrayNode, "name", name$1F);
  return ArrayNode;
}, {
  isClass: true,
  isNode: true
});

function assignFactory(_ref) {
  var {
    subset,
    matrix
  } = _ref;
  /**
   * Replace part of an object:
   *
   * - Assign a property to an object
   * - Replace a part of a string
   * - Replace a matrix subset
   *
   * @param {Object | Array | Matrix | string} object
   * @param {Index} index
   * @param {*} value
   * @return {Object | Array | Matrix | string} Returns the original object
   *                                            except in case of a string
   */
  // TODO: change assign to return the value instead of the object
  return function assign(object, index, value) {
    try {
      if (Array.isArray(object)) {
        var result = matrix(object).subset(index, value).valueOf();

        // shallow copy all (updated) items into the original array
        result.forEach((item, index) => {
          object[index] = item;
        });
        return object;
      } else if (object && typeof object.subset === 'function') {
        // Matrix
        return object.subset(index, value);
      } else if (typeof object === 'string') {
        // TODO: move setStringSubset into a separate util file, use that
        return subset(object, index, value);
      } else if (typeof object === 'object') {
        if (!index.isObjectProperty()) {
          throw TypeError('Cannot apply a numeric index as object property');
        }
        setSafeProperty(object, index.getObjectProperty(), value);
        return object;
      } else {
        throw new TypeError('Cannot apply index: unsupported type of object');
      }
    } catch (err) {
      throw errorTransform(err);
    }
  };
}

// list of identifiers of nodes in order of their precedence
var properties = [{
  // assignment
  AssignmentNode: {},
  FunctionAssignmentNode: {}
}, {
  // conditional expression
  ConditionalNode: {
    latexLeftParens: false,
    latexRightParens: false,
    latexParens: false
    // conditionals don't need parentheses in LaTeX because
    // they are 2 dimensional
  }
}, {
  // logical or
  'OperatorNode:or': {
    op: 'or',
    associativity: 'left',
    associativeWith: []
  }
}, {
  // logical xor
  'OperatorNode:xor': {
    op: 'xor',
    associativity: 'left',
    associativeWith: []
  }
}, {
  // logical and
  'OperatorNode:and': {
    op: 'and',
    associativity: 'left',
    associativeWith: []
  }
}, {
  // bitwise or
  'OperatorNode:bitOr': {
    op: '|',
    associativity: 'left',
    associativeWith: []
  }
}, {
  // bitwise xor
  'OperatorNode:bitXor': {
    op: '^|',
    associativity: 'left',
    associativeWith: []
  }
}, {
  // bitwise and
  'OperatorNode:bitAnd': {
    op: '&',
    associativity: 'left',
    associativeWith: []
  }
}, {
  // relational operators
  'OperatorNode:equal': {
    op: '==',
    associativity: 'left',
    associativeWith: []
  },
  'OperatorNode:unequal': {
    op: '!=',
    associativity: 'left',
    associativeWith: []
  },
  'OperatorNode:smaller': {
    op: '<',
    associativity: 'left',
    associativeWith: []
  },
  'OperatorNode:larger': {
    op: '>',
    associativity: 'left',
    associativeWith: []
  },
  'OperatorNode:smallerEq': {
    op: '<=',
    associativity: 'left',
    associativeWith: []
  },
  'OperatorNode:largerEq': {
    op: '>=',
    associativity: 'left',
    associativeWith: []
  },
  RelationalNode: {
    associativity: 'left',
    associativeWith: []
  }
}, {
  // bitshift operators
  'OperatorNode:leftShift': {
    op: '<<',
    associativity: 'left',
    associativeWith: []
  },
  'OperatorNode:rightArithShift': {
    op: '>>',
    associativity: 'left',
    associativeWith: []
  },
  'OperatorNode:rightLogShift': {
    op: '>>>',
    associativity: 'left',
    associativeWith: []
  }
}, {
  // unit conversion
  'OperatorNode:to': {
    op: 'to',
    associativity: 'left',
    associativeWith: []
  }
}, {
  // range
  RangeNode: {}
}, {
  // addition, subtraction
  'OperatorNode:add': {
    op: '+',
    associativity: 'left',
    associativeWith: ['OperatorNode:add', 'OperatorNode:subtract']
  },
  'OperatorNode:subtract': {
    op: '-',
    associativity: 'left',
    associativeWith: []
  }
}, {
  // multiply, divide, modulus
  'OperatorNode:multiply': {
    op: '*',
    associativity: 'left',
    associativeWith: ['OperatorNode:multiply', 'OperatorNode:divide', 'Operator:dotMultiply', 'Operator:dotDivide']
  },
  'OperatorNode:divide': {
    op: '/',
    associativity: 'left',
    associativeWith: [],
    latexLeftParens: false,
    latexRightParens: false,
    latexParens: false
    // fractions don't require parentheses because
    // they're 2 dimensional, so parens aren't needed
    // in LaTeX
  },
  'OperatorNode:dotMultiply': {
    op: '.*',
    associativity: 'left',
    associativeWith: ['OperatorNode:multiply', 'OperatorNode:divide', 'OperatorNode:dotMultiply', 'OperatorNode:doDivide']
  },
  'OperatorNode:dotDivide': {
    op: './',
    associativity: 'left',
    associativeWith: []
  },
  'OperatorNode:mod': {
    op: 'mod',
    associativity: 'left',
    associativeWith: []
  }
}, {
  // Repeat multiplication for implicit multiplication
  'OperatorNode:multiply': {
    associativity: 'left',
    associativeWith: ['OperatorNode:multiply', 'OperatorNode:divide', 'Operator:dotMultiply', 'Operator:dotDivide']
  }
}, {
  // unary prefix operators
  'OperatorNode:unaryPlus': {
    op: '+',
    associativity: 'right'
  },
  'OperatorNode:unaryMinus': {
    op: '-',
    associativity: 'right'
  },
  'OperatorNode:bitNot': {
    op: '~',
    associativity: 'right'
  },
  'OperatorNode:not': {
    op: 'not',
    associativity: 'right'
  }
}, {
  // exponentiation
  'OperatorNode:pow': {
    op: '^',
    associativity: 'right',
    associativeWith: [],
    latexRightParens: false
    // the exponent doesn't need parentheses in
    // LaTeX because it's 2 dimensional
    // (it's on top)
  },
  'OperatorNode:dotPow': {
    op: '.^',
    associativity: 'right',
    associativeWith: []
  }
}, {
  // factorial
  'OperatorNode:factorial': {
    op: '!',
    associativity: 'left'
  }
}, {
  // matrix transpose
  'OperatorNode:ctranspose': {
    op: "'",
    associativity: 'left'
  }
}];

/**
 * Returns the first non-parenthesis internal node, but only
 * when the 'parenthesis' option is unset or auto.
 * @param {Node} _node
 * @param {string} parenthesis
 * @return {Node}
 */
function unwrapParen(_node, parenthesis) {
  if (!parenthesis || parenthesis !== 'auto') return _node;
  var node = _node;
  while (isParenthesisNode(node)) node = node.content;
  return node;
}

/**
 * Get the precedence of a Node.
 * Higher number for higher precedence, starting with 0.
 * Returns null if the precedence is undefined.
 *
 * @param {Node} _node
 * @param {string} parenthesis
 * @param {string} implicit
 * @param {Node} parent (for determining context for implicit multiplication)
 * @return {number | null}
 */
function getPrecedence(_node, parenthesis, implicit, parent) {
  var node = _node;
  if (parenthesis !== 'keep') {
    // ParenthesisNodes are only ignored when not in 'keep' mode
    node = _node.getContent();
  }
  var identifier = node.getIdentifier();
  var precedence = null;
  for (var i = 0; i < properties.length; i++) {
    if (identifier in properties[i]) {
      precedence = i;
      break;
    }
  }
  // Bump up precedence of implicit multiplication, except when preceded
  // by a "Rule 2" fraction ( [unaryOp]constant / constant )
  if (identifier === 'OperatorNode:multiply' && node.implicit && implicit !== 'show') {
    var leftArg = unwrapParen(node.args[0], parenthesis);
    if (!(isConstantNode(leftArg) && parent && parent.getIdentifier() === 'OperatorNode:divide' && rule2Node(unwrapParen(parent.args[0], parenthesis))) && !(leftArg.getIdentifier() === 'OperatorNode:divide' && rule2Node(unwrapParen(leftArg.args[0], parenthesis)) && isConstantNode(unwrapParen(leftArg.args[1])))) {
      precedence += 1;
    }
  }
  return precedence;
}

/**
 * Get the associativity of an operator (left or right).
 * Returns a string containing 'left' or 'right' or null if
 * the associativity is not defined.
 *
 * @param {Node} _node
 * @param {string} parenthesis
 * @return {string|null}
 * @throws {Error}
 */
function getAssociativity(_node, parenthesis) {
  var node = _node;
  if (parenthesis !== 'keep') {
    // ParenthesisNodes are only ignored when not in 'keep' mode
    node = _node.getContent();
  }
  var identifier = node.getIdentifier();
  var index = getPrecedence(node, parenthesis);
  if (index === null) {
    // node isn't in the list
    return null;
  }
  var property = properties[index][identifier];
  if (hasOwnProperty(property, 'associativity')) {
    if (property.associativity === 'left') {
      return 'left';
    }
    if (property.associativity === 'right') {
      return 'right';
    }
    // associativity is invalid
    throw Error('\'' + identifier + '\' has the invalid associativity \'' + property.associativity + '\'.');
  }

  // associativity is undefined
  return null;
}

/**
 * Check if an operator is associative with another operator.
 * Returns either true or false or null if not defined.
 *
 * @param {Node} nodeA
 * @param {Node} nodeB
 * @param {string} parenthesis
 * @return {boolean | null}
 */
function isAssociativeWith(nodeA, nodeB, parenthesis) {
  // ParenthesisNodes are only ignored when not in 'keep' mode
  var a = parenthesis !== 'keep' ? nodeA.getContent() : nodeA;
  var b = parenthesis !== 'keep' ? nodeA.getContent() : nodeB;
  var identifierA = a.getIdentifier();
  var identifierB = b.getIdentifier();
  var index = getPrecedence(a, parenthesis);
  if (index === null) {
    // node isn't in the list
    return null;
  }
  var property = properties[index][identifierA];
  if (hasOwnProperty(property, 'associativeWith') && property.associativeWith instanceof Array) {
    for (var i = 0; i < property.associativeWith.length; i++) {
      if (property.associativeWith[i] === identifierB) {
        return true;
      }
    }
    return false;
  }

  // associativeWith is not defined
  return null;
}

/**
 * Get the operator associated with a function name.
 * Returns a string with the operator symbol, or null if the
 * input is not the name of a function associated with an
 * operator.
 *
 * @param {string} Function name
 * @return {string | null} Associated operator symbol, if any
 */
function getOperator(fn) {
  var identifier = 'OperatorNode:' + fn;
  for (var group of properties) {
    if (identifier in group) {
      return group[identifier].op;
    }
  }
  return null;
}

var name$1E = 'AssignmentNode';
var dependencies$1E = ['subset', '?matrix',
// FIXME: should not be needed at all, should be handled by subset
'Node'];
var createAssignmentNode = /* #__PURE__ */factory(name$1E, dependencies$1E, _ref => {
  var {
    subset,
    matrix,
    Node
  } = _ref;
  var access = accessFactory({
    subset
  });
  var assign = assignFactory({
    subset,
    matrix
  });

  /*
   * Is parenthesis needed?
   * @param {node} node
   * @param {string} [parenthesis='keep']
   * @param {string} implicit
   * @private
   */
  function needParenthesis(node, parenthesis, implicit) {
    if (!parenthesis) {
      parenthesis = 'keep';
    }
    var precedence = getPrecedence(node, parenthesis, implicit);
    var exprPrecedence = getPrecedence(node.value, parenthesis, implicit);
    return parenthesis === 'all' || exprPrecedence !== null && exprPrecedence <= precedence;
  }
  class AssignmentNode extends Node {
    /**
     * @constructor AssignmentNode
     * @extends {Node}
     *
     * Define a symbol, like `a=3.2`, update a property like `a.b=3.2`, or
     * replace a subset of a matrix like `A[2,2]=42`.
     *
     * Syntax:
     *
     *     new AssignmentNode(symbol, value)
     *     new AssignmentNode(object, index, value)
     *
     * Usage:
     *
     *    new AssignmentNode(new SymbolNode('a'), new ConstantNode(2))  // a=2
     *    new AssignmentNode(new SymbolNode('a'),
     *                       new IndexNode('b'),
     *                       new ConstantNode(2))   // a.b=2
     *    new AssignmentNode(new SymbolNode('a'),
     *                       new IndexNode(1, 2),
     *                       new ConstantNode(3))  // a[1,2]=3
     *
     * @param {SymbolNode | AccessorNode} object
     *     Object on which to assign a value
     * @param {IndexNode} [index=null]
     *     Index, property name or matrix index. Optional. If not provided
     *     and `object` is a SymbolNode, the property is assigned to the
     *     global scope.
     * @param {Node} value
     *     The value to be assigned
     */
    constructor(object, index, value) {
      super();
      this.object = object;
      this.index = value ? index : null;
      this.value = value || index;

      // validate input
      if (!isSymbolNode(object) && !isAccessorNode(object)) {
        throw new TypeError('SymbolNode or AccessorNode expected as "object"');
      }
      if (isSymbolNode(object) && object.name === 'end') {
        throw new Error('Cannot assign to symbol "end"');
      }
      if (this.index && !isIndexNode(this.index)) {
        // index is optional
        throw new TypeError('IndexNode expected as "index"');
      }
      if (!isNode(this.value)) {
        throw new TypeError('Node expected as "value"');
      }
    }

    // class name for typing purposes:

    // readonly property name
    get name() {
      if (this.index) {
        return this.index.isObjectProperty() ? this.index.getObjectProperty() : '';
      } else {
        return this.object.name || '';
      }
    }
    get type() {
      return name$1E;
    }
    get isAssignmentNode() {
      return true;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      var evalObject = this.object._compile(math, argNames);
      var evalIndex = this.index ? this.index._compile(math, argNames) : null;
      var evalValue = this.value._compile(math, argNames);
      var name = this.object.name;
      if (!this.index) {
        // apply a variable to the scope, for example `a=2`
        if (!isSymbolNode(this.object)) {
          throw new TypeError('SymbolNode expected as object');
        }
        return function evalAssignmentNode(scope, args, context) {
          var value = evalValue(scope, args, context);
          scope.set(name, value);
          return value;
        };
      } else if (this.index.isObjectProperty()) {
        // apply an object property for example `a.b=2`
        var prop = this.index.getObjectProperty();
        return function evalAssignmentNode(scope, args, context) {
          var object = evalObject(scope, args, context);
          var value = evalValue(scope, args, context);
          setSafeProperty(object, prop, value);
          return value;
        };
      } else if (isSymbolNode(this.object)) {
        // update a matrix subset, for example `a[2]=3`
        return function evalAssignmentNode(scope, args, context) {
          var childObject = evalObject(scope, args, context);
          var value = evalValue(scope, args, context);
          // Important:  we pass childObject instead of context:
          var index = evalIndex(scope, args, childObject);
          scope.set(name, assign(childObject, index, value));
          return value;
        };
      } else {
        // isAccessorNode(node.object) === true
        // update a matrix subset, for example `a.b[2]=3`

        // we will not use the compile function of the AccessorNode, but
        // compile it ourselves here as we need the parent object of the
        // AccessorNode:
        // wee need to apply the updated object to parent object
        var evalParentObject = this.object.object._compile(math, argNames);
        if (this.object.index.isObjectProperty()) {
          var parentProp = this.object.index.getObjectProperty();
          return function evalAssignmentNode(scope, args, context) {
            var parent = evalParentObject(scope, args, context);
            var childObject = getSafeProperty(parent, parentProp);
            // Important: we pass childObject instead of context:
            var index = evalIndex(scope, args, childObject);
            var value = evalValue(scope, args, context);
            setSafeProperty(parent, parentProp, assign(childObject, index, value));
            return value;
          };
        } else {
          // if some parameters use the 'end' parameter, we need to calculate
          // the size
          var evalParentIndex = this.object.index._compile(math, argNames);
          return function evalAssignmentNode(scope, args, context) {
            var parent = evalParentObject(scope, args, context);
            // Important: we pass parent instead of context:
            var parentIndex = evalParentIndex(scope, args, parent);
            var childObject = access(parent, parentIndex);
            // Important:  we pass childObject instead of context
            var index = evalIndex(scope, args, childObject);
            var value = evalValue(scope, args, context);
            assign(parent, parentIndex, assign(childObject, index, value));
            return value;
          };
        }
      }
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      callback(this.object, 'object', this);
      if (this.index) {
        callback(this.index, 'index', this);
      }
      callback(this.value, 'value', this);
    }

    /**
     * Create a new AssignmentNode whose children are the results of calling
     * the provided callback function for each child of the original node.
     * @param {function(child: Node, path: string, parent: Node): Node} callback
     * @returns {AssignmentNode} Returns a transformed copy of the node
     */
    map(callback) {
      var object = this._ifNode(callback(this.object, 'object', this));
      var index = this.index ? this._ifNode(callback(this.index, 'index', this)) : null;
      var value = this._ifNode(callback(this.value, 'value', this));
      return new AssignmentNode(object, index, value);
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {AssignmentNode}
     */
    clone() {
      return new AssignmentNode(this.object, this.index, this.value);
    }

    /**
     * Get string representation
     * @param {Object} options
     * @return {string}
     */
    _toString(options) {
      var object = this.object.toString(options);
      var index = this.index ? this.index.toString(options) : '';
      var value = this.value.toString(options);
      if (needParenthesis(this, options && options.parenthesis, options && options.implicit)) {
        value = '(' + value + ')';
      }
      return object + index + ' = ' + value;
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      return {
        mathjs: name$1E,
        object: this.object,
        index: this.index,
        value: this.value
      };
    }

    /**
     * Instantiate an AssignmentNode from its JSON representation
     * @param {Object} json
     *     An object structured like
     *     `{"mathjs": "AssignmentNode", object: ..., index: ..., value: ...}`,
     *     where mathjs is optional
     * @returns {AssignmentNode}
     */
    static fromJSON(json) {
      return new AssignmentNode(json.object, json.index, json.value);
    }

    /**
     * Get HTML representation
     * @param {Object} options
     * @return {string}
     */
    _toHTML(options) {
      var object = this.object.toHTML(options);
      var index = this.index ? this.index.toHTML(options) : '';
      var value = this.value.toHTML(options);
      if (needParenthesis(this, options && options.parenthesis, options && options.implicit)) {
        value = '<span class="math-paranthesis math-round-parenthesis">(</span>' + value + '<span class="math-paranthesis math-round-parenthesis">)</span>';
      }
      return object + index + '<span class="math-operator math-assignment-operator ' + 'math-variable-assignment-operator math-binary-operator">=</span>' + value;
    }

    /**
     * Get LaTeX representation
     * @param {Object} options
     * @return {string}
     */
    _toTex(options) {
      var object = this.object.toTex(options);
      var index = this.index ? this.index.toTex(options) : '';
      var value = this.value.toTex(options);
      if (needParenthesis(this, options && options.parenthesis, options && options.implicit)) {
        value = "\\left(".concat(value, "\\right)");
      }
      return object + index + '=' + value;
    }
  }
  _defineProperty(AssignmentNode, "name", name$1E);
  return AssignmentNode;
}, {
  isClass: true,
  isNode: true
});

var name$1D = 'BlockNode';
var dependencies$1D = ['ResultSet', 'Node'];
var createBlockNode = /* #__PURE__ */factory(name$1D, dependencies$1D, _ref => {
  var {
    ResultSet,
    Node
  } = _ref;
  class BlockNode extends Node {
    /**
     * @constructor BlockNode
     * @extends {Node}
     * Holds a set with blocks
     * @param {Array.<{node: Node} | {node: Node, visible: boolean}>} blocks
     *            An array with blocks, where a block is constructed as an
     *            Object with properties block, which is a Node, and visible,
     *            which is a boolean. The property visible is optional and
     *            is true by default
     */
    constructor(blocks) {
      super();
      // validate input, copy blocks
      if (!Array.isArray(blocks)) throw new Error('Array expected');
      this.blocks = blocks.map(function (block) {
        var node = block && block.node;
        var visible = block && block.visible !== undefined ? block.visible : true;
        if (!isNode(node)) throw new TypeError('Property "node" must be a Node');
        if (typeof visible !== 'boolean') {
          throw new TypeError('Property "visible" must be a boolean');
        }
        return {
          node,
          visible
        };
      });
    }
    get type() {
      return name$1D;
    }
    get isBlockNode() {
      return true;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      var evalBlocks = map(this.blocks, function (block) {
        return {
          evaluate: block.node._compile(math, argNames),
          visible: block.visible
        };
      });
      return function evalBlockNodes(scope, args, context) {
        var results = [];
        forEach(evalBlocks, function evalBlockNode(block) {
          var result = block.evaluate(scope, args, context);
          if (block.visible) {
            results.push(result);
          }
        });
        return new ResultSet(results);
      };
    }

    /**
     * Execute a callback for each of the child blocks of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      for (var i = 0; i < this.blocks.length; i++) {
        callback(this.blocks[i].node, 'blocks[' + i + '].node', this);
      }
    }

    /**
     * Create a new BlockNode whose children are the results of calling
     * the provided callback function for each child of the original node.
     * @param {function(child: Node, path: string, parent: Node): Node} callback
     * @returns {BlockNode} Returns a transformed copy of the node
     */
    map(callback) {
      var blocks = [];
      for (var i = 0; i < this.blocks.length; i++) {
        var block = this.blocks[i];
        var node = this._ifNode(callback(block.node, 'blocks[' + i + '].node', this));
        blocks[i] = {
          node,
          visible: block.visible
        };
      }
      return new BlockNode(blocks);
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {BlockNode}
     */
    clone() {
      var blocks = this.blocks.map(function (block) {
        return {
          node: block.node,
          visible: block.visible
        };
      });
      return new BlockNode(blocks);
    }

    /**
     * Get string representation
     * @param {Object} options
     * @return {string} str
     * @override
     */
    _toString(options) {
      return this.blocks.map(function (param) {
        return param.node.toString(options) + (param.visible ? '' : ';');
      }).join('\n');
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      return {
        mathjs: name$1D,
        blocks: this.blocks
      };
    }

    /**
     * Instantiate an BlockNode from its JSON representation
     * @param {Object} json
     *     An object structured like
     *     `{"mathjs": "BlockNode", blocks: [{node: ..., visible: false}, ...]}`,
     *     where mathjs is optional
     * @returns {BlockNode}
     */
    static fromJSON(json) {
      return new BlockNode(json.blocks);
    }

    /**
     * Get HTML representation
     * @param {Object} options
     * @return {string} str
     * @override
     */
    _toHTML(options) {
      return this.blocks.map(function (param) {
        return param.node.toHTML(options) + (param.visible ? '' : '<span class="math-separator">;</span>');
      }).join('<span class="math-separator"><br /></span>');
    }

    /**
     * Get LaTeX representation
     * @param {Object} options
     * @return {string} str
     */
    _toTex(options) {
      return this.blocks.map(function (param) {
        return param.node.toTex(options) + (param.visible ? '' : ';');
      }).join('\\;\\;\n');
    }
  }
  _defineProperty(BlockNode, "name", name$1D);
  return BlockNode;
}, {
  isClass: true,
  isNode: true
});

var name$1C = 'ConditionalNode';
var dependencies$1C = ['Node'];
var createConditionalNode = /* #__PURE__ */factory(name$1C, dependencies$1C, _ref => {
  var {
    Node
  } = _ref;
  /**
   * Test whether a condition is met
   * @param {*} condition
   * @returns {boolean} true if condition is true or non-zero, else false
   */
  function testCondition(condition) {
    if (typeof condition === 'number' || typeof condition === 'boolean' || typeof condition === 'string') {
      return !!condition;
    }
    if (condition) {
      if (isBigNumber(condition)) {
        return !condition.isZero();
      }
      if (isComplex(condition)) {
        return !!(condition.re || condition.im);
      }
      if (isUnit(condition)) {
        return !!condition.value;
      }
    }
    if (condition === null || condition === undefined) {
      return false;
    }
    throw new TypeError('Unsupported type of condition "' + typeOf(condition) + '"');
  }
  class ConditionalNode extends Node {
    /**
     * A lazy evaluating conditional operator: 'condition ? trueExpr : falseExpr'
     *
     * @param {Node} condition   Condition, must result in a boolean
     * @param {Node} trueExpr    Expression evaluated when condition is true
     * @param {Node} falseExpr   Expression evaluated when condition is true
     *
     * @constructor ConditionalNode
     * @extends {Node}
     */
    constructor(condition, trueExpr, falseExpr) {
      super();
      if (!isNode(condition)) {
        throw new TypeError('Parameter condition must be a Node');
      }
      if (!isNode(trueExpr)) {
        throw new TypeError('Parameter trueExpr must be a Node');
      }
      if (!isNode(falseExpr)) {
        throw new TypeError('Parameter falseExpr must be a Node');
      }
      this.condition = condition;
      this.trueExpr = trueExpr;
      this.falseExpr = falseExpr;
    }
    get type() {
      return name$1C;
    }
    get isConditionalNode() {
      return true;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      var evalCondition = this.condition._compile(math, argNames);
      var evalTrueExpr = this.trueExpr._compile(math, argNames);
      var evalFalseExpr = this.falseExpr._compile(math, argNames);
      return function evalConditionalNode(scope, args, context) {
        return testCondition(evalCondition(scope, args, context)) ? evalTrueExpr(scope, args, context) : evalFalseExpr(scope, args, context);
      };
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      callback(this.condition, 'condition', this);
      callback(this.trueExpr, 'trueExpr', this);
      callback(this.falseExpr, 'falseExpr', this);
    }

    /**
     * Create a new ConditionalNode whose children are the results of calling
     * the provided callback function for each child of the original node.
     * @param {function(child: Node, path: string, parent: Node): Node} callback
     * @returns {ConditionalNode} Returns a transformed copy of the node
     */
    map(callback) {
      return new ConditionalNode(this._ifNode(callback(this.condition, 'condition', this)), this._ifNode(callback(this.trueExpr, 'trueExpr', this)), this._ifNode(callback(this.falseExpr, 'falseExpr', this)));
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {ConditionalNode}
     */
    clone() {
      return new ConditionalNode(this.condition, this.trueExpr, this.falseExpr);
    }

    /**
     * Get string representation
     * @param {Object} options
     * @return {string} str
     */
    _toString(options) {
      var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
      var precedence = getPrecedence(this, parenthesis, options && options.implicit);

      // Enclose Arguments in parentheses if they are an OperatorNode
      // or have lower or equal precedence
      // NOTE: enclosing all OperatorNodes in parentheses is a decision
      // purely based on aesthetics and readability
      var condition = this.condition.toString(options);
      var conditionPrecedence = getPrecedence(this.condition, parenthesis, options && options.implicit);
      if (parenthesis === 'all' || this.condition.type === 'OperatorNode' || conditionPrecedence !== null && conditionPrecedence <= precedence) {
        condition = '(' + condition + ')';
      }
      var trueExpr = this.trueExpr.toString(options);
      var truePrecedence = getPrecedence(this.trueExpr, parenthesis, options && options.implicit);
      if (parenthesis === 'all' || this.trueExpr.type === 'OperatorNode' || truePrecedence !== null && truePrecedence <= precedence) {
        trueExpr = '(' + trueExpr + ')';
      }
      var falseExpr = this.falseExpr.toString(options);
      var falsePrecedence = getPrecedence(this.falseExpr, parenthesis, options && options.implicit);
      if (parenthesis === 'all' || this.falseExpr.type === 'OperatorNode' || falsePrecedence !== null && falsePrecedence <= precedence) {
        falseExpr = '(' + falseExpr + ')';
      }
      return condition + ' ? ' + trueExpr + ' : ' + falseExpr;
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      return {
        mathjs: name$1C,
        condition: this.condition,
        trueExpr: this.trueExpr,
        falseExpr: this.falseExpr
      };
    }

    /**
     * Instantiate an ConditionalNode from its JSON representation
     * @param {Object} json
     *     An object structured like
     *     ```
     *     {"mathjs": "ConditionalNode",
     *      "condition": ...,
     *      "trueExpr": ...,
     *      "falseExpr": ...}
     *     ```
     *     where mathjs is optional
     * @returns {ConditionalNode}
     */
    static fromJSON(json) {
      return new ConditionalNode(json.condition, json.trueExpr, json.falseExpr);
    }

    /**
     * Get HTML representation
     * @param {Object} options
     * @return {string} str
     */
    _toHTML(options) {
      var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
      var precedence = getPrecedence(this, parenthesis, options && options.implicit);

      // Enclose Arguments in parentheses if they are an OperatorNode
      // or have lower or equal precedence
      // NOTE: enclosing all OperatorNodes in parentheses is a decision
      // purely based on aesthetics and readability
      var condition = this.condition.toHTML(options);
      var conditionPrecedence = getPrecedence(this.condition, parenthesis, options && options.implicit);
      if (parenthesis === 'all' || this.condition.type === 'OperatorNode' || conditionPrecedence !== null && conditionPrecedence <= precedence) {
        condition = '<span class="math-parenthesis math-round-parenthesis">(</span>' + condition + '<span class="math-parenthesis math-round-parenthesis">)</span>';
      }
      var trueExpr = this.trueExpr.toHTML(options);
      var truePrecedence = getPrecedence(this.trueExpr, parenthesis, options && options.implicit);
      if (parenthesis === 'all' || this.trueExpr.type === 'OperatorNode' || truePrecedence !== null && truePrecedence <= precedence) {
        trueExpr = '<span class="math-parenthesis math-round-parenthesis">(</span>' + trueExpr + '<span class="math-parenthesis math-round-parenthesis">)</span>';
      }
      var falseExpr = this.falseExpr.toHTML(options);
      var falsePrecedence = getPrecedence(this.falseExpr, parenthesis, options && options.implicit);
      if (parenthesis === 'all' || this.falseExpr.type === 'OperatorNode' || falsePrecedence !== null && falsePrecedence <= precedence) {
        falseExpr = '<span class="math-parenthesis math-round-parenthesis">(</span>' + falseExpr + '<span class="math-parenthesis math-round-parenthesis">)</span>';
      }
      return condition + '<span class="math-operator math-conditional-operator">?</span>' + trueExpr + '<span class="math-operator math-conditional-operator">:</span>' + falseExpr;
    }

    /**
     * Get LaTeX representation
     * @param {Object} options
     * @return {string} str
     */
    _toTex(options) {
      return '\\begin{cases} {' + this.trueExpr.toTex(options) + '}, &\\quad{\\text{if }\\;' + this.condition.toTex(options) + '}\\\\{' + this.falseExpr.toTex(options) + '}, &\\quad{\\text{otherwise}}\\end{cases}';
    }
  }
  _defineProperty(ConditionalNode, "name", name$1C);
  return ConditionalNode;
}, {
  isClass: true,
  isNode: true
});

// Map the characters to escape to their escaped values. The list is derived
// from http://www.cespedes.org/blog/85/how-to-escape-latex-special-characters

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var defaultEscapes = {
  "{": "\\{",
  "}": "\\}",
  "\\": "\\textbackslash{}",
  "#": "\\#",
  $: "\\$",
  "%": "\\%",
  "&": "\\&",
  "^": "\\textasciicircum{}",
  _: "\\_",
  "~": "\\textasciitilde{}"
};
var formatEscapes = {
  "\u2013": "\\--",
  "\u2014": "\\---",
  " ": "~",
  "\t": "\\qquad{}",
  "\r\n": "\\newline{}",
  "\n": "\\newline{}"
};

var defaultEscapeMapFn = function defaultEscapeMapFn(defaultEscapes, formatEscapes) {
  return _extends({}, defaultEscapes, formatEscapes);
};

/**
 * Escape a string to be used in LaTeX documents.
 * @param {string} str the string to be escaped.
 * @param {boolean} params.preserveFormatting whether formatting escapes should
 *  be performed (default: false).
 * @param {function} params.escapeMapFn the function to modify the escape maps.
 * @return {string} the escaped string, ready to be used in LaTeX.
 */
var dist = function (str) {
  var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      _ref$preserveFormatti = _ref.preserveFormatting,
      preserveFormatting = _ref$preserveFormatti === undefined ? false : _ref$preserveFormatti,
      _ref$escapeMapFn = _ref.escapeMapFn,
      escapeMapFn = _ref$escapeMapFn === undefined ? defaultEscapeMapFn : _ref$escapeMapFn;

  var runningStr = String(str);
  var result = "";

  var escapes = escapeMapFn(_extends({}, defaultEscapes), preserveFormatting ? _extends({}, formatEscapes) : {});
  var escapeKeys = Object.keys(escapes); // as it is reused later on

  // Algorithm: Go through the string character by character, if it matches
  // with one of the special characters then we'll replace it with the escaped
  // version.

  var _loop = function _loop() {
    var specialCharFound = false;
    escapeKeys.forEach(function (key, index) {
      if (specialCharFound) {
        return;
      }
      if (runningStr.length >= key.length && runningStr.slice(0, key.length) === key) {
        result += escapes[escapeKeys[index]];
        runningStr = runningStr.slice(key.length, runningStr.length);
        specialCharFound = true;
      }
    });
    if (!specialCharFound) {
      result += runningStr.slice(0, 1);
      runningStr = runningStr.slice(1, runningStr.length);
    }
  };

  while (runningStr) {
    _loop();
  }
  return result;
};

/* eslint no-template-curly-in-string: "off" */
var latexSymbols = {
  // GREEK LETTERS
  Alpha: 'A',
  alpha: '\\alpha',
  Beta: 'B',
  beta: '\\beta',
  Gamma: '\\Gamma',
  gamma: '\\gamma',
  Delta: '\\Delta',
  delta: '\\delta',
  Epsilon: 'E',
  epsilon: '\\epsilon',
  varepsilon: '\\varepsilon',
  Zeta: 'Z',
  zeta: '\\zeta',
  Eta: 'H',
  eta: '\\eta',
  Theta: '\\Theta',
  theta: '\\theta',
  vartheta: '\\vartheta',
  Iota: 'I',
  iota: '\\iota',
  Kappa: 'K',
  kappa: '\\kappa',
  varkappa: '\\varkappa',
  Lambda: '\\Lambda',
  lambda: '\\lambda',
  Mu: 'M',
  mu: '\\mu',
  Nu: 'N',
  nu: '\\nu',
  Xi: '\\Xi',
  xi: '\\xi',
  Omicron: 'O',
  omicron: 'o',
  Pi: '\\Pi',
  pi: '\\pi',
  varpi: '\\varpi',
  Rho: 'P',
  rho: '\\rho',
  varrho: '\\varrho',
  Sigma: '\\Sigma',
  sigma: '\\sigma',
  varsigma: '\\varsigma',
  Tau: 'T',
  tau: '\\tau',
  Upsilon: '\\Upsilon',
  upsilon: '\\upsilon',
  Phi: '\\Phi',
  phi: '\\phi',
  varphi: '\\varphi',
  Chi: 'X',
  chi: '\\chi',
  Psi: '\\Psi',
  psi: '\\psi',
  Omega: '\\Omega',
  omega: '\\omega',
  // logic
  true: '\\mathrm{True}',
  false: '\\mathrm{False}',
  // other
  i: 'i',
  // TODO use \i ??
  inf: '\\infty',
  Inf: '\\infty',
  infinity: '\\infty',
  Infinity: '\\infty',
  oo: '\\infty',
  lim: '\\lim',
  undefined: '\\mathbf{?}'
};
var latexOperators = {
  transpose: '^\\top',
  ctranspose: '^H',
  factorial: '!',
  pow: '^',
  dotPow: '.^\\wedge',
  // TODO find ideal solution
  unaryPlus: '+',
  unaryMinus: '-',
  bitNot: '\\~',
  // TODO find ideal solution
  not: '\\neg',
  multiply: '\\cdot',
  divide: '\\frac',
  // TODO how to handle that properly?
  dotMultiply: '.\\cdot',
  // TODO find ideal solution
  dotDivide: '.:',
  // TODO find ideal solution
  mod: '\\mod',
  add: '+',
  subtract: '-',
  to: '\\rightarrow',
  leftShift: '<<',
  rightArithShift: '>>',
  rightLogShift: '>>>',
  equal: '=',
  unequal: '\\neq',
  smaller: '<',
  larger: '>',
  smallerEq: '\\leq',
  largerEq: '\\geq',
  bitAnd: '\\&',
  bitXor: '\\underline{|}',
  bitOr: '|',
  and: '\\wedge',
  xor: '\\veebar',
  or: '\\vee'
};
var latexFunctions = {
  // arithmetic
  abs: {
    1: '\\left|${args[0]}\\right|'
  },
  add: {
    2: "\\left(${args[0]}".concat(latexOperators.add, "${args[1]}\\right)")
  },
  cbrt: {
    1: '\\sqrt[3]{${args[0]}}'
  },
  ceil: {
    1: '\\left\\lceil${args[0]}\\right\\rceil'
  },
  cube: {
    1: '\\left(${args[0]}\\right)^3'
  },
  divide: {
    2: '\\frac{${args[0]}}{${args[1]}}'
  },
  dotDivide: {
    2: "\\left(${args[0]}".concat(latexOperators.dotDivide, "${args[1]}\\right)")
  },
  dotMultiply: {
    2: "\\left(${args[0]}".concat(latexOperators.dotMultiply, "${args[1]}\\right)")
  },
  dotPow: {
    2: "\\left(${args[0]}".concat(latexOperators.dotPow, "${args[1]}\\right)")
  },
  exp: {
    1: '\\exp\\left(${args[0]}\\right)'
  },
  expm1: "\\left(e".concat(latexOperators.pow, "{${args[0]}}-1\\right)"),
  fix: {
    1: '\\mathrm{${name}}\\left(${args[0]}\\right)'
  },
  floor: {
    1: '\\left\\lfloor${args[0]}\\right\\rfloor'
  },
  gcd: '\\gcd\\left(${args}\\right)',
  hypot: '\\hypot\\left(${args}\\right)',
  log: {
    1: '\\ln\\left(${args[0]}\\right)',
    2: '\\log_{${args[1]}}\\left(${args[0]}\\right)'
  },
  log10: {
    1: '\\log_{10}\\left(${args[0]}\\right)'
  },
  log1p: {
    1: '\\ln\\left(${args[0]}+1\\right)',
    2: '\\log_{${args[1]}}\\left(${args[0]}+1\\right)'
  },
  log2: '\\log_{2}\\left(${args[0]}\\right)',
  mod: {
    2: "\\left(${args[0]}".concat(latexOperators.mod, "${args[1]}\\right)")
  },
  multiply: {
    2: "\\left(${args[0]}".concat(latexOperators.multiply, "${args[1]}\\right)")
  },
  norm: {
    1: '\\left\\|${args[0]}\\right\\|',
    2: undefined // use default template
  },
  nthRoot: {
    2: '\\sqrt[${args[1]}]{${args[0]}}'
  },
  nthRoots: {
    2: '\\{y : $y^{args[1]} = {${args[0]}}\\}'
  },
  pow: {
    2: "\\left(${args[0]}\\right)".concat(latexOperators.pow, "{${args[1]}}")
  },
  round: {
    1: '\\left\\lfloor${args[0]}\\right\\rceil',
    2: undefined // use default template
  },
  sign: {
    1: '\\mathrm{${name}}\\left(${args[0]}\\right)'
  },
  sqrt: {
    1: '\\sqrt{${args[0]}}'
  },
  square: {
    1: '\\left(${args[0]}\\right)^2'
  },
  subtract: {
    2: "\\left(${args[0]}".concat(latexOperators.subtract, "${args[1]}\\right)")
  },
  unaryMinus: {
    1: "".concat(latexOperators.unaryMinus, "\\left(${args[0]}\\right)")
  },
  unaryPlus: {
    1: "".concat(latexOperators.unaryPlus, "\\left(${args[0]}\\right)")
  },
  // bitwise
  bitAnd: {
    2: "\\left(${args[0]}".concat(latexOperators.bitAnd, "${args[1]}\\right)")
  },
  bitNot: {
    1: latexOperators.bitNot + '\\left(${args[0]}\\right)'
  },
  bitOr: {
    2: "\\left(${args[0]}".concat(latexOperators.bitOr, "${args[1]}\\right)")
  },
  bitXor: {
    2: "\\left(${args[0]}".concat(latexOperators.bitXor, "${args[1]}\\right)")
  },
  leftShift: {
    2: "\\left(${args[0]}".concat(latexOperators.leftShift, "${args[1]}\\right)")
  },
  rightArithShift: {
    2: "\\left(${args[0]}".concat(latexOperators.rightArithShift, "${args[1]}\\right)")
  },
  rightLogShift: {
    2: "\\left(${args[0]}".concat(latexOperators.rightLogShift, "${args[1]}\\right)")
  },
  // combinatorics
  bellNumbers: {
    1: '\\mathrm{B}_{${args[0]}}'
  },
  catalan: {
    1: '\\mathrm{C}_{${args[0]}}'
  },
  stirlingS2: {
    2: '\\mathrm{S}\\left(${args}\\right)'
  },
  // complex
  arg: {
    1: '\\arg\\left(${args[0]}\\right)'
  },
  conj: {
    1: '\\left(${args[0]}\\right)^*'
  },
  im: {
    1: '\\Im\\left\\lbrace${args[0]}\\right\\rbrace'
  },
  re: {
    1: '\\Re\\left\\lbrace${args[0]}\\right\\rbrace'
  },
  // logical
  and: {
    2: "\\left(${args[0]}".concat(latexOperators.and, "${args[1]}\\right)")
  },
  not: {
    1: latexOperators.not + '\\left(${args[0]}\\right)'
  },
  or: {
    2: "\\left(${args[0]}".concat(latexOperators.or, "${args[1]}\\right)")
  },
  xor: {
    2: "\\left(${args[0]}".concat(latexOperators.xor, "${args[1]}\\right)")
  },
  // matrix
  cross: {
    2: '\\left(${args[0]}\\right)\\times\\left(${args[1]}\\right)'
  },
  ctranspose: {
    1: "\\left(${args[0]}\\right)".concat(latexOperators.ctranspose)
  },
  det: {
    1: '\\det\\left(${args[0]}\\right)'
  },
  dot: {
    2: '\\left(${args[0]}\\cdot${args[1]}\\right)'
  },
  expm: {
    1: '\\exp\\left(${args[0]}\\right)'
  },
  inv: {
    1: '\\left(${args[0]}\\right)^{-1}'
  },
  pinv: {
    1: '\\left(${args[0]}\\right)^{+}'
  },
  sqrtm: {
    1: "{${args[0]}}".concat(latexOperators.pow, "{\\frac{1}{2}}")
  },
  trace: {
    1: '\\mathrm{tr}\\left(${args[0]}\\right)'
  },
  transpose: {
    1: "\\left(${args[0]}\\right)".concat(latexOperators.transpose)
  },
  // probability
  combinations: {
    2: '\\binom{${args[0]}}{${args[1]}}'
  },
  combinationsWithRep: {
    2: '\\left(\\!\\!{\\binom{${args[0]}}{${args[1]}}}\\!\\!\\right)'
  },
  factorial: {
    1: "\\left(${args[0]}\\right)".concat(latexOperators.factorial)
  },
  gamma: {
    1: '\\Gamma\\left(${args[0]}\\right)'
  },
  lgamma: {
    1: '\\ln\\Gamma\\left(${args[0]}\\right)'
  },
  // relational
  equal: {
    2: "\\left(${args[0]}".concat(latexOperators.equal, "${args[1]}\\right)")
  },
  larger: {
    2: "\\left(${args[0]}".concat(latexOperators.larger, "${args[1]}\\right)")
  },
  largerEq: {
    2: "\\left(${args[0]}".concat(latexOperators.largerEq, "${args[1]}\\right)")
  },
  smaller: {
    2: "\\left(${args[0]}".concat(latexOperators.smaller, "${args[1]}\\right)")
  },
  smallerEq: {
    2: "\\left(${args[0]}".concat(latexOperators.smallerEq, "${args[1]}\\right)")
  },
  unequal: {
    2: "\\left(${args[0]}".concat(latexOperators.unequal, "${args[1]}\\right)")
  },
  // special
  erf: {
    1: 'erf\\left(${args[0]}\\right)'
  },
  // statistics
  max: '\\max\\left(${args}\\right)',
  min: '\\min\\left(${args}\\right)',
  variance: '\\mathrm{Var}\\left(${args}\\right)',
  // trigonometry
  acos: {
    1: '\\cos^{-1}\\left(${args[0]}\\right)'
  },
  acosh: {
    1: '\\cosh^{-1}\\left(${args[0]}\\right)'
  },
  acot: {
    1: '\\cot^{-1}\\left(${args[0]}\\right)'
  },
  acoth: {
    1: '\\coth^{-1}\\left(${args[0]}\\right)'
  },
  acsc: {
    1: '\\csc^{-1}\\left(${args[0]}\\right)'
  },
  acsch: {
    1: '\\mathrm{csch}^{-1}\\left(${args[0]}\\right)'
  },
  asec: {
    1: '\\sec^{-1}\\left(${args[0]}\\right)'
  },
  asech: {
    1: '\\mathrm{sech}^{-1}\\left(${args[0]}\\right)'
  },
  asin: {
    1: '\\sin^{-1}\\left(${args[0]}\\right)'
  },
  asinh: {
    1: '\\sinh^{-1}\\left(${args[0]}\\right)'
  },
  atan: {
    1: '\\tan^{-1}\\left(${args[0]}\\right)'
  },
  atan2: {
    2: '\\mathrm{atan2}\\left(${args}\\right)'
  },
  atanh: {
    1: '\\tanh^{-1}\\left(${args[0]}\\right)'
  },
  cos: {
    1: '\\cos\\left(${args[0]}\\right)'
  },
  cosh: {
    1: '\\cosh\\left(${args[0]}\\right)'
  },
  cot: {
    1: '\\cot\\left(${args[0]}\\right)'
  },
  coth: {
    1: '\\coth\\left(${args[0]}\\right)'
  },
  csc: {
    1: '\\csc\\left(${args[0]}\\right)'
  },
  csch: {
    1: '\\mathrm{csch}\\left(${args[0]}\\right)'
  },
  sec: {
    1: '\\sec\\left(${args[0]}\\right)'
  },
  sech: {
    1: '\\mathrm{sech}\\left(${args[0]}\\right)'
  },
  sin: {
    1: '\\sin\\left(${args[0]}\\right)'
  },
  sinh: {
    1: '\\sinh\\left(${args[0]}\\right)'
  },
  tan: {
    1: '\\tan\\left(${args[0]}\\right)'
  },
  tanh: {
    1: '\\tanh\\left(${args[0]}\\right)'
  },
  // unit
  to: {
    2: "\\left(${args[0]}".concat(latexOperators.to, "${args[1]}\\right)")
  },
  // utils
  numeric: function numeric(node, options) {
    // Not sure if this is strictly right but should work correctly for the vast majority of use cases.
    return node.args[0].toTex();
  },
  // type
  number: {
    0: '0',
    1: '\\left(${args[0]}\\right)',
    2: '\\left(\\left(${args[0]}\\right)${args[1]}\\right)'
  },
  string: {
    0: '\\mathtt{""}',
    1: '\\mathrm{string}\\left(${args[0]}\\right)'
  },
  bignumber: {
    0: '0',
    1: '\\left(${args[0]}\\right)'
  },
  bigint: {
    0: '0',
    1: '\\left(${args[0]}\\right)'
  },
  complex: {
    0: '0',
    1: '\\left(${args[0]}\\right)',
    2: "\\left(\\left(${args[0]}\\right)+".concat(latexSymbols.i, "\\cdot\\left(${args[1]}\\right)\\right)")
  },
  matrix: {
    0: '\\begin{bmatrix}\\end{bmatrix}',
    1: '\\left(${args[0]}\\right)',
    2: '\\left(${args[0]}\\right)'
  },
  sparse: {
    0: '\\begin{bsparse}\\end{bsparse}',
    1: '\\left(${args[0]}\\right)'
  },
  unit: {
    1: '\\left(${args[0]}\\right)',
    2: '\\left(\\left(${args[0]}\\right)${args[1]}\\right)'
  }
};
var defaultTemplate = '\\mathrm{${name}}\\left(${args}\\right)';
var latexUnits = {
  deg: '^\\circ'
};
function escapeLatex(string) {
  return dist(string, {
    preserveFormatting: true
  });
}

// @param {string} name
// @param {boolean} isUnit
function toSymbol(name, isUnit) {
  isUnit = typeof isUnit === 'undefined' ? false : isUnit;
  if (isUnit) {
    if (hasOwnProperty(latexUnits, name)) {
      return latexUnits[name];
    }
    return '\\mathrm{' + escapeLatex(name) + '}';
  }
  if (hasOwnProperty(latexSymbols, name)) {
    return latexSymbols[name];
  }
  return escapeLatex(name);
}

var name$1B = 'ConstantNode';
var dependencies$1B = ['Node'];
var createConstantNode = /* #__PURE__ */factory(name$1B, dependencies$1B, _ref => {
  var {
    Node
  } = _ref;
  class ConstantNode extends Node {
    /**
     * A ConstantNode holds a constant value like a number or string.
     *
     * Usage:
     *
     *     new ConstantNode(2.3)
     *     new ConstantNode('hello')
     *
     * @param {*} value    Value can be any type (number, BigNumber, bigint, string, ...)
     * @constructor ConstantNode
     * @extends {Node}
     */
    constructor(value) {
      super();
      this.value = value;
    }
    get type() {
      return name$1B;
    }
    get isConstantNode() {
      return true;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      var value = this.value;
      return function evalConstantNode() {
        return value;
      };
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      // nothing to do, we don't have any children
    }

    /**
     * Create a new ConstantNode with children produced by the given callback.
     * Trivial because there are no children.
     * @param {function(child: Node, path: string, parent: Node) : Node} callback
     * @returns {ConstantNode} Returns a clone of the node
     */
    map(callback) {
      return this.clone();
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {ConstantNode}
     */
    clone() {
      return new ConstantNode(this.value);
    }

    /**
     * Get string representation
     * @param {Object} options
     * @return {string} str
     */
    _toString(options) {
      return format(this.value, options);
    }

    /**
     * Get HTML representation
     * @param {Object} options
     * @return {string} str
     */
    _toHTML(options) {
      var value = this._toString(options);
      switch (typeOf(this.value)) {
        case 'number':
        case 'bigint':
        case 'BigNumber':
        case 'Fraction':
          return '<span class="math-number">' + value + '</span>';
        case 'string':
          return '<span class="math-string">' + value + '</span>';
        case 'boolean':
          return '<span class="math-boolean">' + value + '</span>';
        case 'null':
          return '<span class="math-null-symbol">' + value + '</span>';
        case 'undefined':
          return '<span class="math-undefined">' + value + '</span>';
        default:
          return '<span class="math-symbol">' + value + '</span>';
      }
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      return {
        mathjs: name$1B,
        value: this.value
      };
    }

    /**
     * Instantiate a ConstantNode from its JSON representation
     * @param {Object} json  An object structured like
     *                       `{"mathjs": "SymbolNode", value: 2.3}`,
     *                       where mathjs is optional
     * @returns {ConstantNode}
     */
    static fromJSON(json) {
      return new ConstantNode(json.value);
    }

    /**
     * Get LaTeX representation
     * @param {Object} options
     * @return {string} str
     */
    _toTex(options) {
      var value = this._toString(options);
      var type = typeOf(this.value);
      switch (type) {
        case 'string':
          return '\\mathtt{' + escapeLatex(value) + '}';
        case 'number':
        case 'BigNumber':
          {
            var finite = type === 'BigNumber' ? this.value.isFinite() : isFinite(this.value);
            if (!finite) {
              return this.value.valueOf() < 0 ? '-\\infty' : '\\infty';
            }
            var index = value.toLowerCase().indexOf('e');
            if (index !== -1) {
              return value.substring(0, index) + '\\cdot10^{' + value.substring(index + 1) + '}';
            }
            return value;
          }
        case 'bigint':
          {
            return value.toString();
          }
        case 'Fraction':
          return this.value.toLatex();
        default:
          return value;
      }
    }
  }
  _defineProperty(ConstantNode, "name", name$1B);
  return ConstantNode;
}, {
  isClass: true,
  isNode: true
});

var name$1A = 'FunctionAssignmentNode';
var dependencies$1A = ['typed', 'Node'];
var createFunctionAssignmentNode = /* #__PURE__ */factory(name$1A, dependencies$1A, _ref => {
  var {
    typed,
    Node
  } = _ref;
  /**
   * Is parenthesis needed?
   * @param {Node} node
   * @param {Object} parenthesis
   * @param {string} implicit
   * @private
   */
  function needParenthesis(node, parenthesis, implicit) {
    var precedence = getPrecedence(node, parenthesis, implicit);
    var exprPrecedence = getPrecedence(node.expr, parenthesis, implicit);
    return parenthesis === 'all' || exprPrecedence !== null && exprPrecedence <= precedence;
  }
  class FunctionAssignmentNode extends Node {
    /**
     * @constructor FunctionAssignmentNode
     * @extends {Node}
     * Function assignment
     *
     * @param {string} name           Function name
     * @param {string[] | Array.<{name: string, type: string}>} params
     *                                Array with function parameter names, or an
     *                                array with objects containing the name
     *                                and type of the parameter
     * @param {Node} expr             The function expression
     */
    constructor(name, params, expr) {
      super();
      // validate input
      if (typeof name !== 'string') {
        throw new TypeError('String expected for parameter "name"');
      }
      if (!Array.isArray(params)) {
        throw new TypeError('Array containing strings or objects expected for parameter "params"');
      }
      if (!isNode(expr)) {
        throw new TypeError('Node expected for parameter "expr"');
      }
      if (keywords.has(name)) {
        throw new Error('Illegal function name, "' + name + '" is a reserved keyword');
      }
      var paramNames = new Set();
      for (var param of params) {
        var _name = typeof param === 'string' ? param : param.name;
        if (paramNames.has(_name)) {
          throw new Error("Duplicate parameter name \"".concat(_name, "\""));
        } else {
          paramNames.add(_name);
        }
      }
      this.name = name;
      this.params = params.map(function (param) {
        return param && param.name || param;
      });
      this.types = params.map(function (param) {
        return param && param.type || 'any';
      });
      this.expr = expr;
    }
    get type() {
      return name$1A;
    }
    get isFunctionAssignmentNode() {
      return true;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      var childArgNames = Object.create(argNames);
      forEach(this.params, function (param) {
        childArgNames[param] = true;
      });

      // compile the function expression with the child args
      var evalExpr = this.expr._compile(math, childArgNames);
      var name = this.name;
      var params = this.params;
      var signature = join(this.types, ',');
      var syntax = name + '(' + join(this.params, ', ') + ')';
      return function evalFunctionAssignmentNode(scope, args, context) {
        var signatures = {};
        signatures[signature] = function () {
          var childArgs = Object.create(args);
          for (var i = 0; i < params.length; i++) {
            childArgs[params[i]] = arguments[i];
          }
          return evalExpr(scope, childArgs, context);
        };
        var fn = typed(name, signatures);
        fn.syntax = syntax;
        scope.set(name, fn);
        return fn;
      };
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      callback(this.expr, 'expr', this);
    }

    /**
     * Create a new FunctionAssignmentNode whose children are the results of
     * calling the provided callback function for each child of the original
     * node.
     * @param {function(child: Node, path: string, parent: Node): Node} callback
     * @returns {FunctionAssignmentNode} Returns a transformed copy of the node
     */
    map(callback) {
      var expr = this._ifNode(callback(this.expr, 'expr', this));
      return new FunctionAssignmentNode(this.name, this.params.slice(0), expr);
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {FunctionAssignmentNode}
     */
    clone() {
      return new FunctionAssignmentNode(this.name, this.params.slice(0), this.expr);
    }

    /**
     * get string representation
     * @param {Object} options
     * @return {string} str
     */
    _toString(options) {
      var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
      var expr = this.expr.toString(options);
      if (needParenthesis(this, parenthesis, options && options.implicit)) {
        expr = '(' + expr + ')';
      }
      return this.name + '(' + this.params.join(', ') + ') = ' + expr;
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      var types = this.types;
      return {
        mathjs: name$1A,
        name: this.name,
        params: this.params.map(function (param, index) {
          return {
            name: param,
            type: types[index]
          };
        }),
        expr: this.expr
      };
    }

    /**
     * Instantiate an FunctionAssignmentNode from its JSON representation
     * @param {Object} json
     *     An object structured like
     *     ```
     *     {"mathjs": "FunctionAssignmentNode",
     *      name: ..., params: ..., expr: ...}
     *     ```
     *     where mathjs is optional
     * @returns {FunctionAssignmentNode}
     */
    static fromJSON(json) {
      return new FunctionAssignmentNode(json.name, json.params, json.expr);
    }

    /**
     * get HTML representation
     * @param {Object} options
     * @return {string} str
     */
    _toHTML(options) {
      var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
      var params = [];
      for (var i = 0; i < this.params.length; i++) {
        params.push('<span class="math-symbol math-parameter">' + escape(this.params[i]) + '</span>');
      }
      var expr = this.expr.toHTML(options);
      if (needParenthesis(this, parenthesis, options && options.implicit)) {
        expr = '<span class="math-parenthesis math-round-parenthesis">(</span>' + expr + '<span class="math-parenthesis math-round-parenthesis">)</span>';
      }
      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;
    }

    /**
     * get LaTeX representation
     * @param {Object} options
     * @return {string} str
     */
    _toTex(options) {
      var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
      var expr = this.expr.toTex(options);
      if (needParenthesis(this, parenthesis, options && options.implicit)) {
        expr = "\\left(".concat(expr, "\\right)");
      }
      return '\\mathrm{' + this.name + '}\\left(' + this.params.map(toSymbol).join(',') + '\\right)=' + expr;
    }
  }
  _defineProperty(FunctionAssignmentNode, "name", name$1A);
  return FunctionAssignmentNode;
}, {
  isClass: true,
  isNode: true
});

var name$1z = 'IndexNode';
var dependencies$1z = ['Node', 'size'];
var createIndexNode = /* #__PURE__ */factory(name$1z, dependencies$1z, _ref => {
  var {
    Node,
    size
  } = _ref;
  class IndexNode extends Node {
    /**
     * @constructor IndexNode
     * @extends Node
     *
     * Describes a subset of a matrix or an object property.
     * Cannot be used on its own, needs to be used within an AccessorNode or
     * AssignmentNode.
     *
     * @param {Node[]} dimensions
     * @param {boolean} [dotNotation=false]
     *     Optional property describing whether this index was written using dot
     *     notation like `a.b`, or using bracket notation like `a["b"]`
     *     (which is the default). This property is used for string conversion.
     */
    constructor(dimensions, dotNotation) {
      super();
      this.dimensions = dimensions;
      this.dotNotation = dotNotation || false;

      // validate input
      if (!Array.isArray(dimensions) || !dimensions.every(isNode)) {
        throw new TypeError('Array containing Nodes expected for parameter "dimensions"');
      }
      if (this.dotNotation && !this.isObjectProperty()) {
        throw new Error('dotNotation only applicable for object properties');
      }
    }
    get type() {
      return name$1z;
    }
    get isIndexNode() {
      return true;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      // TODO: implement support for bignumber (currently bignumbers are silently
      //       reduced to numbers when changing the value to zero-based)

      // TODO: Optimization: when the range values are ConstantNodes,
      //       we can beforehand resolve the zero-based value

      // optimization for a simple object property
      var evalDimensions = map(this.dimensions, function (dimension, i) {
        var needsEnd = dimension.filter(node => node.isSymbolNode && node.name === 'end').length > 0;
        if (needsEnd) {
          // SymbolNode 'end' is used inside the index,
          // like in `A[end]` or `A[end - 2]`
          var childArgNames = Object.create(argNames);
          childArgNames.end = true;
          var _evalDimension = dimension._compile(math, childArgNames);
          return function evalDimension(scope, args, context) {
            if (!isMatrix(context) && !isArray(context) && !isString(context)) {
              throw new TypeError('Cannot resolve "end": ' + 'context must be a Matrix, Array, or string but is ' + typeOf(context));
            }
            var s = size(context).valueOf();
            var childArgs = Object.create(args);
            childArgs.end = s[i];
            return _evalDimension(scope, childArgs, context);
          };
        } else {
          // SymbolNode `end` not used
          return dimension._compile(math, argNames);
        }
      });
      var index = getSafeProperty(math, 'index');
      return function evalIndexNode(scope, args, context) {
        var dimensions = map(evalDimensions, function (evalDimension) {
          return evalDimension(scope, args, context);
        });
        return index(...dimensions);
      };
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      for (var i = 0; i < this.dimensions.length; i++) {
        callback(this.dimensions[i], 'dimensions[' + i + ']', this);
      }
    }

    /**
     * Create a new IndexNode whose children are the results of calling
     * the provided callback function for each child of the original node.
     * @param {function(child: Node, path: string, parent: Node): Node} callback
     * @returns {IndexNode} Returns a transformed copy of the node
     */
    map(callback) {
      var dimensions = [];
      for (var i = 0; i < this.dimensions.length; i++) {
        dimensions[i] = this._ifNode(callback(this.dimensions[i], 'dimensions[' + i + ']', this));
      }
      return new IndexNode(dimensions, this.dotNotation);
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {IndexNode}
     */
    clone() {
      return new IndexNode(this.dimensions.slice(0), this.dotNotation);
    }

    /**
     * Test whether this IndexNode contains a single property name
     * @return {boolean}
     */
    isObjectProperty() {
      return this.dimensions.length === 1 && isConstantNode(this.dimensions[0]) && typeof this.dimensions[0].value === 'string';
    }

    /**
     * Returns the property name if IndexNode contains a property.
     * If not, returns null.
     * @return {string | null}
     */
    getObjectProperty() {
      return this.isObjectProperty() ? this.dimensions[0].value : null;
    }

    /**
     * Get string representation
     * @param {Object} options
     * @return {string} str
     */
    _toString(options) {
      // format the parameters like "[1, 0:5]"
      return this.dotNotation ? '.' + this.getObjectProperty() : '[' + this.dimensions.join(', ') + ']';
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      return {
        mathjs: name$1z,
        dimensions: this.dimensions,
        dotNotation: this.dotNotation
      };
    }

    /**
     * Instantiate an IndexNode from its JSON representation
     * @param {Object} json
     *     An object structured like
     *     `{"mathjs": "IndexNode", dimensions: [...], dotNotation: false}`,
     *     where mathjs is optional
     * @returns {IndexNode}
     */
    static fromJSON(json) {
      return new IndexNode(json.dimensions, json.dotNotation);
    }

    /**
     * Get HTML representation
     * @param {Object} options
     * @return {string} str
     */
    _toHTML(options) {
      // format the parameters like "[1, 0:5]"
      var dimensions = [];
      for (var i = 0; i < this.dimensions.length; i++) {
        dimensions[i] = this.dimensions[i].toHTML();
      }
      if (this.dotNotation) {
        return '<span class="math-operator math-accessor-operator">.</span>' + '<span class="math-symbol math-property">' + escape(this.getObjectProperty()) + '</span>';
      } else {
        return '<span class="math-parenthesis math-square-parenthesis">[</span>' + dimensions.join('<span class="math-separator">,</span>') + '<span class="math-parenthesis math-square-parenthesis">]</span>';
      }
    }

    /**
     * Get LaTeX representation
     * @param {Object} options
     * @return {string} str
     */
    _toTex(options) {
      var dimensions = this.dimensions.map(function (range) {
        return range.toTex(options);
      });
      return this.dotNotation ? '.' + this.getObjectProperty() + '' : '_{' + dimensions.join(',') + '}';
    }
  }
  _defineProperty(IndexNode, "name", name$1z);
  return IndexNode;
}, {
  isClass: true,
  isNode: true
});

var name$1y = 'ObjectNode';
var dependencies$1y = ['Node'];
var createObjectNode = /* #__PURE__ */factory(name$1y, dependencies$1y, _ref => {
  var {
    Node
  } = _ref;
  class ObjectNode extends Node {
    /**
     * @constructor ObjectNode
     * @extends {Node}
     * Holds an object with keys/values
     * @param {Object.<string, Node>} [properties]   object with key/value pairs
     */
    constructor(properties) {
      super();
      this.properties = properties || {};

      // validate input
      if (properties) {
        if (!(typeof properties === 'object') || !Object.keys(properties).every(function (key) {
          return isNode(properties[key]);
        })) {
          throw new TypeError('Object containing Nodes expected');
        }
      }
    }
    get type() {
      return name$1y;
    }
    get isObjectNode() {
      return true;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      var evalEntries = {};
      for (var key in this.properties) {
        if (hasOwnProperty(this.properties, key)) {
          // we stringify/parse the key here to resolve unicode characters,
          // so you cannot create a key like {"co\\u006Estructor": null}
          var stringifiedKey = stringify(key);
          var parsedKey = JSON.parse(stringifiedKey);
          var prop = getSafeProperty(this.properties, key);
          evalEntries[parsedKey] = prop._compile(math, argNames);
        }
      }
      return function evalObjectNode(scope, args, context) {
        var obj = {};
        for (var _key in evalEntries) {
          if (hasOwnProperty(evalEntries, _key)) {
            obj[_key] = evalEntries[_key](scope, args, context);
          }
        }
        return obj;
      };
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      for (var key in this.properties) {
        if (hasOwnProperty(this.properties, key)) {
          callback(this.properties[key], 'properties[' + stringify(key) + ']', this);
        }
      }
    }

    /**
     * Create a new ObjectNode whose children are the results of calling
     * the provided callback function for each child of the original node.
     * @param {function(child: Node, path: string, parent: Node): Node} callback
     * @returns {ObjectNode} Returns a transformed copy of the node
     */
    map(callback) {
      var properties = {};
      for (var key in this.properties) {
        if (hasOwnProperty(this.properties, key)) {
          properties[key] = this._ifNode(callback(this.properties[key], 'properties[' + stringify(key) + ']', this));
        }
      }
      return new ObjectNode(properties);
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {ObjectNode}
     */
    clone() {
      var properties = {};
      for (var key in this.properties) {
        if (hasOwnProperty(this.properties, key)) {
          properties[key] = this.properties[key];
        }
      }
      return new ObjectNode(properties);
    }

    /**
     * Get string representation
     * @param {Object} options
     * @return {string} str
     * @override
     */
    _toString(options) {
      var entries = [];
      for (var key in this.properties) {
        if (hasOwnProperty(this.properties, key)) {
          entries.push(stringify(key) + ': ' + this.properties[key].toString(options));
        }
      }
      return '{' + entries.join(', ') + '}';
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      return {
        mathjs: name$1y,
        properties: this.properties
      };
    }

    /**
     * Instantiate an OperatorNode from its JSON representation
     * @param {Object} json  An object structured like
     *                       `{"mathjs": "ObjectNode", "properties": {...}}`,
     *                       where mathjs is optional
     * @returns {ObjectNode}
     */
    static fromJSON(json) {
      return new ObjectNode(json.properties);
    }

    /**
     * Get HTML representation
     * @param {Object} options
     * @return {string} str
     * @override
     */
    _toHTML(options) {
      var entries = [];
      for (var key in this.properties) {
        if (hasOwnProperty(this.properties, key)) {
          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));
        }
      }
      return '<span class="math-parenthesis math-curly-parenthesis">{</span>' + entries.join('<span class="math-separator">,</span>') + '<span class="math-parenthesis math-curly-parenthesis">}</span>';
    }

    /**
     * Get LaTeX representation
     * @param {Object} options
     * @return {string} str
     */
    _toTex(options) {
      var entries = [];
      for (var key in this.properties) {
        if (hasOwnProperty(this.properties, key)) {
          entries.push('\\mathbf{' + key + ':} & ' + this.properties[key].toTex(options) + '\\\\');
        }
      }
      var tex = '\\left\\{\\begin{array}{ll}' + entries.join('\n') + '\\end{array}\\right\\}';
      return tex;
    }
  }
  _defineProperty(ObjectNode, "name", name$1y);
  return ObjectNode;
}, {
  isClass: true,
  isNode: true
});

/**
 * Create a new scope which can access the parent scope,
 * but does not affect it when written. This is suitable for variable definitions
 * within a block node, or function definition.
 *
 * If parent scope has a createSubScope method, it delegates to that. Otherwise,
 * creates an empty map, and copies the parent scope to it, adding in
 * the remaining `args`.
 *
 * @param {Map} parentScope
 * @param  {Object} args
 * @returns {PartitionedMap}
 */
function createSubScope(parentScope, args) {
  return new PartitionedMap(parentScope, new ObjectWrappingMap(args), new Set(Object.keys(args)));
}

var name$1x = 'OperatorNode';
var dependencies$1x = ['Node'];
var createOperatorNode = /* #__PURE__ */factory(name$1x, dependencies$1x, _ref => {
  var {
    Node
  } = _ref;
  /**
   * Returns true if the expression starts with a constant, under
   * the current parenthesization:
   * @param {Node} expression
   * @param {string} parenthesis
   * @return {boolean}
   */
  function startsWithConstant(expr, parenthesis) {
    var curNode = expr;
    if (parenthesis === 'auto') {
      while (isParenthesisNode(curNode)) curNode = curNode.content;
    }
    if (isConstantNode(curNode)) return true;
    if (isOperatorNode(curNode)) {
      return startsWithConstant(curNode.args[0], parenthesis);
    }
    return false;
  }

  /**
   * Calculate which parentheses are necessary. Gets an OperatorNode
   * (which is the root of the tree) and an Array of Nodes
   * (this.args) and returns an array where 'true' means that an argument
   * has to be enclosed in parentheses whereas 'false' means the opposite.
   *
   * @param {OperatorNode} root
   * @param {string} parenthesis
   * @param {Node[]} args
   * @param {boolean} latex
   * @return {boolean[]}
   * @private
   */
  function calculateNecessaryParentheses(root, parenthesis, implicit, args, latex) {
    // precedence of the root OperatorNode
    var precedence = getPrecedence(root, parenthesis, implicit);
    var associativity = getAssociativity(root, parenthesis);
    if (parenthesis === 'all' || args.length > 2 && root.getIdentifier() !== 'OperatorNode:add' && root.getIdentifier() !== 'OperatorNode:multiply') {
      return args.map(function (arg) {
        switch (arg.getContent().type) {
          // Nodes that don't need extra parentheses
          case 'ArrayNode':
          case 'ConstantNode':
          case 'SymbolNode':
          case 'ParenthesisNode':
            return false;
          default:
            return true;
        }
      });
    }
    var result;
    switch (args.length) {
      case 0:
        result = [];
        break;
      case 1:
        // unary operators
        {
          // precedence of the operand
          var operandPrecedence = getPrecedence(args[0], parenthesis, implicit, root);

          // handle special cases for LaTeX, where some of the parentheses aren't needed
          if (latex && operandPrecedence !== null) {
            var operandIdentifier;
            var rootIdentifier;
            if (parenthesis === 'keep') {
              operandIdentifier = args[0].getIdentifier();
              rootIdentifier = root.getIdentifier();
            } else {
              // Ignore Parenthesis Nodes when not in 'keep' mode
              operandIdentifier = args[0].getContent().getIdentifier();
              rootIdentifier = root.getContent().getIdentifier();
            }
            if (properties[precedence][rootIdentifier].latexLeftParens === false) {
              result = [false];
              break;
            }
            if (properties[operandPrecedence][operandIdentifier].latexParens === false) {
              result = [false];
              break;
            }
          }
          if (operandPrecedence === null) {
            // if the operand has no defined precedence, no parens are needed
            result = [false];
            break;
          }
          if (operandPrecedence <= precedence) {
            // if the operands precedence is lower, parens are needed
            result = [true];
            break;
          }

          // otherwise, no parens needed
          result = [false];
        }
        break;
      case 2:
        // binary operators
        {
          var lhsParens; // left hand side needs parenthesis?
          // precedence of the left hand side
          var lhsPrecedence = getPrecedence(args[0], parenthesis, implicit, root);
          // is the root node associative with the left hand side
          var assocWithLhs = isAssociativeWith(root, args[0], parenthesis);
          if (lhsPrecedence === null) {
            // if the left hand side has no defined precedence, no parens are needed
            // FunctionNode for example
            lhsParens = false;
          } else if (lhsPrecedence === precedence && associativity === 'right' && !assocWithLhs) {
            // In case of equal precedence, if the root node is left associative
            // parens are **never** necessary for the left hand side.
            // If it is right associative however, parens are necessary
            // if the root node isn't associative with the left hand side
            lhsParens = true;
          } else if (lhsPrecedence < precedence) {
            lhsParens = true;
          } else {
            lhsParens = false;
          }
          var rhsParens; // right hand side needs parenthesis?
          // precedence of the right hand side
          var rhsPrecedence = getPrecedence(args[1], parenthesis, implicit, root);
          // is the root node associative with the right hand side?
          var assocWithRhs = isAssociativeWith(root, args[1], parenthesis);
          if (rhsPrecedence === null) {
            // if the right hand side has no defined precedence, no parens are needed
            // FunctionNode for example
            rhsParens = false;
          } else if (rhsPrecedence === precedence && associativity === 'left' && !assocWithRhs) {
            // In case of equal precedence, if the root node is right associative
            // parens are **never** necessary for the right hand side.
            // If it is left associative however, parens are necessary
            // if the root node isn't associative with the right hand side
            rhsParens = true;
          } else if (rhsPrecedence < precedence) {
            rhsParens = true;
          } else {
            rhsParens = false;
          }

          // handle special cases for LaTeX, where some of the parentheses aren't needed
          if (latex) {
            var _rootIdentifier;
            var lhsIdentifier;
            var rhsIdentifier;
            if (parenthesis === 'keep') {
              _rootIdentifier = root.getIdentifier();
              lhsIdentifier = root.args[0].getIdentifier();
              rhsIdentifier = root.args[1].getIdentifier();
            } else {
              // Ignore ParenthesisNodes when not in 'keep' mode
              _rootIdentifier = root.getContent().getIdentifier();
              lhsIdentifier = root.args[0].getContent().getIdentifier();
              rhsIdentifier = root.args[1].getContent().getIdentifier();
            }
            if (lhsPrecedence !== null) {
              if (properties[precedence][_rootIdentifier].latexLeftParens === false) {
                lhsParens = false;
              }
              if (properties[lhsPrecedence][lhsIdentifier].latexParens === false) {
                lhsParens = false;
              }
            }
            if (rhsPrecedence !== null) {
              if (properties[precedence][_rootIdentifier].latexRightParens === false) {
                rhsParens = false;
              }
              if (properties[rhsPrecedence][rhsIdentifier].latexParens === false) {
                rhsParens = false;
              }
            }
          }
          result = [lhsParens, rhsParens];
        }
        break;
      default:
        if (root.getIdentifier() === 'OperatorNode:add' || root.getIdentifier() === 'OperatorNode:multiply') {
          result = args.map(function (arg) {
            var argPrecedence = getPrecedence(arg, parenthesis, implicit, root);
            var assocWithArg = isAssociativeWith(root, arg, parenthesis);
            var argAssociativity = getAssociativity(arg, parenthesis);
            if (argPrecedence === null) {
              // if the argument has no defined precedence, no parens are needed
              return false;
            } else if (precedence === argPrecedence && associativity === argAssociativity && !assocWithArg) {
              return true;
            } else if (argPrecedence < precedence) {
              return true;
            }
            return false;
          });
        }
        break;
    }

    // Handles an edge case of parentheses with implicit multiplication
    // of ConstantNode.
    // In that case, parenthesize ConstantNodes that follow an unparenthesized
    // expression, even though they normally wouldn't be printed.
    if (args.length >= 2 && root.getIdentifier() === 'OperatorNode:multiply' && root.implicit && parenthesis !== 'all' && implicit === 'hide') {
      for (var i = 1; i < result.length; ++i) {
        if (startsWithConstant(args[i], parenthesis) && !result[i - 1] && (parenthesis !== 'keep' || !isParenthesisNode(args[i - 1]))) {
          result[i] = true;
        }
      }
    }
    return result;
  }
  class OperatorNode extends Node {
    /**
     * @constructor OperatorNode
     * @extends {Node}
     * An operator with two arguments, like 2+3
     *
     * @param {string} op           Operator name, for example '+'
     * @param {string} fn           Function name, for example 'add'
     * @param {Node[]} args         Operator arguments
     * @param {boolean} [implicit]  Is this an implicit multiplication?
     * @param {boolean} [isPercentage] Is this an percentage Operation?
     */
    constructor(op, fn, args, implicit, isPercentage) {
      super();
      // validate input
      if (typeof op !== 'string') {
        throw new TypeError('string expected for parameter "op"');
      }
      if (typeof fn !== 'string') {
        throw new TypeError('string expected for parameter "fn"');
      }
      if (!Array.isArray(args) || !args.every(isNode)) {
        throw new TypeError('Array containing Nodes expected for parameter "args"');
      }
      this.implicit = implicit === true;
      this.isPercentage = isPercentage === true;
      this.op = op;
      this.fn = fn;
      this.args = args || [];
    }
    get type() {
      return name$1x;
    }
    get isOperatorNode() {
      return true;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      // validate fn
      if (typeof this.fn !== 'string' || !isSafeMethod(math, this.fn)) {
        if (!math[this.fn]) {
          throw new Error('Function ' + this.fn + ' missing in provided namespace "math"');
        } else {
          throw new Error('No access to function "' + this.fn + '"');
        }
      }
      var fn = getSafeProperty(math, this.fn);
      var evalArgs = map(this.args, function (arg) {
        return arg._compile(math, argNames);
      });
      if (typeof fn === 'function' && fn.rawArgs === true) {
        // pass unevaluated parameters (nodes) to the function
        // "raw" evaluation
        var rawArgs = this.args;
        return function evalOperatorNode(scope, args, context) {
          return fn(rawArgs, math, createSubScope(scope, args));
        };
      } else if (evalArgs.length === 1) {
        var evalArg0 = evalArgs[0];
        return function evalOperatorNode(scope, args, context) {
          return fn(evalArg0(scope, args, context));
        };
      } else if (evalArgs.length === 2) {
        var _evalArg = evalArgs[0];
        var evalArg1 = evalArgs[1];
        return function evalOperatorNode(scope, args, context) {
          return fn(_evalArg(scope, args, context), evalArg1(scope, args, context));
        };
      } else {
        return function evalOperatorNode(scope, args, context) {
          return fn.apply(null, map(evalArgs, function (evalArg) {
            return evalArg(scope, args, context);
          }));
        };
      }
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      for (var i = 0; i < this.args.length; i++) {
        callback(this.args[i], 'args[' + i + ']', this);
      }
    }

    /**
     * Create a new OperatorNode whose children are the results of calling
     * the provided callback function for each child of the original node.
     * @param {function(child: Node, path: string, parent: Node): Node} callback
     * @returns {OperatorNode} Returns a transformed copy of the node
     */
    map(callback) {
      var args = [];
      for (var i = 0; i < this.args.length; i++) {
        args[i] = this._ifNode(callback(this.args[i], 'args[' + i + ']', this));
      }
      return new OperatorNode(this.op, this.fn, args, this.implicit, this.isPercentage);
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {OperatorNode}
     */
    clone() {
      return new OperatorNode(this.op, this.fn, this.args.slice(0), this.implicit, this.isPercentage);
    }

    /**
     * Check whether this is an unary OperatorNode:
     * has exactly one argument, like `-a`.
     * @return {boolean}
     *     Returns true when an unary operator node, false otherwise.
     */
    isUnary() {
      return this.args.length === 1;
    }

    /**
     * Check whether this is a binary OperatorNode:
     * has exactly two arguments, like `a + b`.
     * @return {boolean}
     *     Returns true when a binary operator node, false otherwise.
     */
    isBinary() {
      return this.args.length === 2;
    }

    /**
     * Get string representation.
     * @param {Object} options
     * @return {string} str
     */
    _toString(options) {
      var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
      var implicit = options && options.implicit ? options.implicit : 'hide';
      var args = this.args;
      var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, false);
      if (args.length === 1) {
        // unary operators
        var assoc = getAssociativity(this, parenthesis);
        var operand = args[0].toString(options);
        if (parens[0]) {
          operand = '(' + operand + ')';
        }

        // for example for "not", we want a space between operand and argument
        var opIsNamed = /[a-zA-Z]+/.test(this.op);
        if (assoc === 'right') {
          // prefix operator
          return this.op + (opIsNamed ? ' ' : '') + operand;
        } else if (assoc === 'left') {
          // postfix
          return operand + (opIsNamed ? ' ' : '') + this.op;
        }

        // fall back to postfix
        return operand + this.op;
      } else if (args.length === 2) {
        var lhs = args[0].toString(options); // left hand side
        var rhs = args[1].toString(options); // right hand side
        if (parens[0]) {
          // left hand side in parenthesis?
          lhs = '(' + lhs + ')';
        }
        if (parens[1]) {
          // right hand side in parenthesis?
          rhs = '(' + rhs + ')';
        }
        if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') {
          return lhs + ' ' + rhs;
        }
        return lhs + ' ' + this.op + ' ' + rhs;
      } else if (args.length > 2 && (this.getIdentifier() === 'OperatorNode:add' || this.getIdentifier() === 'OperatorNode:multiply')) {
        var stringifiedArgs = args.map(function (arg, index) {
          arg = arg.toString(options);
          if (parens[index]) {
            // put in parenthesis?
            arg = '(' + arg + ')';
          }
          return arg;
        });
        if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') {
          return stringifiedArgs.join(' ');
        }
        return stringifiedArgs.join(' ' + this.op + ' ');
      } else {
        // fallback to formatting as a function call
        return this.fn + '(' + this.args.join(', ') + ')';
      }
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      return {
        mathjs: name$1x,
        op: this.op,
        fn: this.fn,
        args: this.args,
        implicit: this.implicit,
        isPercentage: this.isPercentage
      };
    }

    /**
     * Instantiate an OperatorNode from its JSON representation
     * @param {Object} json
     *     An object structured like
     *     ```
     *     {"mathjs": "OperatorNode",
     *      "op": "+", "fn": "add", "args": [...],
     *      "implicit": false,
     *      "isPercentage":false}
     *     ```
     *     where mathjs is optional
     * @returns {OperatorNode}
     */
    static fromJSON(json) {
      return new OperatorNode(json.op, json.fn, json.args, json.implicit, json.isPercentage);
    }

    /**
     * Get HTML representation.
     * @param {Object} options
     * @return {string} str
     */
    _toHTML(options) {
      var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
      var implicit = options && options.implicit ? options.implicit : 'hide';
      var args = this.args;
      var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, false);
      if (args.length === 1) {
        // unary operators
        var assoc = getAssociativity(this, parenthesis);
        var operand = args[0].toHTML(options);
        if (parens[0]) {
          operand = '<span class="math-parenthesis math-round-parenthesis">(</span>' + operand + '<span class="math-parenthesis math-round-parenthesis">)</span>';
        }
        if (assoc === 'right') {
          // prefix operator
          return '<span class="math-operator math-unary-operator ' + 'math-lefthand-unary-operator">' + escape(this.op) + '</span>' + operand;
        } else {
          // postfix when assoc === 'left' or undefined
          return operand + '<span class="math-operator math-unary-operator ' + 'math-righthand-unary-operator">' + escape(this.op) + '</span>';
        }
      } else if (args.length === 2) {
        // binary operatoes
        var lhs = args[0].toHTML(options); // left hand side
        var rhs = args[1].toHTML(options); // right hand side
        if (parens[0]) {
          // left hand side in parenthesis?
          lhs = '<span class="math-parenthesis math-round-parenthesis">(</span>' + lhs + '<span class="math-parenthesis math-round-parenthesis">)</span>';
        }
        if (parens[1]) {
          // right hand side in parenthesis?
          rhs = '<span class="math-parenthesis math-round-parenthesis">(</span>' + rhs + '<span class="math-parenthesis math-round-parenthesis">)</span>';
        }
        if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') {
          return lhs + '<span class="math-operator math-binary-operator ' + 'math-implicit-binary-operator"></span>' + rhs;
        }
        return lhs + '<span class="math-operator math-binary-operator ' + 'math-explicit-binary-operator">' + escape(this.op) + '</span>' + rhs;
      } else {
        var stringifiedArgs = args.map(function (arg, index) {
          arg = arg.toHTML(options);
          if (parens[index]) {
            // put in parenthesis?
            arg = '<span class="math-parenthesis math-round-parenthesis">(</span>' + arg + '<span class="math-parenthesis math-round-parenthesis">)</span>';
          }
          return arg;
        });
        if (args.length > 2 && (this.getIdentifier() === 'OperatorNode:add' || this.getIdentifier() === 'OperatorNode:multiply')) {
          if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') {
            return stringifiedArgs.join('<span class="math-operator math-binary-operator ' + 'math-implicit-binary-operator"></span>');
          }
          return stringifiedArgs.join('<span class="math-operator math-binary-operator ' + 'math-explicit-binary-operator">' + escape(this.op) + '</span>');
        } else {
          // fallback to formatting as a function call
          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>';
        }
      }
    }

    /**
     * Get LaTeX representation
     * @param {Object} options
     * @return {string} str
     */
    _toTex(options) {
      var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
      var implicit = options && options.implicit ? options.implicit : 'hide';
      var args = this.args;
      var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, true);
      var op = latexOperators[this.fn];
      op = typeof op === 'undefined' ? this.op : op; // fall back to using this.op

      if (args.length === 1) {
        // unary operators
        var assoc = getAssociativity(this, parenthesis);
        var operand = args[0].toTex(options);
        if (parens[0]) {
          operand = "\\left(".concat(operand, "\\right)");
        }
        if (assoc === 'right') {
          // prefix operator
          return op + operand;
        } else if (assoc === 'left') {
          // postfix operator
          return operand + op;
        }

        // fall back to postfix
        return operand + op;
      } else if (args.length === 2) {
        // binary operators
        var lhs = args[0]; // left hand side
        var lhsTex = lhs.toTex(options);
        if (parens[0]) {
          lhsTex = "\\left(".concat(lhsTex, "\\right)");
        }
        var rhs = args[1]; // right hand side
        var rhsTex = rhs.toTex(options);
        if (parens[1]) {
          rhsTex = "\\left(".concat(rhsTex, "\\right)");
        }

        // handle some exceptions (due to the way LaTeX works)
        var lhsIdentifier;
        if (parenthesis === 'keep') {
          lhsIdentifier = lhs.getIdentifier();
        } else {
          // Ignore ParenthesisNodes if in 'keep' mode
          lhsIdentifier = lhs.getContent().getIdentifier();
        }
        switch (this.getIdentifier()) {
          case 'OperatorNode:divide':
            // op contains '\\frac' at this point
            return op + '{' + lhsTex + '}' + '{' + rhsTex + '}';
          case 'OperatorNode:pow':
            lhsTex = '{' + lhsTex + '}';
            rhsTex = '{' + rhsTex + '}';
            switch (lhsIdentifier) {
              case 'ConditionalNode': //
              case 'OperatorNode:divide':
                lhsTex = "\\left(".concat(lhsTex, "\\right)");
            }
            break;
          case 'OperatorNode:multiply':
            if (this.implicit && implicit === 'hide') {
              return lhsTex + '~' + rhsTex;
            }
        }
        return lhsTex + op + rhsTex;
      } else if (args.length > 2 && (this.getIdentifier() === 'OperatorNode:add' || this.getIdentifier() === 'OperatorNode:multiply')) {
        var texifiedArgs = args.map(function (arg, index) {
          arg = arg.toTex(options);
          if (parens[index]) {
            arg = "\\left(".concat(arg, "\\right)");
          }
          return arg;
        });
        if (this.getIdentifier() === 'OperatorNode:multiply' && this.implicit && implicit === 'hide') {
          return texifiedArgs.join('~');
        }
        return texifiedArgs.join(op);
      } else {
        // fall back to formatting as a function call
        // as this is a fallback, it doesn't use
        // fancy function names
        return '\\mathrm{' + this.fn + '}\\left(' + args.map(function (arg) {
          return arg.toTex(options);
        }).join(',') + '\\right)';
      }
    }

    /**
     * Get identifier.
     * @return {string}
     */
    getIdentifier() {
      return this.type + ':' + this.fn;
    }
  }
  _defineProperty(OperatorNode, "name", name$1x);
  return OperatorNode;
}, {
  isClass: true,
  isNode: true
});

var name$1w = 'ParenthesisNode';
var dependencies$1w = ['Node'];
var createParenthesisNode = /* #__PURE__ */factory(name$1w, dependencies$1w, _ref => {
  var {
    Node
  } = _ref;
  class ParenthesisNode extends Node {
    /**
     * @constructor ParenthesisNode
     * @extends {Node}
     * A parenthesis node describes manual parenthesis from the user input
     * @param {Node} content
     * @extends {Node}
     */
    constructor(content) {
      super();
      // validate input
      if (!isNode(content)) {
        throw new TypeError('Node expected for parameter "content"');
      }
      this.content = content;
    }
    get type() {
      return name$1w;
    }
    get isParenthesisNode() {
      return true;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      return this.content._compile(math, argNames);
    }

    /**
     * Get the content of the current Node.
     * @return {Node} content
     * @override
     **/
    getContent() {
      return this.content.getContent();
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      callback(this.content, 'content', this);
    }

    /**
     * Create a new ParenthesisNode whose child is the result of calling
     * the provided callback function on the child of this node.
     * @param {function(child: Node, path: string, parent: Node) : Node} callback
     * @returns {ParenthesisNode} Returns a clone of the node
     */
    map(callback) {
      var content = callback(this.content, 'content', this);
      return new ParenthesisNode(content);
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {ParenthesisNode}
     */
    clone() {
      return new ParenthesisNode(this.content);
    }

    /**
     * Get string representation
     * @param {Object} options
     * @return {string} str
     * @override
     */
    _toString(options) {
      if (!options || options && !options.parenthesis || options && options.parenthesis === 'keep') {
        return '(' + this.content.toString(options) + ')';
      }
      return this.content.toString(options);
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      return {
        mathjs: name$1w,
        content: this.content
      };
    }

    /**
     * Instantiate an ParenthesisNode from its JSON representation
     * @param {Object} json  An object structured like
     *                       `{"mathjs": "ParenthesisNode", "content": ...}`,
     *                       where mathjs is optional
     * @returns {ParenthesisNode}
     */
    static fromJSON(json) {
      return new ParenthesisNode(json.content);
    }

    /**
     * Get HTML representation
     * @param {Object} options
     * @return {string} str
     * @override
     */
    _toHTML(options) {
      if (!options || options && !options.parenthesis || options && options.parenthesis === 'keep') {
        return '<span class="math-parenthesis math-round-parenthesis">(</span>' + this.content.toHTML(options) + '<span class="math-parenthesis math-round-parenthesis">)</span>';
      }
      return this.content.toHTML(options);
    }

    /**
     * Get LaTeX representation
     * @param {Object} options
     * @return {string} str
     * @override
     */
    _toTex(options) {
      if (!options || options && !options.parenthesis || options && options.parenthesis === 'keep') {
        return "\\left(".concat(this.content.toTex(options), "\\right)");
      }
      return this.content.toTex(options);
    }
  }
  _defineProperty(ParenthesisNode, "name", name$1w);
  return ParenthesisNode;
}, {
  isClass: true,
  isNode: true
});

var name$1v = 'RangeNode';
var dependencies$1v = ['Node'];
var createRangeNode = /* #__PURE__ */factory(name$1v, dependencies$1v, _ref => {
  var {
    Node
  } = _ref;
  /**
   * Calculate the necessary parentheses
   * @param {Node} node
   * @param {string} parenthesis
   * @param {string} implicit
   * @return {Object} parentheses
   * @private
   */
  function calculateNecessaryParentheses(node, parenthesis, implicit) {
    var precedence = getPrecedence(node, parenthesis, implicit);
    var parens = {};
    var startPrecedence = getPrecedence(node.start, parenthesis, implicit);
    parens.start = startPrecedence !== null && startPrecedence <= precedence || parenthesis === 'all';
    if (node.step) {
      var stepPrecedence = getPrecedence(node.step, parenthesis, implicit);
      parens.step = stepPrecedence !== null && stepPrecedence <= precedence || parenthesis === 'all';
    }
    var endPrecedence = getPrecedence(node.end, parenthesis, implicit);
    parens.end = endPrecedence !== null && endPrecedence <= precedence || parenthesis === 'all';
    return parens;
  }
  class RangeNode extends Node {
    /**
     * @constructor RangeNode
     * @extends {Node}
     * create a range
     * @param {Node} start  included lower-bound
     * @param {Node} end    included upper-bound
     * @param {Node} [step] optional step
     */
    constructor(start, end, step) {
      super();
      // validate inputs
      if (!isNode(start)) throw new TypeError('Node expected');
      if (!isNode(end)) throw new TypeError('Node expected');
      if (step && !isNode(step)) throw new TypeError('Node expected');
      if (arguments.length > 3) throw new Error('Too many arguments');
      this.start = start; // included lower-bound
      this.end = end; // included upper-bound
      this.step = step || null; // optional step
    }
    get type() {
      return name$1v;
    }
    get isRangeNode() {
      return true;
    }

    /**
     * Check whether the RangeNode needs the `end` symbol to be defined.
     * This end is the size of the Matrix in current dimension.
     * @return {boolean}
     */
    needsEnd() {
      // find all `end` symbols in this RangeNode
      var endSymbols = this.filter(function (node) {
        return isSymbolNode(node) && node.name === 'end';
      });
      return endSymbols.length > 0;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      var range = math.range;
      var evalStart = this.start._compile(math, argNames);
      var evalEnd = this.end._compile(math, argNames);
      if (this.step) {
        var evalStep = this.step._compile(math, argNames);
        return function evalRangeNode(scope, args, context) {
          return range(evalStart(scope, args, context), evalEnd(scope, args, context), evalStep(scope, args, context));
        };
      } else {
        return function evalRangeNode(scope, args, context) {
          return range(evalStart(scope, args, context), evalEnd(scope, args, context));
        };
      }
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      callback(this.start, 'start', this);
      callback(this.end, 'end', this);
      if (this.step) {
        callback(this.step, 'step', this);
      }
    }

    /**
     * Create a new RangeNode whose children are the results of calling
     * the provided callback function for each child of the original node.
     * @param {function(child: Node, path: string, parent: Node): Node} callback
     * @returns {RangeNode} Returns a transformed copy of the node
     */
    map(callback) {
      return new RangeNode(this._ifNode(callback(this.start, 'start', this)), this._ifNode(callback(this.end, 'end', this)), this.step && this._ifNode(callback(this.step, 'step', this)));
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {RangeNode}
     */
    clone() {
      return new RangeNode(this.start, this.end, this.step && this.step);
    }

    /**
     * Get string representation
     * @param {Object} options
     * @return {string} str
     */
    _toString(options) {
      var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
      var parens = calculateNecessaryParentheses(this, parenthesis, options && options.implicit);

      // format string as start:step:stop
      var str;
      var start = this.start.toString(options);
      if (parens.start) {
        start = '(' + start + ')';
      }
      str = start;
      if (this.step) {
        var step = this.step.toString(options);
        if (parens.step) {
          step = '(' + step + ')';
        }
        str += ':' + step;
      }
      var end = this.end.toString(options);
      if (parens.end) {
        end = '(' + end + ')';
      }
      str += ':' + end;
      return str;
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      return {
        mathjs: name$1v,
        start: this.start,
        end: this.end,
        step: this.step
      };
    }

    /**
     * Instantiate an RangeNode from its JSON representation
     * @param {Object} json
     *     An object structured like
     *     `{"mathjs": "RangeNode", "start": ..., "end": ..., "step": ...}`,
     *     where mathjs is optional
     * @returns {RangeNode}
     */
    static fromJSON(json) {
      return new RangeNode(json.start, json.end, json.step);
    }

    /**
     * Get HTML representation
     * @param {Object} options
     * @return {string} str
     */
    _toHTML(options) {
      var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
      var parens = calculateNecessaryParentheses(this, parenthesis, options && options.implicit);

      // format string as start:step:stop
      var str;
      var start = this.start.toHTML(options);
      if (parens.start) {
        start = '<span class="math-parenthesis math-round-parenthesis">(</span>' + start + '<span class="math-parenthesis math-round-parenthesis">)</span>';
      }
      str = start;
      if (this.step) {
        var step = this.step.toHTML(options);
        if (parens.step) {
          step = '<span class="math-parenthesis math-round-parenthesis">(</span>' + step + '<span class="math-parenthesis math-round-parenthesis">)</span>';
        }
        str += '<span class="math-operator math-range-operator">:</span>' + step;
      }
      var end = this.end.toHTML(options);
      if (parens.end) {
        end = '<span class="math-parenthesis math-round-parenthesis">(</span>' + end + '<span class="math-parenthesis math-round-parenthesis">)</span>';
      }
      str += '<span class="math-operator math-range-operator">:</span>' + end;
      return str;
    }

    /**
     * Get LaTeX representation
     * @params {Object} options
     * @return {string} str
     */
    _toTex(options) {
      var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
      var parens = calculateNecessaryParentheses(this, parenthesis, options && options.implicit);
      var str = this.start.toTex(options);
      if (parens.start) {
        str = "\\left(".concat(str, "\\right)");
      }
      if (this.step) {
        var step = this.step.toTex(options);
        if (parens.step) {
          step = "\\left(".concat(step, "\\right)");
        }
        str += ':' + step;
      }
      var end = this.end.toTex(options);
      if (parens.end) {
        end = "\\left(".concat(end, "\\right)");
      }
      str += ':' + end;
      return str;
    }
  }
  _defineProperty(RangeNode, "name", name$1v);
  return RangeNode;
}, {
  isClass: true,
  isNode: true
});

var name$1u = 'RelationalNode';
var dependencies$1u = ['Node'];
var createRelationalNode = /* #__PURE__ */factory(name$1u, dependencies$1u, _ref => {
  var {
    Node
  } = _ref;
  var operatorMap = {
    equal: '==',
    unequal: '!=',
    smaller: '<',
    larger: '>',
    smallerEq: '<=',
    largerEq: '>='
  };
  class RelationalNode extends Node {
    /**
     * A node representing a chained conditional expression, such as 'x > y > z'
     *
     * @param {String[]} conditionals
     *     An array of conditional operators used to compare the parameters
     * @param {Node[]} params
     *     The parameters that will be compared
     *
     * @constructor RelationalNode
     * @extends {Node}
     */
    constructor(conditionals, params) {
      super();
      if (!Array.isArray(conditionals)) {
        throw new TypeError('Parameter conditionals must be an array');
      }
      if (!Array.isArray(params)) {
        throw new TypeError('Parameter params must be an array');
      }
      if (conditionals.length !== params.length - 1) {
        throw new TypeError('Parameter params must contain exactly one more element ' + 'than parameter conditionals');
      }
      this.conditionals = conditionals;
      this.params = params;
    }
    get type() {
      return name$1u;
    }
    get isRelationalNode() {
      return true;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      var self = this;
      var compiled = this.params.map(p => p._compile(math, argNames));
      return function evalRelationalNode(scope, args, context) {
        var evalLhs;
        var evalRhs = compiled[0](scope, args, context);
        for (var i = 0; i < self.conditionals.length; i++) {
          evalLhs = evalRhs;
          evalRhs = compiled[i + 1](scope, args, context);
          var condFn = getSafeProperty(math, self.conditionals[i]);
          if (!condFn(evalLhs, evalRhs)) {
            return false;
          }
        }
        return true;
      };
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      this.params.forEach((n, i) => callback(n, 'params[' + i + ']', this), this);
    }

    /**
     * Create a new RelationalNode whose children are the results of calling
     * the provided callback function for each child of the original node.
     * @param {function(child: Node, path: string, parent: Node): Node} callback
     * @returns {RelationalNode} Returns a transformed copy of the node
     */
    map(callback) {
      return new RelationalNode(this.conditionals.slice(), this.params.map((n, i) => this._ifNode(callback(n, 'params[' + i + ']', this)), this));
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {RelationalNode}
     */
    clone() {
      return new RelationalNode(this.conditionals, this.params);
    }

    /**
     * Get string representation.
     * @param {Object} options
     * @return {string} str
     */
    _toString(options) {
      var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
      var precedence = getPrecedence(this, parenthesis, options && options.implicit);
      var paramStrings = this.params.map(function (p, index) {
        var paramPrecedence = getPrecedence(p, parenthesis, options && options.implicit);
        return parenthesis === 'all' || paramPrecedence !== null && paramPrecedence <= precedence ? '(' + p.toString(options) + ')' : p.toString(options);
      });
      var ret = paramStrings[0];
      for (var i = 0; i < this.conditionals.length; i++) {
        ret += ' ' + operatorMap[this.conditionals[i]];
        ret += ' ' + paramStrings[i + 1];
      }
      return ret;
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      return {
        mathjs: name$1u,
        conditionals: this.conditionals,
        params: this.params
      };
    }

    /**
     * Instantiate a RelationalNode from its JSON representation
     * @param {Object} json
     *     An object structured like
     *     `{"mathjs": "RelationalNode", "conditionals": ..., "params": ...}`,
     *     where mathjs is optional
     * @returns {RelationalNode}
     */
    static fromJSON(json) {
      return new RelationalNode(json.conditionals, json.params);
    }

    /**
     * Get HTML representation
     * @param {Object} options
     * @return {string} str
     */
    _toHTML(options) {
      var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
      var precedence = getPrecedence(this, parenthesis, options && options.implicit);
      var paramStrings = this.params.map(function (p, index) {
        var paramPrecedence = getPrecedence(p, parenthesis, options && options.implicit);
        return parenthesis === 'all' || paramPrecedence !== null && paramPrecedence <= precedence ? '<span class="math-parenthesis math-round-parenthesis">(</span>' + p.toHTML(options) + '<span class="math-parenthesis math-round-parenthesis">)</span>' : p.toHTML(options);
      });
      var ret = paramStrings[0];
      for (var i = 0; i < this.conditionals.length; i++) {
        ret += '<span class="math-operator math-binary-operator ' + 'math-explicit-binary-operator">' + escape(operatorMap[this.conditionals[i]]) + '</span>' + paramStrings[i + 1];
      }
      return ret;
    }

    /**
     * Get LaTeX representation
     * @param {Object} options
     * @return {string} str
     */
    _toTex(options) {
      var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
      var precedence = getPrecedence(this, parenthesis, options && options.implicit);
      var paramStrings = this.params.map(function (p, index) {
        var paramPrecedence = getPrecedence(p, parenthesis, options && options.implicit);
        return parenthesis === 'all' || paramPrecedence !== null && paramPrecedence <= precedence ? '\\left(' + p.toTex(options) + '\right)' : p.toTex(options);
      });
      var ret = paramStrings[0];
      for (var i = 0; i < this.conditionals.length; i++) {
        ret += latexOperators[this.conditionals[i]] + paramStrings[i + 1];
      }
      return ret;
    }
  }
  _defineProperty(RelationalNode, "name", name$1u);
  return RelationalNode;
}, {
  isClass: true,
  isNode: true
});

var name$1t = 'SymbolNode';
var dependencies$1t = ['math', '?Unit', 'Node'];
var createSymbolNode = /* #__PURE__ */factory(name$1t, dependencies$1t, _ref => {
  var {
    math,
    Unit,
    Node
  } = _ref;
  /**
   * Check whether some name is a valueless unit like "inch".
   * @param {string} name
   * @return {boolean}
   */
  function isValuelessUnit(name) {
    return Unit ? Unit.isValuelessUnit(name) : false;
  }
  class SymbolNode extends Node {
    /**
     * @constructor SymbolNode
     * @extends {Node}
     * A symbol node can hold and resolve a symbol
     * @param {string} name
     * @extends {Node}
     */
    constructor(name) {
      super();
      // validate input
      if (typeof name !== 'string') {
        throw new TypeError('String expected for parameter "name"');
      }
      this.name = name;
    }
    get type() {
      return 'SymbolNode';
    }
    get isSymbolNode() {
      return true;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      var name = this.name;
      if (argNames[name] === true) {
        // this is a FunctionAssignment argument
        // (like an x when inside the expression of a function
        // assignment `f(x) = ...`)
        return function (scope, args, context) {
          return getSafeProperty(args, name);
        };
      } else if (name in math) {
        return function (scope, args, context) {
          return scope.has(name) ? scope.get(name) : getSafeProperty(math, name);
        };
      } else {
        var isUnit = isValuelessUnit(name);
        return function (scope, args, context) {
          return scope.has(name) ? scope.get(name) : isUnit ? new Unit(null, name) : SymbolNode.onUndefinedSymbol(name);
        };
      }
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      // nothing to do, we don't have any children
    }

    /**
     * Create a new SymbolNode with children produced by the given callback.
     * Trivial since a SymbolNode has no children
     * @param {function(child: Node, path: string, parent: Node) : Node} callback
     * @returns {SymbolNode} Returns a clone of the node
     */
    map(callback) {
      return this.clone();
    }

    /**
     * Throws an error 'Undefined symbol {name}'
     * @param {string} name
     */
    static onUndefinedSymbol(name) {
      throw new Error('Undefined symbol ' + name);
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {SymbolNode}
     */
    clone() {
      return new SymbolNode(this.name);
    }

    /**
     * Get string representation
     * @param {Object} options
     * @return {string} str
     * @override
     */
    _toString(options) {
      return this.name;
    }

    /**
     * Get HTML representation
     * @param {Object} options
     * @return {string} str
     * @override
     */
    _toHTML(options) {
      var name = escape(this.name);
      if (name === 'true' || name === 'false') {
        return '<span class="math-symbol math-boolean">' + name + '</span>';
      } else if (name === 'i') {
        return '<span class="math-symbol math-imaginary-symbol">' + name + '</span>';
      } else if (name === 'Infinity') {
        return '<span class="math-symbol math-infinity-symbol">' + name + '</span>';
      } else if (name === 'NaN') {
        return '<span class="math-symbol math-nan-symbol">' + name + '</span>';
      } else if (name === 'null') {
        return '<span class="math-symbol math-null-symbol">' + name + '</span>';
      } else if (name === 'undefined') {
        return '<span class="math-symbol math-undefined-symbol">' + name + '</span>';
      }
      return '<span class="math-symbol">' + name + '</span>';
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      return {
        mathjs: 'SymbolNode',
        name: this.name
      };
    }

    /**
     * Instantiate a SymbolNode from its JSON representation
     * @param {Object} json  An object structured like
     *                       `{"mathjs": "SymbolNode", name: "x"}`,
     *                       where mathjs is optional
     * @returns {SymbolNode}
     */
    static fromJSON(json) {
      return new SymbolNode(json.name);
    }

    /**
     * Get LaTeX representation
     * @param {Object} options
     * @return {string} str
     * @override
     */
    _toTex(options) {
      var isUnit = false;
      if (typeof math[this.name] === 'undefined' && isValuelessUnit(this.name)) {
        isUnit = true;
      }
      var symbol = toSymbol(this.name, isUnit);
      if (symbol[0] === '\\') {
        // no space needed if the symbol starts with '\'
        return symbol;
      }
      // the space prevents symbols from breaking stuff like '\cdot'
      // if it's written right before the symbol
      return ' ' + symbol;
    }
  }
  return SymbolNode;
}, {
  isClass: true,
  isNode: true
});

var name$1s = 'FunctionNode';
var dependencies$1s = ['math', 'Node', 'SymbolNode'];
var createFunctionNode = /* #__PURE__ */factory(name$1s, dependencies$1s, _ref => {
  var _FunctionNode;
  var {
    math,
    Node,
    SymbolNode
  } = _ref;
  /* format to fixed length */
  var strin = entity => format(entity, {
    truncate: 78
  });

  /*
   * Expand a LaTeX template
   *
   * @param {string} template
   * @param {Node} node
   * @param {Object} options
   * @private
   **/
  function expandTemplate(template, node, options) {
    var latex = '';

    // Match everything of the form ${identifier} or ${identifier[2]} or $$
    // while submatching identifier and 2 (in the second case)
    var regex = /\$(?:\{([a-z_][a-z_0-9]*)(?:\[([0-9]+)\])?\}|\$)/gi;
    var inputPos = 0; // position in the input string
    var match;
    while ((match = regex.exec(template)) !== null) {
      // go through all matches
      // add everything in front of the match to the LaTeX string
      latex += template.substring(inputPos, match.index);
      inputPos = match.index;
      if (match[0] === '$$') {
        // escaped dollar sign
        latex += '$';
        inputPos++;
      } else {
        // template parameter
        inputPos += match[0].length;
        var property = node[match[1]];
        if (!property) {
          throw new ReferenceError('Template: Property ' + match[1] + ' does not exist.');
        }
        if (match[2] === undefined) {
          // no square brackets
          switch (typeof property) {
            case 'string':
              latex += property;
              break;
            case 'object':
              if (isNode(property)) {
                latex += property.toTex(options);
              } else if (Array.isArray(property)) {
                // make array of Nodes into comma separated list
                latex += property.map(function (arg, index) {
                  if (isNode(arg)) {
                    return arg.toTex(options);
                  }
                  throw new TypeError('Template: ' + match[1] + '[' + index + '] is not a Node.');
                }).join(',');
              } else {
                throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes');
              }
              break;
            default:
              throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes');
          }
        } else {
          // with square brackets
          if (isNode(property[match[2]] && property[match[2]])) {
            latex += property[match[2]].toTex(options);
          } else {
            throw new TypeError('Template: ' + match[1] + '[' + match[2] + '] is not a Node.');
          }
        }
      }
    }
    latex += template.slice(inputPos); // append rest of the template

    return latex;
  }
  class FunctionNode extends Node {
    /**
     * @constructor FunctionNode
     * @extends {./Node}
     * invoke a list with arguments on a node
     * @param {./Node | string} fn
     *     Item resolving to a function on which to invoke
     *     the arguments, typically a SymboNode or AccessorNode
     * @param {./Node[]} args
     */
    constructor(fn, args) {
      super();
      if (typeof fn === 'string') {
        fn = new SymbolNode(fn);
      }

      // validate input
      if (!isNode(fn)) throw new TypeError('Node expected as parameter "fn"');
      if (!Array.isArray(args) || !args.every(isNode)) {
        throw new TypeError('Array containing Nodes expected for parameter "args"');
      }
      this.fn = fn;
      this.args = args || [];
    }

    // readonly property name
    get name() {
      return this.fn.name || '';
    }
    get type() {
      return name$1s;
    }
    get isFunctionNode() {
      return true;
    }

    /**
     * Compile a node into a JavaScript function.
     * This basically pre-calculates as much as possible and only leaves open
     * calculations which depend on a dynamic scope with variables.
     * @param {Object} math     Math.js namespace with functions and constants.
     * @param {Object} argNames An object with argument names as key and `true`
     *                          as value. Used in the SymbolNode to optimize
     *                          for arguments from user assigned functions
     *                          (see FunctionAssignmentNode) or special symbols
     *                          like `end` (see IndexNode).
     * @return {function} Returns a function which can be called like:
     *                        evalNode(scope: Object, args: Object, context: *)
     */
    _compile(math, argNames) {
      // compile arguments
      var evalArgs = this.args.map(arg => arg._compile(math, argNames));
      if (isSymbolNode(this.fn)) {
        var _name = this.fn.name;
        if (!argNames[_name]) {
          // we can statically determine whether the function
          // has the rawArgs property
          var fn = _name in math ? getSafeProperty(math, _name) : undefined;
          var isRaw = typeof fn === 'function' && fn.rawArgs === true;
          var resolveFn = scope => {
            var value;
            if (scope.has(_name)) {
              value = scope.get(_name);
            } else if (_name in math) {
              value = getSafeProperty(math, _name);
            } else {
              return FunctionNode.onUndefinedFunction(_name);
            }
            if (typeof value === 'function') {
              return value;
            }
            throw new TypeError("'".concat(_name, "' is not a function; its value is:\n  ").concat(strin(value)));
          };
          if (isRaw) {
            // pass unevaluated parameters (nodes) to the function
            // "raw" evaluation
            var rawArgs = this.args;
            return function evalFunctionNode(scope, args, context) {
              var fn = resolveFn(scope);
              return fn(rawArgs, math, createSubScope(scope, args));
            };
          } else {
            // "regular" evaluation
            switch (evalArgs.length) {
              case 0:
                return function evalFunctionNode(scope, args, context) {
                  var fn = resolveFn(scope);
                  return fn();
                };
              case 1:
                return function evalFunctionNode(scope, args, context) {
                  var fn = resolveFn(scope);
                  var evalArg0 = evalArgs[0];
                  return fn(evalArg0(scope, args, context));
                };
              case 2:
                return function evalFunctionNode(scope, args, context) {
                  var fn = resolveFn(scope);
                  var evalArg0 = evalArgs[0];
                  var evalArg1 = evalArgs[1];
                  return fn(evalArg0(scope, args, context), evalArg1(scope, args, context));
                };
              default:
                return function evalFunctionNode(scope, args, context) {
                  var fn = resolveFn(scope);
                  var values = evalArgs.map(evalArg => evalArg(scope, args, context));
                  return fn(...values);
                };
            }
          }
        } else {
          // the function symbol is an argName
          var _rawArgs = this.args;
          return function evalFunctionNode(scope, args, context) {
            var fn = getSafeProperty(args, _name);
            if (typeof fn !== 'function') {
              throw new TypeError("Argument '".concat(_name, "' was not a function; received: ").concat(strin(fn)));
            }
            if (fn.rawArgs) {
              // "Raw" evaluation
              return fn(_rawArgs, math, createSubScope(scope, args));
            } else {
              var values = evalArgs.map(evalArg => evalArg(scope, args, context));
              return fn.apply(fn, values);
            }
          };
        }
      } else if (isAccessorNode(this.fn) && isIndexNode(this.fn.index) && this.fn.index.isObjectProperty()) {
        // execute the function with the right context:
        // the object of the AccessorNode

        var evalObject = this.fn.object._compile(math, argNames);
        var prop = this.fn.index.getObjectProperty();
        var _rawArgs2 = this.args;
        return function evalFunctionNode(scope, args, context) {
          var object = evalObject(scope, args, context);
          var fn = getSafeMethod(object, prop);
          if (fn !== null && fn !== void 0 && fn.rawArgs) {
            // "Raw" evaluation
            return fn(_rawArgs2, math, createSubScope(scope, args));
          } else {
            // "regular" evaluation
            var values = evalArgs.map(evalArg => evalArg(scope, args, context));
            return fn.apply(object, values);
          }
        };
      } else {
        // node.fn.isAccessorNode && !node.fn.index.isObjectProperty()
        // we have to dynamically determine whether the function has the
        // rawArgs property
        var fnExpr = this.fn.toString();
        var evalFn = this.fn._compile(math, argNames);
        var _rawArgs3 = this.args;
        return function evalFunctionNode(scope, args, context) {
          var fn = evalFn(scope, args, context);
          if (typeof fn !== 'function') {
            throw new TypeError("Expression '".concat(fnExpr, "' did not evaluate to a function; value is:") + "\n  ".concat(strin(fn)));
          }
          if (fn.rawArgs) {
            // "Raw" evaluation
            return fn(_rawArgs3, math, createSubScope(scope, args));
          } else {
            // "regular" evaluation
            var values = evalArgs.map(evalArg => evalArg(scope, args, context));
            return fn.apply(fn, values);
          }
        };
      }
    }

    /**
     * Execute a callback for each of the child nodes of this node
     * @param {function(child: Node, path: string, parent: Node)} callback
     */
    forEach(callback) {
      callback(this.fn, 'fn', this);
      for (var i = 0; i < this.args.length; i++) {
        callback(this.args[i], 'args[' + i + ']', this);
      }
    }

    /**
     * Create a new FunctionNode whose children are the results of calling
     * the provided callback function for each child of the original node.
     * @param {function(child: Node, path: string, parent: Node): Node} callback
     * @returns {FunctionNode} Returns a transformed copy of the node
     */
    map(callback) {
      var fn = this._ifNode(callback(this.fn, 'fn', this));
      var args = [];
      for (var i = 0; i < this.args.length; i++) {
        args[i] = this._ifNode(callback(this.args[i], 'args[' + i + ']', this));
      }
      return new FunctionNode(fn, args);
    }

    /**
     * Create a clone of this node, a shallow copy
     * @return {FunctionNode}
     */
    clone() {
      return new FunctionNode(this.fn, this.args.slice(0));
    }

    /**
     * Throws an error 'Undefined function {name}'
     * @param {string} name
     */

    /**
     * Get string representation. (wrapper function)
     * This overrides parts of Node's toString function.
     * If callback is an object containing callbacks, it
     * calls the correct callback for the current node,
     * otherwise it falls back to calling Node's toString
     * function.
     *
     * @param {Object} options
     * @return {string} str
     * @override
     */
    toString(options) {
      var customString;
      var name = this.fn.toString(options);
      if (options && typeof options.handler === 'object' && hasOwnProperty(options.handler, name)) {
        // callback is a map of callback functions
        customString = options.handler[name](this, options);
      }
      if (typeof customString !== 'undefined') {
        return customString;
      }

      // fall back to Node's toString
      return super.toString(options);
    }

    /**
     * Get string representation
     * @param {Object} options
     * @return {string} str
     */
    _toString(options) {
      var args = this.args.map(function (arg) {
        return arg.toString(options);
      });
      var fn = isFunctionAssignmentNode(this.fn) ? '(' + this.fn.toString(options) + ')' : this.fn.toString(options);

      // format the arguments like "add(2, 4.2)"
      return fn + '(' + args.join(', ') + ')';
    }

    /**
     * Get a JSON representation of the node
     * @returns {Object}
     */
    toJSON() {
      return {
        mathjs: name$1s,
        fn: this.fn,
        args: this.args
      };
    }

    /**
     * Instantiate an AssignmentNode from its JSON representation
     * @param {Object} json  An object structured like
     *                       `{"mathjs": "FunctionNode", fn: ..., args: ...}`,
     *                       where mathjs is optional
     * @returns {FunctionNode}
     */

    /**
     * Get HTML representation
     * @param {Object} options
     * @return {string} str
     */
    _toHTML(options) {
      var args = this.args.map(function (arg) {
        return arg.toHTML(options);
      });

      // format the arguments like "add(2, 4.2)"
      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>';
    }

    /**
     * Get LaTeX representation. (wrapper function)
     * This overrides parts of Node's toTex function.
     * If callback is an object containing callbacks, it
     * calls the correct callback for the current node,
     * otherwise it falls back to calling Node's toTex
     * function.
     *
     * @param {Object} options
     * @return {string}
     */
    toTex(options) {
      var customTex;
      if (options && typeof options.handler === 'object' && hasOwnProperty(options.handler, this.name)) {
        // callback is a map of callback functions
        customTex = options.handler[this.name](this, options);
      }
      if (typeof customTex !== 'undefined') {
        return customTex;
      }

      // fall back to Node's toTex
      return super.toTex(options);
    }

    /**
     * Get LaTeX representation
     * @param {Object} options
     * @return {string} str
     */
    _toTex(options) {
      var args = this.args.map(function (arg) {
        // get LaTeX of the arguments
        return arg.toTex(options);
      });
      var latexConverter;
      if (latexFunctions[this.name]) {
        latexConverter = latexFunctions[this.name];
      }

      // toTex property on the function itself
      if (math[this.name] && (typeof math[this.name].toTex === 'function' || typeof math[this.name].toTex === 'object' || typeof math[this.name].toTex === 'string')) {
        // .toTex is a callback function
        latexConverter = math[this.name].toTex;
      }
      var customToTex;
      switch (typeof latexConverter) {
        case 'function':
          // a callback function
          customToTex = latexConverter(this, options);
          break;
        case 'string':
          // a template string
          customToTex = expandTemplate(latexConverter, this, options);
          break;
        case 'object':
          // an object with different "converters" for different
          // numbers of arguments
          switch (typeof latexConverter[args.length]) {
            case 'function':
              customToTex = latexConverter[args.length](this, options);
              break;
            case 'string':
              customToTex = expandTemplate(latexConverter[args.length], this, options);
              break;
          }
      }
      if (typeof customToTex !== 'undefined') {
        return customToTex;
      }
      return expandTemplate(defaultTemplate, this, options);
    }

    /**
     * Get identifier.
     * @return {string}
     */
    getIdentifier() {
      return this.type + ':' + this.name;
    }
  }
  _FunctionNode = FunctionNode;
  _defineProperty(FunctionNode, "name", name$1s);
  _defineProperty(FunctionNode, "onUndefinedFunction", function (name) {
    throw new Error('Undefined function ' + name);
  });
  _defineProperty(FunctionNode, "fromJSON", function (json) {
    return new _FunctionNode(json.fn, json.args);
  });
  return FunctionNode;
}, {
  isClass: true,
  isNode: true
});

var name$1r = 'parse';
var dependencies$1r = ['typed', 'numeric', 'config', 'AccessorNode', 'ArrayNode', 'AssignmentNode', 'BlockNode', 'ConditionalNode', 'ConstantNode', 'FunctionAssignmentNode', 'FunctionNode', 'IndexNode', 'ObjectNode', 'OperatorNode', 'ParenthesisNode', 'RangeNode', 'RelationalNode', 'SymbolNode'];
var createParse = /* #__PURE__ */factory(name$1r, dependencies$1r, _ref => {
  var {
    typed,
    numeric,
    config,
    AccessorNode,
    ArrayNode,
    AssignmentNode,
    BlockNode,
    ConditionalNode,
    ConstantNode,
    FunctionAssignmentNode,
    FunctionNode,
    IndexNode,
    ObjectNode,
    OperatorNode,
    ParenthesisNode,
    RangeNode,
    RelationalNode,
    SymbolNode
  } = _ref;
  /**
   * Parse an expression. Returns a node tree, which can be evaluated by
   * invoking node.evaluate().
   *
   * Note the evaluating arbitrary expressions may involve security risks,
   * see [https://mathjs.org/docs/expressions/security.html](https://mathjs.org/docs/expressions/security.html) for more information.
   *
   * Syntax:
   *
   *     math.parse(expr)
   *     math.parse(expr, options)
   *     math.parse([expr1, expr2, expr3, ...])
   *     math.parse([expr1, expr2, expr3, ...], options)
   *
   * Example:
   *
   *     const node1 = math.parse('sqrt(3^2 + 4^2)')
   *     node1.compile().evaluate() // 5
   *
   *     let scope = {a:3, b:4}
   *     const node2 = math.parse('a * b') // 12
   *     const code2 = node2.compile()
   *     code2.evaluate(scope) // 12
   *     scope.a = 5
   *     code2.evaluate(scope) // 20
   *
   *     const nodes = math.parse(['a = 3', 'b = 4', 'a * b'])
   *     nodes[2].compile().evaluate() // 12
   *
   * See also:
   *
   *     evaluate, compile
   *
   * @param {string | string[] | Matrix} expr          Expression to be parsed
   * @param {{nodes: Object<string, Node>}} [options]  Available options:
   *                                                   - `nodes` a set of custom nodes
   * @return {Node | Node[]} node
   * @throws {Error}
   */
  var parse = typed(name$1r, {
    string: function string(expression) {
      return parseStart(expression, {});
    },
    'Array | Matrix': function ArrayMatrix(expressions) {
      return parseMultiple(expressions, {});
    },
    'string, Object': function stringObject(expression, options) {
      var extraNodes = options.nodes !== undefined ? options.nodes : {};
      return parseStart(expression, extraNodes);
    },
    'Array | Matrix, Object': parseMultiple
  });
  function parseMultiple(expressions) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var extraNodes = options.nodes !== undefined ? options.nodes : {};

    // parse an array or matrix with expressions
    return deepMap(expressions, function (elem) {
      if (typeof elem !== 'string') throw new TypeError('String expected');
      return parseStart(elem, extraNodes);
    });
  }

  // token types enumeration
  var TOKENTYPE = {
    NULL: 0,
    DELIMITER: 1,
    NUMBER: 2,
    SYMBOL: 3,
    UNKNOWN: 4
  };

  // map with all delimiters
  var DELIMITERS = {
    ',': true,
    '(': true,
    ')': true,
    '[': true,
    ']': true,
    '{': true,
    '}': true,
    '"': true,
    '\'': true,
    ';': true,
    '+': true,
    '-': true,
    '*': true,
    '.*': true,
    '/': true,
    './': true,
    '%': true,
    '^': true,
    '.^': true,
    '~': true,
    '!': true,
    '&': true,
    '|': true,
    '^|': true,
    '=': true,
    ':': true,
    '?': true,
    '==': true,
    '!=': true,
    '<': true,
    '>': true,
    '<=': true,
    '>=': true,
    '<<': true,
    '>>': true,
    '>>>': true
  };

  // map with all named delimiters
  var NAMED_DELIMITERS = {
    mod: true,
    to: true,
    in: true,
    and: true,
    xor: true,
    or: true,
    not: true
  };
  var CONSTANTS = {
    true: true,
    false: false,
    null: null,
    undefined
  };
  var NUMERIC_CONSTANTS = ['NaN', 'Infinity'];
  var ESCAPE_CHARACTERS = {
    '"': '"',
    "'": "'",
    '\\': '\\',
    '/': '/',
    b: '\b',
    f: '\f',
    n: '\n',
    r: '\r',
    t: '\t'
    // note that \u is handled separately in parseStringToken()
  };
  function initialState() {
    return {
      extraNodes: {},
      // current extra nodes, must be careful not to mutate
      expression: '',
      // current expression
      comment: '',
      // last parsed comment
      index: 0,
      // current index in expr
      token: '',
      // current token
      tokenType: TOKENTYPE.NULL,
      // type of the token
      nestingLevel: 0,
      // level of nesting inside parameters, used to ignore newline characters
      conditionalLevel: null // when a conditional is being parsed, the level of the conditional is stored here
    };
  }

  /**
   * View upto `length` characters of the expression starting at the current character.
   *
   * @param {Object} state
   * @param {number} [length=1] Number of characters to view
   * @returns {string}
   * @private
   */
  function currentString(state, length) {
    return state.expression.substr(state.index, length);
  }

  /**
   * View the current character. Returns '' if end of expression is reached.
   *
   * @param {Object} state
   * @returns {string}
   * @private
   */
  function currentCharacter(state) {
    return currentString(state, 1);
  }

  /**
   * Get the next character from the expression.
   * The character is stored into the char c. If the end of the expression is
   * reached, the function puts an empty string in c.
   * @private
   */
  function next(state) {
    state.index++;
  }

  /**
   * Preview the previous character from the expression.
   * @return {string} cNext
   * @private
   */
  function prevCharacter(state) {
    return state.expression.charAt(state.index - 1);
  }

  /**
   * Preview the next character from the expression.
   * @return {string} cNext
   * @private
   */
  function nextCharacter(state) {
    return state.expression.charAt(state.index + 1);
  }

  /**
   * Get next token in the current string expr.
   * The token and token type are available as token and tokenType
   * @private
   */
  function getToken(state) {
    state.tokenType = TOKENTYPE.NULL;
    state.token = '';
    state.comment = '';

    // skip over ignored characters:
    while (true) {
      // comments:
      if (currentCharacter(state) === '#') {
        while (currentCharacter(state) !== '\n' && currentCharacter(state) !== '') {
          state.comment += currentCharacter(state);
          next(state);
        }
      }
      // whitespace: space, tab, and newline when inside parameters
      if (parse.isWhitespace(currentCharacter(state), state.nestingLevel)) {
        next(state);
      } else {
        break;
      }
    }

    // check for end of expression
    if (currentCharacter(state) === '') {
      // token is still empty
      state.tokenType = TOKENTYPE.DELIMITER;
      return;
    }

    // check for new line character
    if (currentCharacter(state) === '\n' && !state.nestingLevel) {
      state.tokenType = TOKENTYPE.DELIMITER;
      state.token = currentCharacter(state);
      next(state);
      return;
    }
    var c1 = currentCharacter(state);
    var c2 = currentString(state, 2);
    var c3 = currentString(state, 3);
    if (c3.length === 3 && DELIMITERS[c3]) {
      state.tokenType = TOKENTYPE.DELIMITER;
      state.token = c3;
      next(state);
      next(state);
      next(state);
      return;
    }

    // check for delimiters consisting of 2 characters
    if (c2.length === 2 && DELIMITERS[c2]) {
      state.tokenType = TOKENTYPE.DELIMITER;
      state.token = c2;
      next(state);
      next(state);
      return;
    }

    // check for delimiters consisting of 1 character
    if (DELIMITERS[c1]) {
      state.tokenType = TOKENTYPE.DELIMITER;
      state.token = c1;
      next(state);
      return;
    }

    // check for a number
    if (parse.isDigitDot(c1)) {
      state.tokenType = TOKENTYPE.NUMBER;

      // check for binary, octal, or hex
      var _c = currentString(state, 2);
      if (_c === '0b' || _c === '0o' || _c === '0x') {
        state.token += currentCharacter(state);
        next(state);
        state.token += currentCharacter(state);
        next(state);
        while (parse.isHexDigit(currentCharacter(state))) {
          state.token += currentCharacter(state);
          next(state);
        }
        if (currentCharacter(state) === '.') {
          // this number has a radix point
          state.token += '.';
          next(state);
          // get the digits after the radix
          while (parse.isHexDigit(currentCharacter(state))) {
            state.token += currentCharacter(state);
            next(state);
          }
        } else if (currentCharacter(state) === 'i') {
          // this number has a word size suffix
          state.token += 'i';
          next(state);
          // get the word size
          while (parse.isDigit(currentCharacter(state))) {
            state.token += currentCharacter(state);
            next(state);
          }
        }
        return;
      }

      // get number, can have a single dot
      if (currentCharacter(state) === '.') {
        state.token += currentCharacter(state);
        next(state);
        if (!parse.isDigit(currentCharacter(state))) {
          // this is no number, it is just a dot (can be dot notation)
          state.tokenType = TOKENTYPE.DELIMITER;
          return;
        }
      } else {
        while (parse.isDigit(currentCharacter(state))) {
          state.token += currentCharacter(state);
          next(state);
        }
        if (parse.isDecimalMark(currentCharacter(state), nextCharacter(state))) {
          state.token += currentCharacter(state);
          next(state);
        }
      }
      while (parse.isDigit(currentCharacter(state))) {
        state.token += currentCharacter(state);
        next(state);
      }
      // check for exponential notation like "2.3e-4", "1.23e50" or "2e+4"
      if (currentCharacter(state) === 'E' || currentCharacter(state) === 'e') {
        if (parse.isDigit(nextCharacter(state)) || nextCharacter(state) === '-' || nextCharacter(state) === '+') {
          state.token += currentCharacter(state);
          next(state);
          if (currentCharacter(state) === '+' || currentCharacter(state) === '-') {
            state.token += currentCharacter(state);
            next(state);
          }
          // Scientific notation MUST be followed by an exponent
          if (!parse.isDigit(currentCharacter(state))) {
            throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"');
          }
          while (parse.isDigit(currentCharacter(state))) {
            state.token += currentCharacter(state);
            next(state);
          }
          if (parse.isDecimalMark(currentCharacter(state), nextCharacter(state))) {
            throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"');
          }
        } else if (nextCharacter(state) === '.') {
          next(state);
          throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"');
        }
      }
      return;
    }

    // check for variables, functions, named operators
    if (parse.isAlpha(currentCharacter(state), prevCharacter(state), nextCharacter(state))) {
      while (parse.isAlpha(currentCharacter(state), prevCharacter(state), nextCharacter(state)) || parse.isDigit(currentCharacter(state))) {
        state.token += currentCharacter(state);
        next(state);
      }
      if (hasOwnProperty(NAMED_DELIMITERS, state.token)) {
        state.tokenType = TOKENTYPE.DELIMITER;
      } else {
        state.tokenType = TOKENTYPE.SYMBOL;
      }
      return;
    }

    // something unknown is found, wrong characters -> a syntax error
    state.tokenType = TOKENTYPE.UNKNOWN;
    while (currentCharacter(state) !== '') {
      state.token += currentCharacter(state);
      next(state);
    }
    throw createSyntaxError(state, 'Syntax error in part "' + state.token + '"');
  }

  /**
   * Get next token and skip newline tokens
   */
  function getTokenSkipNewline(state) {
    do {
      getToken(state);
    } while (state.token === '\n'); // eslint-disable-line no-unmodified-loop-condition
  }

  /**
   * Open parameters.
   * New line characters will be ignored until closeParams(state) is called
   */
  function openParams(state) {
    state.nestingLevel++;
  }

  /**
   * Close parameters.
   * New line characters will no longer be ignored
   */
  function closeParams(state) {
    state.nestingLevel--;
  }

  /**
   * Checks whether the current character `c` is a valid alpha character:
   *
   * - A latin letter (upper or lower case) Ascii: a-z, A-Z
   * - An underscore                        Ascii: _
   * - A dollar sign                        Ascii: $
   * - A latin letter with accents          Unicode: \u00C0 - \u02AF
   * - A greek letter                       Unicode: \u0370 - \u03FF
   * - A mathematical alphanumeric symbol   Unicode: \u{1D400} - \u{1D7FF} excluding invalid code points
   *
   * The previous and next characters are needed to determine whether
   * this character is part of a unicode surrogate pair.
   *
   * @param {string} c      Current character in the expression
   * @param {string} cPrev  Previous character
   * @param {string} cNext  Next character
   * @return {boolean}
   */
  parse.isAlpha = function isAlpha(c, cPrev, cNext) {
    return parse.isValidLatinOrGreek(c) || parse.isValidMathSymbol(c, cNext) || parse.isValidMathSymbol(cPrev, c);
  };

  /**
   * Test whether a character is a valid latin, greek, or letter-like character
   * @param {string} c
   * @return {boolean}
   */
  parse.isValidLatinOrGreek = function isValidLatinOrGreek(c) {
    return /^[a-zA-Z_$\u00C0-\u02AF\u0370-\u03FF\u2100-\u214F]$/.test(c);
  };

  /**
   * Test whether two given 16 bit characters form a surrogate pair of a
   * unicode math symbol.
   *
   * https://unicode-table.com/en/
   * https://www.wikiwand.com/en/Mathematical_operators_and_symbols_in_Unicode
   *
   * Note: In ES6 will be unicode aware:
   * https://stackoverflow.com/questions/280712/javascript-unicode-regexes
   * https://mathiasbynens.be/notes/es6-unicode-regex
   *
   * @param {string} high
   * @param {string} low
   * @return {boolean}
   */
  parse.isValidMathSymbol = function isValidMathSymbol(high, low) {
    return /^[\uD835]$/.test(high) && /^[\uDC00-\uDFFF]$/.test(low) && /^[^\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDFCC\uDFCD]$/.test(low);
  };

  /**
   * Check whether given character c is a white space character: space, tab, or enter
   * @param {string} c
   * @param {number} nestingLevel
   * @return {boolean}
   */
  parse.isWhitespace = function isWhitespace(c, nestingLevel) {
    // TODO: also take '\r' carriage return as newline? Or does that give problems on mac?
    return c === ' ' || c === '\t' || c === '\n' && nestingLevel > 0;
  };

  /**
   * Test whether the character c is a decimal mark (dot).
   * This is the case when it's not the start of a delimiter '.*', './', or '.^'
   * @param {string} c
   * @param {string} cNext
   * @return {boolean}
   */
  parse.isDecimalMark = function isDecimalMark(c, cNext) {
    return c === '.' && cNext !== '/' && cNext !== '*' && cNext !== '^';
  };

  /**
   * checks if the given char c is a digit or dot
   * @param {string} c   a string with one character
   * @return {boolean}
   */
  parse.isDigitDot = function isDigitDot(c) {
    return c >= '0' && c <= '9' || c === '.';
  };

  /**
   * checks if the given char c is a digit
   * @param {string} c   a string with one character
   * @return {boolean}
   */
  parse.isDigit = function isDigit(c) {
    return c >= '0' && c <= '9';
  };

  /**
   * checks if the given char c is a hex digit
   * @param {string} c   a string with one character
   * @return {boolean}
   */
  parse.isHexDigit = function isHexDigit(c) {
    return c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F';
  };

  /**
   * Start of the parse levels below, in order of precedence
   * @return {Node} node
   * @private
   */
  function parseStart(expression, extraNodes) {
    var state = initialState();
    _extends$1(state, {
      expression,
      extraNodes
    });
    getToken(state);
    var node = parseBlock(state);

    // check for garbage at the end of the expression
    // an expression ends with a empty character '' and tokenType DELIMITER
    if (state.token !== '') {
      if (state.tokenType === TOKENTYPE.DELIMITER) {
        // user entered a not existing operator like "//"

        // TODO: give hints for aliases, for example with "<>" give as hint " did you mean !== ?"
        throw createError(state, 'Unexpected operator ' + state.token);
      } else {
        throw createSyntaxError(state, 'Unexpected part "' + state.token + '"');
      }
    }
    return node;
  }

  /**
   * Parse a block with expressions. Expressions can be separated by a newline
   * character '\n', or by a semicolon ';'. In case of a semicolon, no output
   * of the preceding line is returned.
   * @return {Node} node
   * @private
   */
  function parseBlock(state) {
    var node;
    var blocks = [];
    var visible;
    if (state.token !== '' && state.token !== '\n' && state.token !== ';') {
      node = parseAssignment(state);
      if (state.comment) {
        node.comment = state.comment;
      }
    }

    // TODO: simplify this loop
    while (state.token === '\n' || state.token === ';') {
      // eslint-disable-line no-unmodified-loop-condition
      if (blocks.length === 0 && node) {
        visible = state.token !== ';';
        blocks.push({
          node,
          visible
        });
      }
      getToken(state);
      if (state.token !== '\n' && state.token !== ';' && state.token !== '') {
        node = parseAssignment(state);
        if (state.comment) {
          node.comment = state.comment;
        }
        visible = state.token !== ';';
        blocks.push({
          node,
          visible
        });
      }
    }
    if (blocks.length > 0) {
      return new BlockNode(blocks);
    } else {
      if (!node) {
        node = new ConstantNode(undefined);
        if (state.comment) {
          node.comment = state.comment;
        }
      }
      return node;
    }
  }

  /**
   * Assignment of a function or variable,
   * - can be a variable like 'a=2.3'
   * - or a updating an existing variable like 'matrix(2,3:5)=[6,7,8]'
   * - defining a function like 'f(x) = x^2'
   * @return {Node} node
   * @private
   */
  function parseAssignment(state) {
    var name, args, value, valid;
    var node = parseConditional(state);
    if (state.token === '=') {
      if (isSymbolNode(node)) {
        // parse a variable assignment like 'a = 2/3'
        name = node.name;
        getTokenSkipNewline(state);
        value = parseAssignment(state);
        return new AssignmentNode(new SymbolNode(name), value);
      } else if (isAccessorNode(node)) {
        // parse a matrix subset assignment like 'A[1,2] = 4'
        getTokenSkipNewline(state);
        value = parseAssignment(state);
        return new AssignmentNode(node.object, node.index, value);
      } else if (isFunctionNode(node) && isSymbolNode(node.fn)) {
        // parse function assignment like 'f(x) = x^2'
        valid = true;
        args = [];
        name = node.name;
        node.args.forEach(function (arg, index) {
          if (isSymbolNode(arg)) {
            args[index] = arg.name;
          } else {
            valid = false;
          }
        });
        if (valid) {
          getTokenSkipNewline(state);
          value = parseAssignment(state);
          return new FunctionAssignmentNode(name, args, value);
        }
      }
      throw createSyntaxError(state, 'Invalid left hand side of assignment operator =');
    }
    return node;
  }

  /**
   * conditional operation
   *
   *     condition ? truePart : falsePart
   *
   * Note: conditional operator is right-associative
   *
   * @return {Node} node
   * @private
   */
  function parseConditional(state) {
    var node = parseLogicalOr(state);
    while (state.token === '?') {
      // eslint-disable-line no-unmodified-loop-condition
      // set a conditional level, the range operator will be ignored as long
      // as conditionalLevel === state.nestingLevel.
      var prev = state.conditionalLevel;
      state.conditionalLevel = state.nestingLevel;
      getTokenSkipNewline(state);
      var condition = node;
      var trueExpr = parseAssignment(state);
      if (state.token !== ':') throw createSyntaxError(state, 'False part of conditional expression expected');
      state.conditionalLevel = null;
      getTokenSkipNewline(state);
      var falseExpr = parseAssignment(state); // Note: check for conditional operator again, right associativity

      node = new ConditionalNode(condition, trueExpr, falseExpr);

      // restore the previous conditional level
      state.conditionalLevel = prev;
    }
    return node;
  }

  /**
   * logical or, 'x or y'
   * @return {Node} node
   * @private
   */
  function parseLogicalOr(state) {
    var node = parseLogicalXor(state);
    while (state.token === 'or') {
      // eslint-disable-line no-unmodified-loop-condition
      getTokenSkipNewline(state);
      node = new OperatorNode('or', 'or', [node, parseLogicalXor(state)]);
    }
    return node;
  }

  /**
   * logical exclusive or, 'x xor y'
   * @return {Node} node
   * @private
   */
  function parseLogicalXor(state) {
    var node = parseLogicalAnd(state);
    while (state.token === 'xor') {
      // eslint-disable-line no-unmodified-loop-condition
      getTokenSkipNewline(state);
      node = new OperatorNode('xor', 'xor', [node, parseLogicalAnd(state)]);
    }
    return node;
  }

  /**
   * logical and, 'x and y'
   * @return {Node} node
   * @private
   */
  function parseLogicalAnd(state) {
    var node = parseBitwiseOr(state);
    while (state.token === 'and') {
      // eslint-disable-line no-unmodified-loop-condition
      getTokenSkipNewline(state);
      node = new OperatorNode('and', 'and', [node, parseBitwiseOr(state)]);
    }
    return node;
  }

  /**
   * bitwise or, 'x | y'
   * @return {Node} node
   * @private
   */
  function parseBitwiseOr(state) {
    var node = parseBitwiseXor(state);
    while (state.token === '|') {
      // eslint-disable-line no-unmodified-loop-condition
      getTokenSkipNewline(state);
      node = new OperatorNode('|', 'bitOr', [node, parseBitwiseXor(state)]);
    }
    return node;
  }

  /**
   * bitwise exclusive or (xor), 'x ^| y'
   * @return {Node} node
   * @private
   */
  function parseBitwiseXor(state) {
    var node = parseBitwiseAnd(state);
    while (state.token === '^|') {
      // eslint-disable-line no-unmodified-loop-condition
      getTokenSkipNewline(state);
      node = new OperatorNode('^|', 'bitXor', [node, parseBitwiseAnd(state)]);
    }
    return node;
  }

  /**
   * bitwise and, 'x & y'
   * @return {Node} node
   * @private
   */
  function parseBitwiseAnd(state) {
    var node = parseRelational(state);
    while (state.token === '&') {
      // eslint-disable-line no-unmodified-loop-condition
      getTokenSkipNewline(state);
      node = new OperatorNode('&', 'bitAnd', [node, parseRelational(state)]);
    }
    return node;
  }

  /**
   * Parse a chained conditional, like 'a > b >= c'
   * @return {Node} node
   */
  function parseRelational(state) {
    var params = [parseShift(state)];
    var conditionals = [];
    var operators = {
      '==': 'equal',
      '!=': 'unequal',
      '<': 'smaller',
      '>': 'larger',
      '<=': 'smallerEq',
      '>=': 'largerEq'
    };
    while (hasOwnProperty(operators, state.token)) {
      // eslint-disable-line no-unmodified-loop-condition
      var cond = {
        name: state.token,
        fn: operators[state.token]
      };
      conditionals.push(cond);
      getTokenSkipNewline(state);
      params.push(parseShift(state));
    }
    if (params.length === 1) {
      return params[0];
    } else if (params.length === 2) {
      return new OperatorNode(conditionals[0].name, conditionals[0].fn, params);
    } else {
      return new RelationalNode(conditionals.map(c => c.fn), params);
    }
  }

  /**
   * Bitwise left shift, bitwise right arithmetic shift, bitwise right logical shift
   * @return {Node} node
   * @private
   */
  function parseShift(state) {
    var node, name, fn, params;
    node = parseConversion(state);
    var operators = {
      '<<': 'leftShift',
      '>>': 'rightArithShift',
      '>>>': 'rightLogShift'
    };
    while (hasOwnProperty(operators, state.token)) {
      name = state.token;
      fn = operators[name];
      getTokenSkipNewline(state);
      params = [node, parseConversion(state)];
      node = new OperatorNode(name, fn, params);
    }
    return node;
  }

  /**
   * conversion operators 'to' and 'in'
   * @return {Node} node
   * @private
   */
  function parseConversion(state) {
    var node, name, fn, params;
    node = parseRange(state);
    var operators = {
      to: 'to',
      in: 'to' // alias of 'to'
    };
    while (hasOwnProperty(operators, state.token)) {
      name = state.token;
      fn = operators[name];
      getTokenSkipNewline(state);
      if (name === 'in' && state.token === '') {
        // end of expression -> this is the unit 'in' ('inch')
        node = new OperatorNode('*', 'multiply', [node, new SymbolNode('in')], true);
      } else {
        // operator 'a to b' or 'a in b'
        params = [node, parseRange(state)];
        node = new OperatorNode(name, fn, params);
      }
    }
    return node;
  }

  /**
   * parse range, "start:end", "start:step:end", ":", "start:", ":end", etc
   * @return {Node} node
   * @private
   */
  function parseRange(state) {
    var node;
    var params = [];
    if (state.token === ':') {
      // implicit start=1 (one-based)
      node = new ConstantNode(1);
    } else {
      // explicit start
      node = parseAddSubtract(state);
    }
    if (state.token === ':' && state.conditionalLevel !== state.nestingLevel) {
      // we ignore the range operator when a conditional operator is being processed on the same level
      params.push(node);

      // parse step and end
      while (state.token === ':' && params.length < 3) {
        // eslint-disable-line no-unmodified-loop-condition
        getTokenSkipNewline(state);
        if (state.token === ')' || state.token === ']' || state.token === ',' || state.token === '') {
          // implicit end
          params.push(new SymbolNode('end'));
        } else {
          // explicit end
          params.push(parseAddSubtract(state));
        }
      }
      if (params.length === 3) {
        // params = [start, step, end]
        node = new RangeNode(params[0], params[2], params[1]); // start, end, step
      } else {
        // length === 2
        // params = [start, end]
        node = new RangeNode(params[0], params[1]); // start, end
      }
    }
    return node;
  }

  /**
   * add or subtract
   * @return {Node} node
   * @private
   */
  function parseAddSubtract(state) {
    var node, name, fn, params;
    node = parseMultiplyDivide(state);
    var operators = {
      '+': 'add',
      '-': 'subtract'
    };
    while (hasOwnProperty(operators, state.token)) {
      name = state.token;
      fn = operators[name];
      getTokenSkipNewline(state);
      var rightNode = parseMultiplyDivide(state);
      if (rightNode.isPercentage) {
        params = [node, new OperatorNode('*', 'multiply', [node, rightNode])];
      } else {
        params = [node, rightNode];
      }
      node = new OperatorNode(name, fn, params);
    }
    return node;
  }

  /**
   * multiply, divide
   * @return {Node} node
   * @private
   */
  function parseMultiplyDivide(state) {
    var node, last, name, fn;
    node = parseImplicitMultiplication(state);
    last = node;
    var operators = {
      '*': 'multiply',
      '.*': 'dotMultiply',
      '/': 'divide',
      './': 'dotDivide'
    };
    while (true) {
      if (hasOwnProperty(operators, state.token)) {
        // explicit operators
        name = state.token;
        fn = operators[name];
        getTokenSkipNewline(state);
        last = parseImplicitMultiplication(state);
        node = new OperatorNode(name, fn, [node, last]);
      } else {
        break;
      }
    }
    return node;
  }

  /**
   * implicit multiplication
   * @return {Node} node
   * @private
   */
  function parseImplicitMultiplication(state) {
    var node, last;
    node = parseRule2(state);
    last = node;
    while (true) {
      if (state.tokenType === TOKENTYPE.SYMBOL || state.token === 'in' && isConstantNode(node) || state.tokenType === TOKENTYPE.NUMBER && !isConstantNode(last) && (!isOperatorNode(last) || last.op === '!') || state.token === '(') {
        // parse implicit multiplication
        //
        // symbol:      implicit multiplication like '2a', '(2+3)a', 'a b'
        // number:      implicit multiplication like '(2+3)2'
        // parenthesis: implicit multiplication like '2(3+4)', '(3+4)(1+2)'
        last = parseRule2(state);
        node = new OperatorNode('*', 'multiply', [node, last], true /* implicit */);
      } else {
        break;
      }
    }
    return node;
  }

  /**
   * Infamous "rule 2" as described in https://github.com/josdejong/mathjs/issues/792#issuecomment-361065370
   * And as amended in https://github.com/josdejong/mathjs/issues/2370#issuecomment-1054052164
   * Explicit division gets higher precedence than implicit multiplication
   * when the division matches this pattern:
   *   [unaryPrefixOp]?[number] / [number] [symbol]
   * @return {Node} node
   * @private
   */
  function parseRule2(state) {
    var node = parseModulusPercentage(state);
    var last = node;
    var tokenStates = [];
    while (true) {
      // Match the "number /" part of the pattern "number / number symbol"
      if (state.token === '/' && rule2Node(last)) {
        // Look ahead to see if the next token is a number
        tokenStates.push(_extends$1({}, state));
        getTokenSkipNewline(state);

        // Match the "number / number" part of the pattern
        if (state.tokenType === TOKENTYPE.NUMBER) {
          // Look ahead again
          tokenStates.push(_extends$1({}, state));
          getTokenSkipNewline(state);

          // Match the "symbol" part of the pattern, or a left parenthesis
          if (state.tokenType === TOKENTYPE.SYMBOL || state.token === '(') {
            // We've matched the pattern "number / number symbol".
            // Rewind once and build the "number / number" node; the symbol will be consumed later
            _extends$1(state, tokenStates.pop());
            tokenStates.pop();
            last = parseModulusPercentage(state);
            node = new OperatorNode('/', 'divide', [node, last]);
          } else {
            // Not a match, so rewind
            tokenStates.pop();
            _extends$1(state, tokenStates.pop());
            break;
          }
        } else {
          // Not a match, so rewind
          _extends$1(state, tokenStates.pop());
          break;
        }
      } else {
        break;
      }
    }
    return node;
  }

  /**
   * modulus and percentage
   * @return {Node} node
   * @private
   */
  function parseModulusPercentage(state) {
    var node, name, fn, params;
    node = parseUnary(state);
    var operators = {
      '%': 'mod',
      mod: 'mod'
    };
    while (hasOwnProperty(operators, state.token)) {
      name = state.token;
      fn = operators[name];
      getTokenSkipNewline(state);
      if (name === '%' && state.tokenType === TOKENTYPE.DELIMITER && state.token !== '(') {
        // If the expression contains only %, then treat that as /100
        node = new OperatorNode('/', 'divide', [node, new ConstantNode(100)], false, true);
      } else {
        params = [node, parseUnary(state)];
        node = new OperatorNode(name, fn, params);
      }
    }
    return node;
  }

  /**
   * Unary plus and minus, and logical and bitwise not
   * @return {Node} node
   * @private
   */
  function parseUnary(state) {
    var name, params, fn;
    var operators = {
      '-': 'unaryMinus',
      '+': 'unaryPlus',
      '~': 'bitNot',
      not: 'not'
    };
    if (hasOwnProperty(operators, state.token)) {
      fn = operators[state.token];
      name = state.token;
      getTokenSkipNewline(state);
      params = [parseUnary(state)];
      return new OperatorNode(name, fn, params);
    }
    return parsePow(state);
  }

  /**
   * power
   * Note: power operator is right associative
   * @return {Node} node
   * @private
   */
  function parsePow(state) {
    var node, name, fn, params;
    node = parseLeftHandOperators(state);
    if (state.token === '^' || state.token === '.^') {
      name = state.token;
      fn = name === '^' ? 'pow' : 'dotPow';
      getTokenSkipNewline(state);
      params = [node, parseUnary(state)]; // Go back to unary, we can have '2^-3'
      node = new OperatorNode(name, fn, params);
    }
    return node;
  }

  /**
   * Left hand operators: factorial x!, ctranspose x'
   * @return {Node} node
   * @private
   */
  function parseLeftHandOperators(state) {
    var node, name, fn, params;
    node = parseCustomNodes(state);
    var operators = {
      '!': 'factorial',
      '\'': 'ctranspose'
    };
    while (hasOwnProperty(operators, state.token)) {
      name = state.token;
      fn = operators[name];
      getToken(state);
      params = [node];
      node = new OperatorNode(name, fn, params);
      node = parseAccessors(state, node);
    }
    return node;
  }

  /**
   * Parse a custom node handler. A node handler can be used to process
   * nodes in a custom way, for example for handling a plot.
   *
   * A handler must be passed as second argument of the parse function.
   * - must extend math.Node
   * - must contain a function _compile(defs: Object) : string
   * - must contain a function find(filter: Object) : Node[]
   * - must contain a function toString() : string
   * - the constructor is called with a single argument containing all parameters
   *
   * For example:
   *
   *     nodes = {
   *       'plot': PlotHandler
   *     }
   *
   * The constructor of the handler is called as:
   *
   *     node = new PlotHandler(params)
   *
   * The handler will be invoked when evaluating an expression like:
   *
   *     node = math.parse('plot(sin(x), x)', nodes)
   *
   * @return {Node} node
   * @private
   */
  function parseCustomNodes(state) {
    var params = [];
    if (state.tokenType === TOKENTYPE.SYMBOL && hasOwnProperty(state.extraNodes, state.token)) {
      var CustomNode = state.extraNodes[state.token];
      getToken(state);

      // parse parameters
      if (state.token === '(') {
        params = [];
        openParams(state);
        getToken(state);
        if (state.token !== ')') {
          params.push(parseAssignment(state));

          // parse a list with parameters
          while (state.token === ',') {
            // eslint-disable-line no-unmodified-loop-condition
            getToken(state);
            params.push(parseAssignment(state));
          }
        }
        if (state.token !== ')') {
          throw createSyntaxError(state, 'Parenthesis ) expected');
        }
        closeParams(state);
        getToken(state);
      }

      // create a new custom node
      // noinspection JSValidateTypes
      return new CustomNode(params);
    }
    return parseSymbol(state);
  }

  /**
   * parse symbols: functions, variables, constants, units
   * @return {Node} node
   * @private
   */
  function parseSymbol(state) {
    var node, name;
    if (state.tokenType === TOKENTYPE.SYMBOL || state.tokenType === TOKENTYPE.DELIMITER && state.token in NAMED_DELIMITERS) {
      name = state.token;
      getToken(state);
      if (hasOwnProperty(CONSTANTS, name)) {
        // true, false, null, ...
        node = new ConstantNode(CONSTANTS[name]);
      } else if (NUMERIC_CONSTANTS.includes(name)) {
        // NaN, Infinity
        node = new ConstantNode(numeric(name, 'number'));
      } else {
        node = new SymbolNode(name);
      }

      // parse function parameters and matrix index
      node = parseAccessors(state, node);
      return node;
    }
    return parseString(state);
  }

  /**
   * parse accessors:
   * - function invocation in round brackets (...), for example sqrt(2)
   * - index enclosed in square brackets [...], for example A[2,3]
   * - dot notation for properties, like foo.bar
   * @param {Object} state
   * @param {Node} node    Node on which to apply the parameters. If there
   *                       are no parameters in the expression, the node
   *                       itself is returned
   * @param {string[]} [types]  Filter the types of notations
   *                            can be ['(', '[', '.']
   * @return {Node} node
   * @private
   */
  function parseAccessors(state, node, types) {
    var params;
    while ((state.token === '(' || state.token === '[' || state.token === '.') && (!types || types.includes(state.token))) {
      // eslint-disable-line no-unmodified-loop-condition
      params = [];
      if (state.token === '(') {
        if (isSymbolNode(node) || isAccessorNode(node)) {
          // function invocation like fn(2, 3) or obj.fn(2, 3)
          openParams(state);
          getToken(state);
          if (state.token !== ')') {
            params.push(parseAssignment(state));

            // parse a list with parameters
            while (state.token === ',') {
              // eslint-disable-line no-unmodified-loop-condition
              getToken(state);
              params.push(parseAssignment(state));
            }
          }
          if (state.token !== ')') {
            throw createSyntaxError(state, 'Parenthesis ) expected');
          }
          closeParams(state);
          getToken(state);
          node = new FunctionNode(node, params);
        } else {
          // implicit multiplication like (2+3)(4+5) or sqrt(2)(1+2)
          // don't parse it here but let it be handled by parseImplicitMultiplication
          // with correct precedence
          return node;
        }
      } else if (state.token === '[') {
        // index notation like variable[2, 3]
        openParams(state);
        getToken(state);
        if (state.token !== ']') {
          params.push(parseAssignment(state));

          // parse a list with parameters
          while (state.token === ',') {
            // eslint-disable-line no-unmodified-loop-condition
            getToken(state);
            params.push(parseAssignment(state));
          }
        }
        if (state.token !== ']') {
          throw createSyntaxError(state, 'Parenthesis ] expected');
        }
        closeParams(state);
        getToken(state);
        node = new AccessorNode(node, new IndexNode(params));
      } else {
        // dot notation like variable.prop
        getToken(state);
        var isPropertyName = state.tokenType === TOKENTYPE.SYMBOL || state.tokenType === TOKENTYPE.DELIMITER && state.token in NAMED_DELIMITERS;
        if (!isPropertyName) {
          throw createSyntaxError(state, 'Property name expected after dot');
        }
        params.push(new ConstantNode(state.token));
        getToken(state);
        var dotNotation = true;
        node = new AccessorNode(node, new IndexNode(params, dotNotation));
      }
    }
    return node;
  }

  /**
   * Parse a single or double quoted string.
   * @return {Node} node
   * @private
   */
  function parseString(state) {
    var node, str;
    if (state.token === '"' || state.token === "'") {
      str = parseStringToken(state, state.token);

      // create constant
      node = new ConstantNode(str);

      // parse index parameters
      node = parseAccessors(state, node);
      return node;
    }
    return parseMatrix(state);
  }

  /**
   * Parse a string surrounded by single or double quotes
   * @param {Object} state
   * @param {"'" | "\""} quote
   * @return {string}
   */
  function parseStringToken(state, quote) {
    var str = '';
    while (currentCharacter(state) !== '' && currentCharacter(state) !== quote) {
      if (currentCharacter(state) === '\\') {
        next(state);
        var char = currentCharacter(state);
        var escapeChar = ESCAPE_CHARACTERS[char];
        if (escapeChar !== undefined) {
          // an escaped control character like \" or \n
          str += escapeChar;
          state.index += 1;
        } else if (char === 'u') {
          // escaped unicode character
          var unicode = state.expression.slice(state.index + 1, state.index + 5);
          if (/^[0-9A-Fa-f]{4}$/.test(unicode)) {
            // test whether the string holds four hexadecimal values
            str += String.fromCharCode(parseInt(unicode, 16));
            state.index += 5;
          } else {
            throw createSyntaxError(state, "Invalid unicode character \\u".concat(unicode));
          }
        } else {
          throw createSyntaxError(state, "Bad escape character \\".concat(char));
        }
      } else {
        // any regular character
        str += currentCharacter(state);
        next(state);
      }
    }
    getToken(state);
    if (state.token !== quote) {
      throw createSyntaxError(state, "End of string ".concat(quote, " expected"));
    }
    getToken(state);
    return str;
  }

  /**
   * parse the matrix
   * @return {Node} node
   * @private
   */
  function parseMatrix(state) {
    var array, params, rows, cols;
    if (state.token === '[') {
      // matrix [...]
      openParams(state);
      getToken(state);
      if (state.token !== ']') {
        // this is a non-empty matrix
        var row = parseRow(state);
        if (state.token === ';') {
          // 2 dimensional array
          rows = 1;
          params = [row];

          // the rows of the matrix are separated by dot-comma's
          while (state.token === ';') {
            // eslint-disable-line no-unmodified-loop-condition
            getToken(state);
            if (state.token !== ']') {
              params[rows] = parseRow(state);
              rows++;
            }
          }
          if (state.token !== ']') {
            throw createSyntaxError(state, 'End of matrix ] expected');
          }
          closeParams(state);
          getToken(state);

          // check if the number of columns matches in all rows
          cols = params[0].items.length;
          for (var r = 1; r < rows; r++) {
            if (params[r].items.length !== cols) {
              throw createError(state, 'Column dimensions mismatch ' + '(' + params[r].items.length + ' !== ' + cols + ')');
            }
          }
          array = new ArrayNode(params);
        } else {
          // 1 dimensional vector
          if (state.token !== ']') {
            throw createSyntaxError(state, 'End of matrix ] expected');
          }
          closeParams(state);
          getToken(state);
          array = row;
        }
      } else {
        // this is an empty matrix "[ ]"
        closeParams(state);
        getToken(state);
        array = new ArrayNode([]);
      }
      return parseAccessors(state, array);
    }
    return parseObject(state);
  }

  /**
   * Parse a single comma-separated row from a matrix, like 'a, b, c'
   * @return {ArrayNode} node
   */
  function parseRow(state) {
    var params = [parseAssignment(state)];
    var len = 1;
    while (state.token === ',') {
      // eslint-disable-line no-unmodified-loop-condition
      getToken(state);

      // parse expression
      if (state.token !== ']' && state.token !== ';') {
        params[len] = parseAssignment(state);
        len++;
      }
    }
    return new ArrayNode(params);
  }

  /**
   * parse an object, enclosed in angle brackets{...}, for example {value: 2}
   * @return {Node} node
   * @private
   */
  function parseObject(state) {
    if (state.token === '{') {
      openParams(state);
      var key;
      var properties = {};
      do {
        getToken(state);
        if (state.token !== '}') {
          // parse key
          if (state.token === '"' || state.token === "'") {
            key = parseStringToken(state, state.token);
          } else if (state.tokenType === TOKENTYPE.SYMBOL || state.tokenType === TOKENTYPE.DELIMITER && state.token in NAMED_DELIMITERS) {
            key = state.token;
            getToken(state);
          } else {
            throw createSyntaxError(state, 'Symbol or string expected as object key');
          }

          // parse key/value separator
          if (state.token !== ':') {
            throw createSyntaxError(state, 'Colon : expected after object key');
          }
          getToken(state);

          // parse key
          properties[key] = parseAssignment(state);
        }
      } while (state.token === ','); // eslint-disable-line no-unmodified-loop-condition

      if (state.token !== '}') {
        throw createSyntaxError(state, 'Comma , or bracket } expected after object value');
      }
      closeParams(state);
      getToken(state);
      var node = new ObjectNode(properties);

      // parse index parameters
      node = parseAccessors(state, node);
      return node;
    }
    return parseNumber(state);
  }

  /**
   * parse a number
   * @return {Node} node
   * @private
   */
  function parseNumber(state) {
    var numberStr;
    if (state.tokenType === TOKENTYPE.NUMBER) {
      // this is a number
      numberStr = state.token;
      getToken(state);
      var numericType = safeNumberType(numberStr, config);
      var value = numeric(numberStr, numericType);
      return new ConstantNode(value);
    }
    return parseParentheses(state);
  }

  /**
   * parentheses
   * @return {Node} node
   * @private
   */
  function parseParentheses(state) {
    var node;

    // check if it is a parenthesized expression
    if (state.token === '(') {
      // parentheses (...)
      openParams(state);
      getToken(state);
      node = parseAssignment(state); // start again

      if (state.token !== ')') {
        throw createSyntaxError(state, 'Parenthesis ) expected');
      }
      closeParams(state);
      getToken(state);
      node = new ParenthesisNode(node);
      node = parseAccessors(state, node);
      return node;
    }
    return parseEnd(state);
  }

  /**
   * Evaluated when the expression is not yet ended but expected to end
   * @return {Node} res
   * @private
   */
  function parseEnd(state) {
    if (state.token === '') {
      // syntax error or unexpected end of expression
      throw createSyntaxError(state, 'Unexpected end of expression');
    } else {
      throw createSyntaxError(state, 'Value expected');
    }
  }

  /**
   * Shortcut for getting the current row value (one based)
   * Returns the line of the currently handled expression
   * @private
   */
  /* TODO: implement keeping track on the row number
  function row () {
    return null
  }
  */

  /**
   * Shortcut for getting the current col value (one based)
   * Returns the column (position) where the last state.token starts
   * @private
   */
  function col(state) {
    return state.index - state.token.length + 1;
  }

  /**
   * Create an error
   * @param {Object} state
   * @param {string} message
   * @return {SyntaxError} instantiated error
   * @private
   */
  function createSyntaxError(state, message) {
    var c = col(state);
    var error = new SyntaxError(message + ' (char ' + c + ')');
    error.char = c;
    return error;
  }

  /**
   * Create an error
   * @param {Object} state
   * @param {string} message
   * @return {Error} instantiated error
   * @private
   */
  function createError(state, message) {
    var c = col(state);
    var error = new SyntaxError(message + ' (char ' + c + ')');
    error.char = c;
    return error;
  }

  // Now that we can parse, automatically convert strings to Nodes by parsing
  typed.addConversion({
    from: 'string',
    to: 'Node',
    convert: parse
  });
  return parse;
});

var name$1q = 'compile';
var dependencies$1q = ['typed', 'parse'];
var createCompile = /* #__PURE__ */factory(name$1q, dependencies$1q, _ref => {
  var {
    typed,
    parse
  } = _ref;
  /**
   * Parse and compile an expression.
   * Returns a an object with a function `evaluate([scope])` to evaluate the
   * compiled expression.
   *
   * Syntax:
   *
   *     math.compile(expr)                       // returns one node
   *     math.compile([expr1, expr2, expr3, ...]) // returns an array with nodes
   *
   * Examples:
   *
   *     const code1 = math.compile('sqrt(3^2 + 4^2)')
   *     code1.evaluate() // 5
   *
   *     let scope = {a: 3, b: 4}
   *     const code2 = math.compile('a * b') // 12
   *     code2.evaluate(scope) // 12
   *     scope.a = 5
   *     code2.evaluate(scope) // 20
   *
   *     const nodes = math.compile(['a = 3', 'b = 4', 'a * b'])
   *     nodes[2].evaluate() // 12
   *
   * See also:
   *
   *    parse, evaluate
   *
   * @param {string | string[] | Array | Matrix} expr
   *            The expression to be compiled
   * @return {{evaluate: Function} | Array.<{evaluate: Function}>} code
   *            An object with the compiled expression
   * @throws {Error}
   */
  return typed(name$1q, {
    string: function string(expr) {
      return parse(expr).compile();
    },
    'Array | Matrix': function ArrayMatrix(expr) {
      return deepMap(expr, function (entry) {
        return parse(entry).compile();
      });
    }
  });
});

var name$1p = 'evaluate';
var dependencies$1p = ['typed', 'parse'];
var createEvaluate = /* #__PURE__ */factory(name$1p, dependencies$1p, _ref => {
  var {
    typed,
    parse
  } = _ref;
  /**
   * Evaluate an expression.
   *
   * Note the evaluating arbitrary expressions may involve security risks,
   * see [https://mathjs.org/docs/expressions/security.html](https://mathjs.org/docs/expressions/security.html) for more information.
   *
   * Syntax:
   *
   *     math.evaluate(expr)
   *     math.evaluate(expr, scope)
   *     math.evaluate([expr1, expr2, expr3, ...])
   *     math.evaluate([expr1, expr2, expr3, ...], scope)
   *
   * Example:
   *
   *     math.evaluate('(2+3)/4')                // 1.25
   *     math.evaluate('sqrt(3^2 + 4^2)')        // 5
   *     math.evaluate('sqrt(-4)')               // 2i
   *     math.evaluate(['a=3', 'b=4', 'a*b'])    // [3, 4, 12]
   *
   *     let scope = {a:3, b:4}
   *     math.evaluate('a * b', scope)           // 12
   *
   * See also:
   *
   *    parse, compile
   *
   * @param {string | string[] | Matrix} expr   The expression to be evaluated
   * @param {Object} [scope]                    Scope to read/write variables
   * @return {*} The result of the expression
   * @throws {Error}
   */
  return typed(name$1p, {
    string: function string(expr) {
      var scope = createEmptyMap();
      return parse(expr).compile().evaluate(scope);
    },
    'string, Map | Object': function stringMapObject(expr, scope) {
      return parse(expr).compile().evaluate(scope);
    },
    'Array | Matrix': function ArrayMatrix(expr) {
      var scope = createEmptyMap();
      return deepMap(expr, function (entry) {
        return parse(entry).compile().evaluate(scope);
      });
    },
    'Array | Matrix, Map | Object': function ArrayMatrixMapObject(expr, scope) {
      return deepMap(expr, function (entry) {
        return parse(entry).compile().evaluate(scope);
      });
    }
  });
});

var name$1o = 'Parser';
var dependencies$1o = ['evaluate'];
var createParserClass = /* #__PURE__ */factory(name$1o, dependencies$1o, _ref => {
  var {
    evaluate
  } = _ref;
  /**
   * @constructor Parser
   * Parser contains methods to evaluate or parse expressions, and has a number
   * of convenience methods to get, set, and remove variables from memory. Parser
   * keeps a scope containing variables in memory, which is used for all
   * evaluations.
   *
   * Methods:
   *    const result = parser.evaluate(expr)  // evaluate an expression
   *    const value = parser.get(name)        // retrieve a variable from the parser
   *    const values = parser.getAll()        // retrieve all defined variables
   *    parser.set(name, value)               // set a variable in the parser
   *    parser.remove(name)                   // clear a variable from the
   *                                          // parsers scope
   *    parser.clear()                        // clear the parsers scope
   *
   * Example usage:
   *    const parser = new Parser()
   *    // Note: there is a convenience method which can be used instead:
   *    // const parser = new math.parser()
   *
   *    // evaluate expressions
   *    parser.evaluate('sqrt(3^2 + 4^2)')        // 5
   *    parser.evaluate('sqrt(-4)')               // 2i
   *    parser.evaluate('2 inch in cm')           // 5.08 cm
   *    parser.evaluate('cos(45 deg)')            // 0.7071067811865476
   *
   *    // define variables and functions
   *    parser.evaluate('x = 7 / 2')              // 3.5
   *    parser.evaluate('x + 3')                  // 6.5
   *    parser.evaluate('f(x, y) = x^y')          // f(x, y)
   *    parser.evaluate('f(2, 3)')                // 8
   *
   *    // get and set variables and functions
   *    const x = parser.get('x')                 // 3.5
   *    const f = parser.get('f')                 // function
   *    const g = f(3, 2)                         // 9
   *    parser.set('h', 500)
   *    const i = parser.evaluate('h / 2')        // 250
   *    parser.set('hello', function (name) {
   *        return 'hello, ' + name + '!'
   *    })
   *    parser.evaluate('hello("user")')          // "hello, user!"
   *
   *    // clear defined functions and variables
   *    parser.clear()
   *
   */
  function Parser() {
    if (!(this instanceof Parser)) {
      throw new SyntaxError('Constructor must be called with the new operator');
    }
    Object.defineProperty(this, 'scope', {
      value: createEmptyMap(),
      writable: false
    });
  }

  /**
   * Attach type information
   */
  Parser.prototype.type = 'Parser';
  Parser.prototype.isParser = true;

  /**
   * Parse and evaluate the given expression
   * @param {string | string[]} expr   A string containing an expression,
   *                                   for example "2+3", or a list with expressions
   * @return {*} result     The result, or undefined when the expression was empty
   * @throws {Error}
   */
  Parser.prototype.evaluate = function (expr) {
    // TODO: validate arguments
    return evaluate(expr, this.scope);
  };

  /**
   * Get a variable (a function or variable) by name from the parsers scope.
   * Returns undefined when not found
   * @param {string} name
   * @return {* | undefined} value
   */
  Parser.prototype.get = function (name) {
    // TODO: validate arguments
    if (this.scope.has(name)) {
      return this.scope.get(name);
    }
  };

  /**
   * Get a map with all defined variables
   * @return {Object} values
   */
  Parser.prototype.getAll = function () {
    return toObject(this.scope);
  };

  /**
   * Get a map with all defined variables
   * @return {Map} values
   */
  Parser.prototype.getAllAsMap = function () {
    return this.scope;
  };

  /**
   * Set a symbol (a function or variable) by name from the parsers scope.
   * @param {string} name
   * @param {* | undefined} value
   */
  Parser.prototype.set = function (name, value) {
    this.scope.set(name, value);
    return value;
  };

  /**
   * Remove a variable from the parsers scope
   * @param {string} name
   */
  Parser.prototype.remove = function (name) {
    this.scope.delete(name);
  };

  /**
   * Clear the scope with variables and functions
   */
  Parser.prototype.clear = function () {
    this.scope.clear();
  };
  return Parser;
}, {
  isClass: true
});

var name$1n = 'parser';
var dependencies$1n = ['typed', 'Parser'];
var createParser = /* #__PURE__ */factory(name$1n, dependencies$1n, _ref => {
  var {
    typed,
    Parser
  } = _ref;
  /**
   * Create a parser. The function creates a new `math.Parser` object.
   *
   * Syntax:
   *
   *    math.parser()
   *
   * Examples:
   *
   *     const parser = new math.parser()
   *
   *     // evaluate expressions
   *     const a = parser.evaluate('sqrt(3^2 + 4^2)') // 5
   *     const b = parser.evaluate('sqrt(-4)')        // 2i
   *     const c = parser.evaluate('2 inch in cm')    // 5.08 cm
   *     const d = parser.evaluate('cos(45 deg)')     // 0.7071067811865476
   *
   *     // define variables and functions
   *     parser.evaluate('x = 7 / 2')             // 3.5
   *     parser.evaluate('x + 3')                 // 6.5
   *     parser.evaluate('f(x, y) = x^y')         // f(x, y)
   *     parser.evaluate('f(2, 3)')               // 8
   *
   *     // get and set variables and functions
   *     const x = parser.get('x')                // 3.5
   *     const f = parser.get('f')                // function
   *     const g = f(3, 2)                        // 9
   *     parser.set('h', 500)
   *     const i = parser.evaluate('h / 2')       // 250
   *     parser.set('hello', function (name) {
   *       return 'hello, ' + name + '!'
   *     })
   *     parser.evaluate('hello("user")')         // "hello, user!"
   *
   *     // clear defined functions and variables
   *     parser.clear()
   *
   * See also:
   *
   *    evaluate, compile, parse
   *
   * @return {Parser} Parser
   */
  return typed(name$1n, {
    '': function _() {
      return new Parser();
    }
  });
});

var name$1m = 'lup';
var dependencies$1m = ['typed', 'matrix', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'larger', 'equalScalar', 'unaryMinus', 'DenseMatrix', 'SparseMatrix', 'Spa'];
var createLup = /* #__PURE__ */factory(name$1m, dependencies$1m, _ref => {
  var {
    typed,
    matrix,
    abs,
    addScalar,
    divideScalar,
    multiplyScalar,
    subtractScalar,
    larger,
    equalScalar,
    unaryMinus,
    DenseMatrix,
    SparseMatrix,
    Spa
  } = _ref;
  /**
   * Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a
   * row permutation vector `p` where `A[p,:] = L * U`
   *
   * Syntax:
   *
   *    math.lup(A)
   *
   * Example:
   *
   *    const m = [[2, 1], [1, 4]]
   *    const r = math.lup(m)
   *    // r = {
   *    //   L: [[1, 0], [0.5, 1]],
   *    //   U: [[2, 1], [0, 3.5]],
   *    //   P: [0, 1]
   *    // }
   *
   * See also:
   *
   *    slu, lsolve, lusolve, usolve
   *
   * @param {Matrix | Array} A    A two dimensional matrix or array for which to get the LUP decomposition.
   *
   * @return {{L: Array | Matrix, U: Array | Matrix, P: Array.<number>}} The lower triangular matrix, the upper triangular matrix and the permutation matrix.
   */
  return typed(name$1m, {
    DenseMatrix: function DenseMatrix(m) {
      return _denseLUP(m);
    },
    SparseMatrix: function SparseMatrix(m) {
      return _sparseLUP(m);
    },
    Array: function Array(a) {
      // create dense matrix from array
      var m = matrix(a);
      // lup, use matrix implementation
      var r = _denseLUP(m);
      // result
      return {
        L: r.L.valueOf(),
        U: r.U.valueOf(),
        p: r.p
      };
    }
  });
  function _denseLUP(m) {
    // rows & columns
    var rows = m._size[0];
    var columns = m._size[1];
    // minimum rows and columns
    var n = Math.min(rows, columns);
    // matrix array, clone original data
    var data = clone$2(m._data);
    // l matrix arrays
    var ldata = [];
    var lsize = [rows, n];
    // u matrix arrays
    var udata = [];
    var usize = [n, columns];
    // vars
    var i, j, k;
    // permutation vector
    var p = [];
    for (i = 0; i < rows; i++) {
      p[i] = i;
    }
    // loop columns
    for (j = 0; j < columns; j++) {
      // skip first column in upper triangular matrix
      if (j > 0) {
        // loop rows
        for (i = 0; i < rows; i++) {
          // min i,j
          var min = Math.min(i, j);
          // v[i, j]
          var s = 0;
          // loop up to min
          for (k = 0; k < min; k++) {
            // s = l[i, k] - data[k, j]
            s = addScalar(s, multiplyScalar(data[i][k], data[k][j]));
          }
          data[i][j] = subtractScalar(data[i][j], s);
        }
      }
      // row with larger value in cvector, row >= j
      var pi = j;
      var pabsv = 0;
      var vjj = 0;
      // loop rows
      for (i = j; i < rows; i++) {
        // data @ i, j
        var v = data[i][j];
        // absolute value
        var absv = abs(v);
        // value is greater than pivote value
        if (larger(absv, pabsv)) {
          // store row
          pi = i;
          // update max value
          pabsv = absv;
          // value @ [j, j]
          vjj = v;
        }
      }
      // swap rows (j <-> pi)
      if (j !== pi) {
        // swap values j <-> pi in p
        p[j] = [p[pi], p[pi] = p[j]][0];
        // swap j <-> pi in data
        DenseMatrix._swapRows(j, pi, data);
      }
      // check column is in lower triangular matrix
      if (j < rows) {
        // loop rows (lower triangular matrix)
        for (i = j + 1; i < rows; i++) {
          // value @ i, j
          var vij = data[i][j];
          if (!equalScalar(vij, 0)) {
            // update data
            data[i][j] = divideScalar(data[i][j], vjj);
          }
        }
      }
    }
    // loop columns
    for (j = 0; j < columns; j++) {
      // loop rows
      for (i = 0; i < rows; i++) {
        // initialize row in arrays
        if (j === 0) {
          // check row exists in upper triangular matrix
          if (i < columns) {
            // U
            udata[i] = [];
          }
          // L
          ldata[i] = [];
        }
        // check we are in the upper triangular matrix
        if (i < j) {
          // check row exists in upper triangular matrix
          if (i < columns) {
            // U
            udata[i][j] = data[i][j];
          }
          // check column exists in lower triangular matrix
          if (j < rows) {
            // L
            ldata[i][j] = 0;
          }
          continue;
        }
        // diagonal value
        if (i === j) {
          // check row exists in upper triangular matrix
          if (i < columns) {
            // U
            udata[i][j] = data[i][j];
          }
          // check column exists in lower triangular matrix
          if (j < rows) {
            // L
            ldata[i][j] = 1;
          }
          continue;
        }
        // check row exists in upper triangular matrix
        if (i < columns) {
          // U
          udata[i][j] = 0;
        }
        // check column exists in lower triangular matrix
        if (j < rows) {
          // L
          ldata[i][j] = data[i][j];
        }
      }
    }
    // l matrix
    var l = new DenseMatrix({
      data: ldata,
      size: lsize
    });
    // u matrix
    var u = new DenseMatrix({
      data: udata,
      size: usize
    });
    // p vector
    var pv = [];
    for (i = 0, n = p.length; i < n; i++) {
      pv[p[i]] = i;
    }
    // return matrices
    return {
      L: l,
      U: u,
      p: pv,
      toString: function toString() {
        return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p;
      }
    };
  }
  function _sparseLUP(m) {
    // rows & columns
    var rows = m._size[0];
    var columns = m._size[1];
    // minimum rows and columns
    var n = Math.min(rows, columns);
    // matrix arrays (will not be modified, thanks to permutation vector)
    var values = m._values;
    var index = m._index;
    var ptr = m._ptr;
    // l matrix arrays
    var lvalues = [];
    var lindex = [];
    var lptr = [];
    var lsize = [rows, n];
    // u matrix arrays
    var uvalues = [];
    var uindex = [];
    var uptr = [];
    var usize = [n, columns];
    // vars
    var i, j, k;
    // permutation vectors, (current index -> original index) and (original index -> current index)
    var pvCo = [];
    var pvOc = [];
    for (i = 0; i < rows; i++) {
      pvCo[i] = i;
      pvOc[i] = i;
    }
    // swap indices in permutation vectors (condition x < y)!
    var swapIndeces = function swapIndeces(x, y) {
      // find pv indeces getting data from x and y
      var kx = pvOc[x];
      var ky = pvOc[y];
      // update permutation vector current -> original
      pvCo[kx] = y;
      pvCo[ky] = x;
      // update permutation vector original -> current
      pvOc[x] = ky;
      pvOc[y] = kx;
    };
    // loop columns
    var _loop = function _loop() {
      // sparse accumulator
      var spa = new Spa();
      // check lower triangular matrix has a value @ column j
      if (j < rows) {
        // update ptr
        lptr.push(lvalues.length);
        // first value in j column for lower triangular matrix
        lvalues.push(1);
        lindex.push(j);
      }
      // update ptr
      uptr.push(uvalues.length);
      // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
      var k0 = ptr[j];
      var k1 = ptr[j + 1];
      // copy column j into sparse accumulator
      for (k = k0; k < k1; k++) {
        // row
        i = index[k];
        // copy column values into sparse accumulator (use permutation vector)
        spa.set(pvCo[i], values[k]);
      }
      // skip first column in upper triangular matrix
      if (j > 0) {
        // loop rows in column j (above diagonal)
        spa.forEach(0, j - 1, function (k, vkj) {
          // loop rows in column k (L)
          SparseMatrix._forEachRow(k, lvalues, lindex, lptr, function (i, vik) {
            // check row is below k
            if (i > k) {
              // update spa value
              spa.accumulate(i, unaryMinus(multiplyScalar(vik, vkj)));
            }
          });
        });
      }
      // row with larger value in spa, row >= j
      var pi = j;
      var vjj = spa.get(j);
      var pabsv = abs(vjj);
      // loop values in spa (order by row, below diagonal)
      spa.forEach(j + 1, rows - 1, function (x, v) {
        // absolute value
        var absv = abs(v);
        // value is greater than pivote value
        if (larger(absv, pabsv)) {
          // store row
          pi = x;
          // update max value
          pabsv = absv;
          // value @ [j, j]
          vjj = v;
        }
      });
      // swap rows (j <-> pi)
      if (j !== pi) {
        // swap values j <-> pi in L
        SparseMatrix._swapRows(j, pi, lsize[1], lvalues, lindex, lptr);
        // swap values j <-> pi in U
        SparseMatrix._swapRows(j, pi, usize[1], uvalues, uindex, uptr);
        // swap values in spa
        spa.swap(j, pi);
        // update permutation vector (swap values @ j, pi)
        swapIndeces(j, pi);
      }
      // loop values in spa (order by row)
      spa.forEach(0, rows - 1, function (x, v) {
        // check we are above diagonal
        if (x <= j) {
          // update upper triangular matrix
          uvalues.push(v);
          uindex.push(x);
        } else {
          // update value
          v = divideScalar(v, vjj);
          // check value is non zero
          if (!equalScalar(v, 0)) {
            // update lower triangular matrix
            lvalues.push(v);
            lindex.push(x);
          }
        }
      });
    };
    for (j = 0; j < columns; j++) {
      _loop();
    }
    // update ptrs
    uptr.push(uvalues.length);
    lptr.push(lvalues.length);

    // return matrices
    return {
      L: new SparseMatrix({
        values: lvalues,
        index: lindex,
        ptr: lptr,
        size: lsize
      }),
      U: new SparseMatrix({
        values: uvalues,
        index: uindex,
        ptr: uptr,
        size: usize
      }),
      p: pvCo,
      toString: function toString() {
        return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p;
      }
    };
  }
});

var name$1l = 'qr';
var dependencies$1l = ['typed', 'matrix', 'zeros', 'identity', 'isZero', 'equal', 'sign', 'sqrt', 'conj', 'unaryMinus', 'addScalar', 'divideScalar', 'multiplyScalar', 'subtractScalar', 'complex'];
var createQr = /* #__PURE__ */factory(name$1l, dependencies$1l, _ref => {
  var {
    typed,
    matrix,
    zeros,
    identity,
    isZero,
    equal,
    sign,
    sqrt,
    conj,
    unaryMinus,
    addScalar,
    divideScalar,
    multiplyScalar,
    subtractScalar,
    complex
  } = _ref;
  /**
   * Calculate the Matrix QR decomposition. Matrix `A` is decomposed in
   * two matrices (`Q`, `R`) where `Q` is an
   * orthogonal matrix and `R` is an upper triangular matrix.
   *
   * Syntax:
   *
   *    math.qr(A)
   *
   * Example:
   *
   *    const m = [
   *      [1, -1,  4],
   *      [1,  4, -2],
   *      [1,  4,  2],
   *      [1,  -1, 0]
   *    ]
   *    const result = math.qr(m)
   *    // r = {
   *    //   Q: [
   *    //     [0.5, -0.5,   0.5],
   *    //     [0.5,  0.5,  -0.5],
   *    //     [0.5,  0.5,   0.5],
   *    //     [0.5, -0.5,  -0.5],
   *    //   ],
   *    //   R: [
   *    //     [2, 3,  2],
   *    //     [0, 5, -2],
   *    //     [0, 0,  4],
   *    //     [0, 0,  0]
   *    //   ]
   *    // }
   *
   * See also:
   *
   *    lup, lusolve
   *
   * @param {Matrix | Array} A    A two dimensional matrix or array
   * for which to get the QR decomposition.
   *
   * @return {{Q: Array | Matrix, R: Array | Matrix}} Q: the orthogonal
   * matrix and R: the upper triangular matrix
   */
  return _extends$1(typed(name$1l, {
    DenseMatrix: function DenseMatrix(m) {
      return _denseQR(m);
    },
    SparseMatrix: function SparseMatrix(m) {
      return _sparseQR();
    },
    Array: function Array(a) {
      // create dense matrix from array
      var m = matrix(a);
      // lup, use matrix implementation
      var r = _denseQR(m);
      // result
      return {
        Q: r.Q.valueOf(),
        R: r.R.valueOf()
      };
    }
  }), {
    _denseQRimpl
  });
  function _denseQRimpl(m) {
    // rows & columns (m x n)
    var rows = m._size[0]; // m
    var cols = m._size[1]; // n

    var Q = identity([rows], 'dense');
    var Qdata = Q._data;
    var R = m.clone();
    var Rdata = R._data;

    // vars
    var i, j, k;
    var w = zeros([rows], '');
    for (k = 0; k < Math.min(cols, rows); ++k) {
      /*
       * **k-th Household matrix**
       *
       * The matrix I - 2*v*transpose(v)
       * x     = first column of A
       * x1    = first element of x
       * alpha = x1 / |x1| * |x|
       * e1    = tranpose([1, 0, 0, ...])
       * u     = x - alpha * e1
       * v     = u / |u|
       *
       * Household matrix = I - 2 * v * tranpose(v)
       *
       *  * Initially Q = I and R = A.
       *  * Household matrix is a reflection in a plane normal to v which
       *    will zero out all but the top right element in R.
       *  * Appplying reflection to both Q and R will not change product.
       *  * Repeat this process on the (1,1) minor to get R as an upper
       *    triangular matrix.
       *  * Reflections leave the magnitude of the columns of Q unchanged
       *    so Q remains othoganal.
       *
       */

      var pivot = Rdata[k][k];
      var sgn = unaryMinus(equal(pivot, 0) ? 1 : sign(pivot));
      var conjSgn = conj(sgn);
      var alphaSquared = 0;
      for (i = k; i < rows; i++) {
        alphaSquared = addScalar(alphaSquared, multiplyScalar(Rdata[i][k], conj(Rdata[i][k])));
      }
      var alpha = multiplyScalar(sgn, sqrt(alphaSquared));
      if (!isZero(alpha)) {
        // first element in vector u
        var u1 = subtractScalar(pivot, alpha);

        // w = v * u1 / |u|    (only elements k to (rows-1) are used)
        w[k] = 1;
        for (i = k + 1; i < rows; i++) {
          w[i] = divideScalar(Rdata[i][k], u1);
        }

        // tau = - conj(u1 / alpha)
        var tau = unaryMinus(conj(divideScalar(u1, alpha)));
        var s = void 0;

        /*
         * tau and w have been choosen so that
         *
         * 2 * v * tranpose(v) = tau * w * tranpose(w)
         */

        /*
         * -- calculate R = R - tau * w * tranpose(w) * R --
         * Only do calculation with rows k to (rows-1)
         * Additionally columns 0 to (k-1) will not be changed by this
         *   multiplication so do not bother recalculating them
         */
        for (j = k; j < cols; j++) {
          s = 0.0;

          // calculate jth element of [tranpose(w) * R]
          for (i = k; i < rows; i++) {
            s = addScalar(s, multiplyScalar(conj(w[i]), Rdata[i][j]));
          }

          // calculate the jth element of [tau * transpose(w) * R]
          s = multiplyScalar(s, tau);
          for (i = k; i < rows; i++) {
            Rdata[i][j] = multiplyScalar(subtractScalar(Rdata[i][j], multiplyScalar(w[i], s)), conjSgn);
          }
        }
        /*
         * -- calculate Q = Q - tau * Q * w * transpose(w) --
         * Q is a square matrix (rows x rows)
         * Only do calculation with columns k to (rows-1)
         * Additionally rows 0 to (k-1) will not be changed by this
         *   multiplication so do not bother recalculating them
         */
        for (i = 0; i < rows; i++) {
          s = 0.0;

          // calculate ith element of [Q * w]
          for (j = k; j < rows; j++) {
            s = addScalar(s, multiplyScalar(Qdata[i][j], w[j]));
          }

          // calculate the ith element of [tau * Q * w]
          s = multiplyScalar(s, tau);
          for (j = k; j < rows; ++j) {
            Qdata[i][j] = divideScalar(subtractScalar(Qdata[i][j], multiplyScalar(s, conj(w[j]))), conjSgn);
          }
        }
      }
    }

    // return matrices
    return {
      Q,
      R,
      toString: function toString() {
        return 'Q: ' + this.Q.toString() + '\nR: ' + this.R.toString();
      }
    };
  }
  function _denseQR(m) {
    var ret = _denseQRimpl(m);
    var Rdata = ret.R._data;
    if (m._data.length > 0) {
      var zero = Rdata[0][0].type === 'Complex' ? complex(0) : 0;
      for (var i = 0; i < Rdata.length; ++i) {
        for (var j = 0; j < i && j < (Rdata[0] || []).length; ++j) {
          Rdata[i][j] = zero;
        }
      }
    }
    return ret;
  }
  function _sparseQR(m) {
    throw new Error('qr not implemented for sparse matrices yet');
  }
});

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source

/**
 * Permutes a sparse matrix C = P * A * Q
 *
 * @param {SparseMatrix}  a         The Matrix A
 * @param {Array}   pinv            The row permutation vector
 * @param {Array}   q               The column permutation vector
 * @param {boolean} values          Create a pattern matrix (false), values and pattern otherwise
 *
 * @return {Matrix}                 C = P * A * Q, null on error
 */
function csPermute(a, pinv, q, values) {
  // a arrays
  var avalues = a._values;
  var aindex = a._index;
  var aptr = a._ptr;
  var asize = a._size;
  var adt = a._datatype;
  // rows & columns
  var m = asize[0];
  var n = asize[1];
  // c arrays
  var cvalues = values && a._values ? [] : null;
  var cindex = []; // (aptr[n])
  var cptr = []; // (n + 1)
  // initialize vars
  var nz = 0;
  // loop columns
  for (var k = 0; k < n; k++) {
    // column k of C is column q[k] of A
    cptr[k] = nz;
    // apply column permutation
    var j = q ? q[k] : k;
    // loop values in column j of A
    for (var t0 = aptr[j], t1 = aptr[j + 1], t = t0; t < t1; t++) {
      // row i of A is row pinv[i] of C
      var r = pinv ? pinv[aindex[t]] : aindex[t];
      // index
      cindex[nz] = r;
      // check we need to populate values
      if (cvalues) {
        cvalues[nz] = avalues[t];
      }
      // increment number of nonzero elements
      nz++;
    }
  }
  // finalize the last column of C
  cptr[n] = nz;
  // return C matrix
  return a.createSparseMatrix({
    values: cvalues,
    index: cindex,
    ptr: cptr,
    size: [m, n],
    datatype: adt
  });
}

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source

/**
 * Depth-first search and postorder of a tree rooted at node j
 *
 * @param {Number}  j               The tree node
 * @param {Number}  k
 * @param {Array}   w               The workspace array
 * @param {Number}  head            The index offset within the workspace for the head array
 * @param {Number}  next            The index offset within the workspace for the next array
 * @param {Array}   post            The post ordering array
 * @param {Number}  stack           The index offset within the workspace for the stack array
 */
function csTdfs(j, k, w, head, next, post, stack) {
  // variables
  var top = 0;
  // place j on the stack
  w[stack] = j;
  // while (stack is not empty)
  while (top >= 0) {
    // p = top of stack
    var p = w[stack + top];
    // i = youngest child of p
    var i = w[head + p];
    if (i === -1) {
      // p has no unordered children left
      top--;
      // node p is the kth postordered node
      post[k++] = p;
    } else {
      // remove i from children of p
      w[head + p] = w[next + i];
      // increment top
      ++top;
      // start dfs on child node i
      w[stack + top] = i;
    }
  }
  return k;
}

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.

/**
 * Post order a tree of forest
 *
 * @param {Array}   parent          The tree or forest
 * @param {Number}  n               Number of columns
 */
function csPost(parent, n) {
  // check inputs
  if (!parent) {
    return null;
  }
  // vars
  var k = 0;
  var j;
  // allocate result
  var post = []; // (n)
  // workspace, head: first n entries, next: next n entries, stack: last n entries
  var w = []; // (3 * n)
  var head = 0;
  var next = n;
  var stack = 2 * n;
  // initialize workspace
  for (j = 0; j < n; j++) {
    // empty linked lists
    w[head + j] = -1;
  }
  // traverse nodes in reverse order
  for (j = n - 1; j >= 0; j--) {
    // check j is a root
    if (parent[j] === -1) {
      continue;
    }
    // add j to list of its parent
    w[next + j] = w[head + parent[j]];
    w[head + parent[j]] = j;
  }
  // loop nodes
  for (j = 0; j < n; j++) {
    // skip j if it is not a root
    if (parent[j] !== -1) {
      continue;
    }
    // depth-first search
    k = csTdfs(j, k, w, head, next, post, stack);
  }
  return post;
}

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source

/**
 * Computes the elimination tree of Matrix A (using triu(A)) or the
 * elimination tree of A'A without forming A'A.
 *
 * @param {Matrix}  a               The A Matrix
 * @param {boolean} ata             A value of true the function computes the etree of A'A
 */
function csEtree(a, ata) {
  // check inputs
  if (!a) {
    return null;
  }
  // a arrays
  var aindex = a._index;
  var aptr = a._ptr;
  var asize = a._size;
  // rows & columns
  var m = asize[0];
  var n = asize[1];

  // allocate result
  var parent = []; // (n)

  // allocate workspace
  var w = []; // (n + (ata ? m : 0))
  var ancestor = 0; // first n entries in w
  var prev = n; // last m entries (ata = true)

  var i, inext;

  // check we are calculating A'A
  if (ata) {
    // initialize workspace
    for (i = 0; i < m; i++) {
      w[prev + i] = -1;
    }
  }
  // loop columns
  for (var k = 0; k < n; k++) {
    // node k has no parent yet
    parent[k] = -1;
    // nor does k have an ancestor
    w[ancestor + k] = -1;
    // values in column k
    for (var p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) {
      // row
      var r = aindex[p];
      // node
      i = ata ? w[prev + r] : r;
      // traverse from i to k
      for (; i !== -1 && i < k; i = inext) {
        // inext = ancestor of i
        inext = w[ancestor + i];
        // path compression
        w[ancestor + i] = k;
        // check no anc., parent is k
        if (inext === -1) {
          parent[i] = k;
        }
      }
      if (ata) {
        w[prev + r] = k;
      }
    }
  }
  return parent;
}

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source

/**
 * Keeps entries in the matrix when the callback function returns true, removes the entry otherwise
 *
 * @param {Matrix}   a              The sparse matrix
 * @param {function} callback       The callback function, function will be invoked with the following args:
 *                                    - The entry row
 *                                    - The entry column
 *                                    - The entry value
 *                                    - The state parameter
 * @param {any}      other          The state
 *
 * @return                          The number of nonzero elements in the matrix
 */
function csFkeep(a, callback, other) {
  // a arrays
  var avalues = a._values;
  var aindex = a._index;
  var aptr = a._ptr;
  var asize = a._size;
  // columns
  var n = asize[1];
  // nonzero items
  var nz = 0;
  // loop columns
  for (var j = 0; j < n; j++) {
    // get current location of col j
    var p = aptr[j];
    // record new location of col j
    aptr[j] = nz;
    for (; p < aptr[j + 1]; p++) {
      // check we need to keep this item
      if (callback(aindex[p], j, avalues ? avalues[p] : 1, other)) {
        // keep A(i,j)
        aindex[nz] = aindex[p];
        // check we need to process values (pattern only)
        if (avalues) {
          avalues[nz] = avalues[p];
        }
        // increment nonzero items
        nz++;
      }
    }
  }
  // finalize A
  aptr[n] = nz;
  // trim arrays
  aindex.splice(nz, aindex.length - nz);
  // check we need to process values (pattern only)
  if (avalues) {
    avalues.splice(nz, avalues.length - nz);
  }
  // return number of nonzero items
  return nz;
}

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source

/**
 * This function "flips" its input about the integer -1.
 *
 * @param {Number}  i               The value to flip
 */
function csFlip(i) {
  // flip the value
  return -i - 2;
}

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
var name$1k = 'csAmd';
var dependencies$1k = ['add', 'multiply', 'transpose'];
var createCsAmd = /* #__PURE__ */factory(name$1k, dependencies$1k, _ref => {
  var {
    add,
    multiply,
    transpose
  } = _ref;
  /**
   * Approximate minimum degree ordering. The minimum degree algorithm is a widely used
   * heuristic for finding a permutation P so that P*A*P' has fewer nonzeros in its factorization
   * than A. It is a gready method that selects the sparsest pivot row and column during the course
   * of a right looking sparse Cholesky factorization.
   *
   * @param {Number} order    0: Natural, 1: Cholesky, 2: LU, 3: QR
   * @param {Matrix} m        Sparse Matrix
   */
  return function csAmd(order, a) {
    // check input parameters
    if (!a || order <= 0 || order > 3) {
      return null;
    }
    // a matrix arrays
    var asize = a._size;
    // rows and columns
    var m = asize[0];
    var n = asize[1];
    // initialize vars
    var lemax = 0;
    // dense threshold
    var dense = Math.max(16, 10 * Math.sqrt(n));
    dense = Math.min(n - 2, dense);
    // create target matrix C
    var cm = _createTargetMatrix(order, a, m, n, dense);
    // drop diagonal entries
    csFkeep(cm, _diag, null);
    // C matrix arrays
    var cindex = cm._index;
    var cptr = cm._ptr;

    // number of nonzero elements in C
    var cnz = cptr[n];

    // allocate result (n+1)
    var P = [];

    // create workspace (8 * (n + 1))
    var W = [];
    var len = 0; // first n + 1 entries
    var nv = n + 1; // next n + 1 entries
    var next = 2 * (n + 1); // next n + 1 entries
    var head = 3 * (n + 1); // next n + 1 entries
    var elen = 4 * (n + 1); // next n + 1 entries
    var degree = 5 * (n + 1); // next n + 1 entries
    var w = 6 * (n + 1); // next n + 1 entries
    var hhead = 7 * (n + 1); // last n + 1 entries

    // use P as workspace for last
    var last = P;

    // initialize quotient graph
    var mark = _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree);

    // initialize degree lists
    var nel = _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next);

    // minimum degree node
    var mindeg = 0;

    // vars
    var i, j, k, k1, k2, e, pj, ln, nvi, pk, eln, p1, p2, pn, h, d;

    // while (selecting pivots) do
    while (nel < n) {
      // select node of minimum approximate degree. amd() is now ready to start eliminating the graph. It first
      // finds a node k of minimum degree and removes it from its degree list. The variable nel keeps track of thow
      // many nodes have been eliminated.
      for (k = -1; mindeg < n && (k = W[head + mindeg]) === -1; mindeg++);
      if (W[next + k] !== -1) {
        last[W[next + k]] = -1;
      }
      // remove k from degree list
      W[head + mindeg] = W[next + k];
      // elenk = |Ek|
      var elenk = W[elen + k];
      // # of nodes k represents
      var nvk = W[nv + k];
      // W[nv + k] nodes of A eliminated
      nel += nvk;

      // Construct a new element. The new element Lk is constructed in place if |Ek| = 0. nv[i] is
      // negated for all nodes i in Lk to flag them as members of this set. Each node i is removed from the
      // degree lists. All elements e in Ek are absorved into element k.
      var dk = 0;
      // flag k as in Lk
      W[nv + k] = -nvk;
      var p = cptr[k];
      // do in place if W[elen + k] === 0
      var pk1 = elenk === 0 ? p : cnz;
      var pk2 = pk1;
      for (k1 = 1; k1 <= elenk + 1; k1++) {
        if (k1 > elenk) {
          // search the nodes in k
          e = k;
          // list of nodes starts at cindex[pj]
          pj = p;
          // length of list of nodes in k
          ln = W[len + k] - elenk;
        } else {
          // search the nodes in e
          e = cindex[p++];
          pj = cptr[e];
          // length of list of nodes in e
          ln = W[len + e];
        }
        for (k2 = 1; k2 <= ln; k2++) {
          i = cindex[pj++];
          // check  node i dead, or seen
          if ((nvi = W[nv + i]) <= 0) {
            continue;
          }
          // W[degree + Lk] += size of node i
          dk += nvi;
          // negate W[nv + i] to denote i in Lk
          W[nv + i] = -nvi;
          // place i in Lk
          cindex[pk2++] = i;
          if (W[next + i] !== -1) {
            last[W[next + i]] = last[i];
          }
          // check we need to remove i from degree list
          if (last[i] !== -1) {
            W[next + last[i]] = W[next + i];
          } else {
            W[head + W[degree + i]] = W[next + i];
          }
        }
        if (e !== k) {
          // absorb e into k
          cptr[e] = csFlip(k);
          // e is now a dead element
          W[w + e] = 0;
        }
      }
      // cindex[cnz...nzmax] is free
      if (elenk !== 0) {
        cnz = pk2;
      }
      // external degree of k - |Lk\i|
      W[degree + k] = dk;
      // element k is in cindex[pk1..pk2-1]
      cptr[k] = pk1;
      W[len + k] = pk2 - pk1;
      // k is now an element
      W[elen + k] = -2;

      // Find set differences. The scan1 function now computes the set differences |Le \ Lk| for all elements e. At the start of the
      // scan, no entry in the w array is greater than or equal to mark.

      // clear w if necessary
      mark = _wclear(mark, lemax, W, w, n);
      // scan 1: find |Le\Lk|
      for (pk = pk1; pk < pk2; pk++) {
        i = cindex[pk];
        // check if W[elen + i] empty, skip it
        if ((eln = W[elen + i]) <= 0) {
          continue;
        }
        // W[nv + i] was negated
        nvi = -W[nv + i];
        var wnvi = mark - nvi;
        // scan Ei
        for (p = cptr[i], p1 = cptr[i] + eln - 1; p <= p1; p++) {
          e = cindex[p];
          if (W[w + e] >= mark) {
            // decrement |Le\Lk|
            W[w + e] -= nvi;
          } else if (W[w + e] !== 0) {
            // ensure e is a live element, 1st time e seen in scan 1
            W[w + e] = W[degree + e] + wnvi;
          }
        }
      }

      // degree update
      // The second pass computes the approximate degree di, prunes the sets Ei and Ai, and computes a hash
      // function h(i) for all nodes in Lk.

      // scan2: degree update
      for (pk = pk1; pk < pk2; pk++) {
        // consider node i in Lk
        i = cindex[pk];
        p1 = cptr[i];
        p2 = p1 + W[elen + i] - 1;
        pn = p1;
        // scan Ei
        for (h = 0, d = 0, p = p1; p <= p2; p++) {
          e = cindex[p];
          // check e is an unabsorbed element
          if (W[w + e] !== 0) {
            // dext = |Le\Lk|
            var dext = W[w + e] - mark;
            if (dext > 0) {
              // sum up the set differences
              d += dext;
              // keep e in Ei
              cindex[pn++] = e;
              // compute the hash of node i
              h += e;
            } else {
              // aggressive absorb. e->k
              cptr[e] = csFlip(k);
              // e is a dead element
              W[w + e] = 0;
            }
          }
        }
        // W[elen + i] = |Ei|
        W[elen + i] = pn - p1 + 1;
        var p3 = pn;
        var p4 = p1 + W[len + i];
        // prune edges in Ai
        for (p = p2 + 1; p < p4; p++) {
          j = cindex[p];
          // check node j dead or in Lk
          var nvj = W[nv + j];
          if (nvj <= 0) {
            continue;
          }
          // degree(i) += |j|
          d += nvj;
          // place j in node list of i
          cindex[pn++] = j;
          // compute hash for node i
          h += j;
        }
        // check for mass elimination
        if (d === 0) {
          // absorb i into k
          cptr[i] = csFlip(k);
          nvi = -W[nv + i];
          // |Lk| -= |i|
          dk -= nvi;
          // |k| += W[nv + i]
          nvk += nvi;
          nel += nvi;
          W[nv + i] = 0;
          // node i is dead
          W[elen + i] = -1;
        } else {
          // update degree(i)
          W[degree + i] = Math.min(W[degree + i], d);
          // move first node to end
          cindex[pn] = cindex[p3];
          // move 1st el. to end of Ei
          cindex[p3] = cindex[p1];
          // add k as 1st element in of Ei
          cindex[p1] = k;
          // new len of adj. list of node i
          W[len + i] = pn - p1 + 1;
          // finalize hash of i
          h = (h < 0 ? -h : h) % n;
          // place i in hash bucket
          W[next + i] = W[hhead + h];
          W[hhead + h] = i;
          // save hash of i in last[i]
          last[i] = h;
        }
      }
      // finalize |Lk|
      W[degree + k] = dk;
      lemax = Math.max(lemax, dk);
      // clear w
      mark = _wclear(mark + lemax, lemax, W, w, n);

      // Supernode detection. Supernode detection relies on the hash function h(i) computed for each node i.
      // If two nodes have identical adjacency lists, their hash functions wil be identical.
      for (pk = pk1; pk < pk2; pk++) {
        i = cindex[pk];
        // check i is dead, skip it
        if (W[nv + i] >= 0) {
          continue;
        }
        // scan hash bucket of node i
        h = last[i];
        i = W[hhead + h];
        // hash bucket will be empty
        W[hhead + h] = -1;
        for (; i !== -1 && W[next + i] !== -1; i = W[next + i], mark++) {
          ln = W[len + i];
          eln = W[elen + i];
          for (p = cptr[i] + 1; p <= cptr[i] + ln - 1; p++) {
            W[w + cindex[p]] = mark;
          }
          var jlast = i;
          // compare i with all j
          for (j = W[next + i]; j !== -1;) {
            var ok = W[len + j] === ln && W[elen + j] === eln;
            for (p = cptr[j] + 1; ok && p <= cptr[j] + ln - 1; p++) {
              // compare i and j
              if (W[w + cindex[p]] !== mark) {
                ok = 0;
              }
            }
            // check i and j are identical
            if (ok) {
              // absorb j into i
              cptr[j] = csFlip(i);
              W[nv + i] += W[nv + j];
              W[nv + j] = 0;
              // node j is dead
              W[elen + j] = -1;
              // delete j from hash bucket
              j = W[next + j];
              W[next + jlast] = j;
            } else {
              // j and i are different
              jlast = j;
              j = W[next + j];
            }
          }
        }
      }

      // Finalize new element. The elimination of node k is nearly complete. All nodes i in Lk are scanned one last time.
      // Node i is removed from Lk if it is dead. The flagged status of nv[i] is cleared.
      for (p = pk1, pk = pk1; pk < pk2; pk++) {
        i = cindex[pk];
        // check  i is dead, skip it
        if ((nvi = -W[nv + i]) <= 0) {
          continue;
        }
        // restore W[nv + i]
        W[nv + i] = nvi;
        // compute external degree(i)
        d = W[degree + i] + dk - nvi;
        d = Math.min(d, n - nel - nvi);
        if (W[head + d] !== -1) {
          last[W[head + d]] = i;
        }
        // put i back in degree list
        W[next + i] = W[head + d];
        last[i] = -1;
        W[head + d] = i;
        // find new minimum degree
        mindeg = Math.min(mindeg, d);
        W[degree + i] = d;
        // place i in Lk
        cindex[p++] = i;
      }
      // # nodes absorbed into k
      W[nv + k] = nvk;
      // length of adj list of element k
      if ((W[len + k] = p - pk1) === 0) {
        // k is a root of the tree
        cptr[k] = -1;
        // k is now a dead element
        W[w + k] = 0;
      }
      if (elenk !== 0) {
        // free unused space in Lk
        cnz = p;
      }
    }

    // Postordering. The elimination is complete, but no permutation has been computed. All that is left
    // of the graph is the assembly tree (ptr) and a set of dead nodes and elements (i is a dead node if
    // nv[i] is zero and a dead element if nv[i] > 0). It is from this information only that the final permutation
    // is computed. The tree is restored by unflipping all of ptr.

    // fix assembly tree
    for (i = 0; i < n; i++) {
      cptr[i] = csFlip(cptr[i]);
    }
    for (j = 0; j <= n; j++) {
      W[head + j] = -1;
    }
    // place unordered nodes in lists
    for (j = n; j >= 0; j--) {
      // skip if j is an element
      if (W[nv + j] > 0) {
        continue;
      }
      // place j in list of its parent
      W[next + j] = W[head + cptr[j]];
      W[head + cptr[j]] = j;
    }
    // place elements in lists
    for (e = n; e >= 0; e--) {
      // skip unless e is an element
      if (W[nv + e] <= 0) {
        continue;
      }
      if (cptr[e] !== -1) {
        // place e in list of its parent
        W[next + e] = W[head + cptr[e]];
        W[head + cptr[e]] = e;
      }
    }
    // postorder the assembly tree
    for (k = 0, i = 0; i <= n; i++) {
      if (cptr[i] === -1) {
        k = csTdfs(i, k, W, head, next, P, w);
      }
    }
    // remove last item in array
    P.splice(P.length - 1, 1);
    // return P
    return P;
  };

  /**
   * Creates the matrix that will be used by the approximate minimum degree ordering algorithm. The function accepts the matrix M as input and returns a permutation
   * vector P. The amd algorithm operates on a symmetrix matrix, so one of three symmetric matrices is formed.
   *
   * Order: 0
   *   A natural ordering P=null matrix is returned.
   *
   * Order: 1
   *   Matrix must be square. This is appropriate for a Cholesky or LU factorization.
   *   P = M + M'
   *
   * Order: 2
   *   Dense columns from M' are dropped, M recreated from M'. This is appropriatefor LU factorization of unsymmetric matrices.
   *   P = M' * M
   *
   * Order: 3
   *   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.
   *   P = M' * M
   */
  function _createTargetMatrix(order, a, m, n, dense) {
    // compute A'
    var at = transpose(a);

    // check order = 1, matrix must be square
    if (order === 1 && n === m) {
      // C = A + A'
      return add(a, at);
    }

    // check order = 2, drop dense columns from M'
    if (order === 2) {
      // transpose arrays
      var tindex = at._index;
      var tptr = at._ptr;
      // new column index
      var p2 = 0;
      // loop A' columns (rows)
      for (var j = 0; j < m; j++) {
        // column j of AT starts here
        var p = tptr[j];
        // new column j starts here
        tptr[j] = p2;
        // skip dense col j
        if (tptr[j + 1] - p > dense) {
          continue;
        }
        // map rows in column j of A
        for (var p1 = tptr[j + 1]; p < p1; p++) {
          tindex[p2++] = tindex[p];
        }
      }
      // finalize AT
      tptr[m] = p2;
      // recreate A from new transpose matrix
      a = transpose(at);
      // use A' * A
      return multiply(at, a);
    }

    // use A' * A, square or rectangular matrix
    return multiply(at, a);
  }

  /**
   * Initialize quotient graph. There are four kind of nodes and elements that must be represented:
   *
   *  - A live node is a node i (or a supernode) that has not been selected as a pivot nad has not been merged into another supernode.
   *  - A dead node i is one that has been removed from the graph, having been absorved into r = flip(ptr[i]).
   *  - A live element e is one that is in the graph, having been formed when node e was selected as the pivot.
   *  - A dead element e is one that has benn absorved into a subsequent element s = flip(ptr[e]).
   */
  function _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree) {
    // Initialize quotient graph
    for (var k = 0; k < n; k++) {
      W[len + k] = cptr[k + 1] - cptr[k];
    }
    W[len + n] = 0;
    // initialize workspace
    for (var i = 0; i <= n; i++) {
      // degree list i is empty
      W[head + i] = -1;
      last[i] = -1;
      W[next + i] = -1;
      // hash list i is empty
      W[hhead + i] = -1;
      // node i is just one node
      W[nv + i] = 1;
      // node i is alive
      W[w + i] = 1;
      // Ek of node i is empty
      W[elen + i] = 0;
      // degree of node i
      W[degree + i] = W[len + i];
    }
    // clear w
    var mark = _wclear(0, 0, W, w, n);
    // n is a dead element
    W[elen + n] = -2;
    // n is a root of assembly tree
    cptr[n] = -1;
    // n is a dead element
    W[w + n] = 0;
    // return mark
    return mark;
  }

  /**
   * Initialize degree lists. Each node is placed in its degree lists. Nodes of zero degree are eliminated immediately. Nodes with
   * degree >= dense are alsol eliminated and merged into a placeholder node n, a dead element. Thes nodes will appera last in the
   * output permutation p.
   */
  function _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next) {
    // result
    var nel = 0;
    // loop columns
    for (var i = 0; i < n; i++) {
      // degree @ i
      var d = W[degree + i];
      // check node i is empty
      if (d === 0) {
        // element i is dead
        W[elen + i] = -2;
        nel++;
        // i is a root of assembly tree
        cptr[i] = -1;
        W[w + i] = 0;
      } else if (d > dense) {
        // absorb i into element n
        W[nv + i] = 0;
        // node i is dead
        W[elen + i] = -1;
        nel++;
        cptr[i] = csFlip(n);
        W[nv + n]++;
      } else {
        var h = W[head + d];
        if (h !== -1) {
          last[h] = i;
        }
        // put node i in degree list d
        W[next + i] = W[head + d];
        W[head + d] = i;
      }
    }
    return nel;
  }
  function _wclear(mark, lemax, W, w, n) {
    if (mark < 2 || mark + lemax < 0) {
      for (var k = 0; k < n; k++) {
        if (W[w + k] !== 0) {
          W[w + k] = 1;
        }
      }
      mark = 2;
    }
    // at this point, W [0..n-1] < mark holds
    return mark;
  }
  function _diag(i, j) {
    return i !== j;
  }
});

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source

/**
 * This function determines if j is a leaf of the ith row subtree.
 * Consider A(i,j), node j in ith row subtree and return lca(jprev,j)
 *
 * @param {Number}  i               The ith row subtree
 * @param {Number}  j               The node to test
 * @param {Array}   w               The workspace array
 * @param {Number}  first           The index offset within the workspace for the first array
 * @param {Number}  maxfirst        The index offset within the workspace for the maxfirst array
 * @param {Number}  prevleaf        The index offset within the workspace for the prevleaf array
 * @param {Number}  ancestor        The index offset within the workspace for the ancestor array
 *
 * @return {Object}
 */
function csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor) {
  var s, sparent;

  // our result
  var jleaf = 0;
  var q;

  // check j is a leaf
  if (i <= j || w[first + j] <= w[maxfirst + i]) {
    return -1;
  }
  // update max first[j] seen so far
  w[maxfirst + i] = w[first + j];
  // jprev = previous leaf of ith subtree
  var jprev = w[prevleaf + i];
  w[prevleaf + i] = j;

  // check j is first or subsequent leaf
  if (jprev === -1) {
    // 1st leaf, q = root of ith subtree
    jleaf = 1;
    q = i;
  } else {
    // update jleaf
    jleaf = 2;
    // q = least common ancester (jprev,j)
    for (q = jprev; q !== w[ancestor + q]; q = w[ancestor + q]);
    for (s = jprev; s !== q; s = sparent) {
      // path compression
      sparent = w[ancestor + s];
      w[ancestor + s] = q;
    }
  }
  return {
    jleaf,
    q
  };
}

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
var name$1j = 'csCounts';
var dependencies$1j = ['transpose'];
var createCsCounts = /* #__PURE__ */factory(name$1j, dependencies$1j, _ref => {
  var {
    transpose
  } = _ref;
  /**
   * Computes the column counts using the upper triangular part of A.
   * It transposes A internally, none of the input parameters are modified.
   *
   * @param {Matrix} a           The sparse matrix A
   *
   * @param {Matrix} ata         Count the columns of A'A instead
   *
   * @return                     An array of size n of the column counts or null on error
   */
  return function (a, parent, post, ata) {
    // check inputs
    if (!a || !parent || !post) {
      return null;
    }
    // a matrix arrays
    var asize = a._size;
    // rows and columns
    var m = asize[0];
    var n = asize[1];
    // variables
    var i, j, k, J, p, p0, p1;

    // workspace size
    var s = 4 * n + (ata ? n + m + 1 : 0);
    // allocate workspace
    var w = []; // (s)
    var ancestor = 0; // first n entries
    var maxfirst = n; // next n entries
    var prevleaf = 2 * n; // next n entries
    var first = 3 * n; // next n entries
    var head = 4 * n; // next n + 1 entries (used when ata is true)
    var next = 5 * n + 1; // last entries in workspace
    // clear workspace w[0..s-1]
    for (k = 0; k < s; k++) {
      w[k] = -1;
    }

    // allocate result
    var colcount = []; // (n)

    // AT = A'
    var at = transpose(a);
    // at arrays
    var tindex = at._index;
    var tptr = at._ptr;

    // find w[first + j]
    for (k = 0; k < n; k++) {
      j = post[k];
      // colcount[j]=1 if j is a leaf
      colcount[j] = w[first + j] === -1 ? 1 : 0;
      for (; j !== -1 && w[first + j] === -1; j = parent[j]) {
        w[first + j] = k;
      }
    }

    // initialize ata if needed
    if (ata) {
      // invert post
      for (k = 0; k < n; k++) {
        w[post[k]] = k;
      }
      // loop rows (columns in AT)
      for (i = 0; i < m; i++) {
        // values in column i of AT
        for (k = n, p0 = tptr[i], p1 = tptr[i + 1], p = p0; p < p1; p++) {
          k = Math.min(k, w[tindex[p]]);
        }
        // place row i in linked list k
        w[next + i] = w[head + k];
        w[head + k] = i;
      }
    }

    // each node in its own set
    for (i = 0; i < n; i++) {
      w[ancestor + i] = i;
    }
    for (k = 0; k < n; k++) {
      // j is the kth node in postordered etree
      j = post[k];
      // check j is not a root
      if (parent[j] !== -1) {
        colcount[parent[j]]--;
      }

      // J=j for LL'=A case
      for (J = ata ? w[head + k] : j; J !== -1; J = ata ? w[next + J] : -1) {
        for (p = tptr[J]; p < tptr[J + 1]; p++) {
          i = tindex[p];
          var r = csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor);
          // check A(i,j) is in skeleton
          if (r.jleaf >= 1) {
            colcount[j]++;
          }
          // check account for overlap in q
          if (r.jleaf === 2) {
            colcount[r.q]--;
          }
        }
      }
      if (parent[j] !== -1) {
        w[ancestor + j] = parent[j];
      }
    }
    // sum up colcount's of each child
    for (j = 0; j < n; j++) {
      if (parent[j] !== -1) {
        colcount[parent[j]] += colcount[j];
      }
    }
    return colcount;
  };
});

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
var name$1i = 'csSqr';
var dependencies$1i = ['add', 'multiply', 'transpose'];
var createCsSqr = /* #__PURE__ */factory(name$1i, dependencies$1i, _ref => {
  var {
    add,
    multiply,
    transpose
  } = _ref;
  var csAmd = createCsAmd({
    add,
    multiply,
    transpose
  });
  var csCounts = createCsCounts({
    transpose
  });

  /**
   * Symbolic ordering and analysis for QR and LU decompositions.
   *
   * @param {Number}  order           The ordering strategy (see csAmd for more details)
   * @param {Matrix}  a               The A matrix
   * @param {boolean} qr              Symbolic ordering and analysis for QR decomposition (true) or
   *                                  symbolic ordering and analysis for LU decomposition (false)
   *
   * @return {Object}                 The Symbolic ordering and analysis for matrix A
   */
  return function csSqr(order, a, qr) {
    // a arrays
    var aptr = a._ptr;
    var asize = a._size;
    // columns
    var n = asize[1];
    // vars
    var k;
    // symbolic analysis result
    var s = {};
    // fill-reducing ordering
    s.q = csAmd(order, a);
    // validate results
    if (order && !s.q) {
      return null;
    }
    // QR symbolic analysis
    if (qr) {
      // apply permutations if needed
      var c = order ? csPermute(a, null, s.q, 0) : a;
      // etree of C'*C, where C=A(:,q)
      s.parent = csEtree(c, 1);
      // post order elimination tree
      var post = csPost(s.parent, n);
      // col counts chol(C'*C)
      s.cp = csCounts(c, s.parent, post, 1);
      // check we have everything needed to calculate number of nonzero elements
      if (c && s.parent && s.cp && _vcount(c, s)) {
        // calculate number of nonzero elements
        for (s.unz = 0, k = 0; k < n; k++) {
          s.unz += s.cp[k];
        }
      }
    } else {
      // for LU factorization only, guess nnz(L) and nnz(U)
      s.unz = 4 * aptr[n] + n;
      s.lnz = s.unz;
    }
    // return result S
    return s;
  };

  /**
   * Compute nnz(V) = s.lnz, s.pinv, s.leftmost, s.m2 from A and s.parent
   */
  function _vcount(a, s) {
    // a arrays
    var aptr = a._ptr;
    var aindex = a._index;
    var asize = a._size;
    // rows & columns
    var m = asize[0];
    var n = asize[1];
    // initialize s arrays
    s.pinv = []; // (m + n)
    s.leftmost = []; // (m)
    // vars
    var parent = s.parent;
    var pinv = s.pinv;
    var leftmost = s.leftmost;
    // workspace, next: first m entries, head: next n entries, tail: next n entries, nque: next n entries
    var w = []; // (m + 3 * n)
    var next = 0;
    var head = m;
    var tail = m + n;
    var nque = m + 2 * n;
    // vars
    var i, k, p, p0, p1;
    // initialize w
    for (k = 0; k < n; k++) {
      // queue k is empty
      w[head + k] = -1;
      w[tail + k] = -1;
      w[nque + k] = 0;
    }
    // initialize row arrays
    for (i = 0; i < m; i++) {
      leftmost[i] = -1;
    }
    // loop columns backwards
    for (k = n - 1; k >= 0; k--) {
      // values & index for column k
      for (p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) {
        // leftmost[i] = min(find(A(i,:)))
        leftmost[aindex[p]] = k;
      }
    }
    // scan rows in reverse order
    for (i = m - 1; i >= 0; i--) {
      // row i is not yet ordered
      pinv[i] = -1;
      k = leftmost[i];
      // check row i is empty
      if (k === -1) {
        continue;
      }
      // first row in queue k
      if (w[nque + k]++ === 0) {
        w[tail + k] = i;
      }
      // put i at head of queue k
      w[next + i] = w[head + k];
      w[head + k] = i;
    }
    s.lnz = 0;
    s.m2 = m;
    // find row permutation and nnz(V)
    for (k = 0; k < n; k++) {
      // remove row i from queue k
      i = w[head + k];
      // count V(k,k) as nonzero
      s.lnz++;
      // add a fictitious row
      if (i < 0) {
        i = s.m2++;
      }
      // associate row i with V(:,k)
      pinv[i] = k;
      // skip if V(k+1:m,k) is empty
      if (--nque[k] <= 0) {
        continue;
      }
      // nque[k] is nnz (V(k+1:m,k))
      s.lnz += w[nque + k];
      // move all rows to parent of k
      var pa = parent[k];
      if (pa !== -1) {
        if (w[nque + pa] === 0) {
          w[tail + pa] = w[tail + k];
        }
        w[next + w[tail + k]] = w[head + pa];
        w[head + pa] = w[next + i];
        w[nque + pa] += w[nque + k];
      }
    }
    for (i = 0; i < m; i++) {
      if (pinv[i] < 0) {
        pinv[i] = k++;
      }
    }
    return true;
  }
});

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source

/**
 * Checks if the node at w[j] is marked
 *
 * @param {Array}   w               The array
 * @param {Number}  j               The array index
 */
function csMarked(w, j) {
  // check node is marked
  return w[j] < 0;
}

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.

/**
 * Marks the node at w[j]
 *
 * @param {Array}   w               The array
 * @param {Number}  j               The array index
 */
function csMark(w, j) {
  // mark w[j]
  w[j] = csFlip(w[j]);
}

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.

/**
 * Flips the value if it is negative of returns the same value otherwise.
 *
 * @param {Number}  i               The value to flip
 */
function csUnflip(i) {
  // flip the value if it is negative
  return i < 0 ? csFlip(i) : i;
}

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.

/**
 * Depth-first search computes the nonzero pattern xi of the directed graph G (Matrix) starting
 * at nodes in B (see csReach()).
 *
 * @param {Number}  j               The starting node for the DFS algorithm
 * @param {Matrix}  g               The G matrix to search, ptr array modified, then restored
 * @param {Number}  top             Start index in stack xi[top..n-1]
 * @param {Number}  k               The kth column in B
 * @param {Array}   xi              The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n
 *                                  The first n entries is the nonzero pattern, the last n entries is the stack
 * @param {Array}   pinv            The inverse row permutation vector, must be null for L * x = b
 *
 * @return {Number}                 New value of top
 */
function csDfs(j, g, top, xi, pinv) {
  // g arrays
  var index = g._index;
  var ptr = g._ptr;
  var size = g._size;
  // columns
  var n = size[1];
  // vars
  var i, p, p2;
  // initialize head
  var head = 0;
  // initialize the recursion stack
  xi[0] = j;
  // loop
  while (head >= 0) {
    // get j from the top of the recursion stack
    j = xi[head];
    // apply permutation vector
    var jnew = pinv ? pinv[j] : j;
    // check node j is marked
    if (!csMarked(ptr, j)) {
      // mark node j as visited
      csMark(ptr, j);
      // update stack (last n entries in xi)
      xi[n + head] = jnew < 0 ? 0 : csUnflip(ptr[jnew]);
    }
    // node j done if no unvisited neighbors
    var done = 1;
    // examine all neighbors of j, stack (last n entries in xi)
    for (p = xi[n + head], p2 = jnew < 0 ? 0 : csUnflip(ptr[jnew + 1]); p < p2; p++) {
      // consider neighbor node i
      i = index[p];
      // check we have visited node i, skip it
      if (csMarked(ptr, i)) {
        continue;
      }
      // pause depth-first search of node j, update stack (last n entries in xi)
      xi[n + head] = p;
      // start dfs at node i
      xi[++head] = i;
      // node j is not done
      done = 0;
      // break, to start dfs(i)
      break;
    }
    // check depth-first search at node j is done
    if (done) {
      // remove j from the recursion stack
      head--;
      // and place in the output stack
      xi[--top] = j;
    }
  }
  return top;
}

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.

/**
 * The csReach function computes X = Reach(B), where B is the nonzero pattern of the n-by-1
 * sparse column of vector b. The function returns the set of nodes reachable from any node in B. The
 * nonzero pattern xi of the solution x to the sparse linear system Lx=b is given by X=Reach(B).
 *
 * @param {Matrix}  g               The G matrix
 * @param {Matrix}  b               The B matrix
 * @param {Number}  k               The kth column in B
 * @param {Array}   xi              The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n
 *                                  The first n entries is the nonzero pattern, the last n entries is the stack
 * @param {Array}   pinv            The inverse row permutation vector
 *
 * @return {Number}                 The index for the nonzero pattern
 */
function csReach(g, b, k, xi, pinv) {
  // g arrays
  var gptr = g._ptr;
  var gsize = g._size;
  // b arrays
  var bindex = b._index;
  var bptr = b._ptr;
  // columns
  var n = gsize[1];
  // vars
  var p, p0, p1;
  // initialize top
  var top = n;
  // loop column indeces in B
  for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) {
    // node i
    var i = bindex[p];
    // check node i is marked
    if (!csMarked(gptr, i)) {
      // start a dfs at unmarked node i
      top = csDfs(i, g, top, xi, pinv);
    }
  }
  // loop columns from top -> n - 1
  for (p = top; p < n; p++) {
    // restore G
    csMark(gptr, xi[p]);
  }
  return top;
}

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
var name$1h = 'csSpsolve';
var dependencies$1h = ['divideScalar', 'multiply', 'subtract'];
var createCsSpsolve = /* #__PURE__ */factory(name$1h, dependencies$1h, _ref => {
  var {
    divideScalar,
    multiply,
    subtract
  } = _ref;
  /**
   * The function csSpsolve() computes the solution to G * x = bk, where bk is the
   * kth column of B. When lo is true, the function assumes G = L is lower triangular with the
   * diagonal entry as the first entry in each column. When lo is true, the function assumes G = U
   * is upper triangular with the diagonal entry as the last entry in each column.
   *
   * @param {Matrix}  g               The G matrix
   * @param {Matrix}  b               The B matrix
   * @param {Number}  k               The kth column in B
   * @param {Array}   xi              The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n
   *                                  The first n entries is the nonzero pattern, the last n entries is the stack
   * @param {Array}   x               The soluton to the linear system G * x = b
   * @param {Array}   pinv            The inverse row permutation vector, must be null for L * x = b
   * @param {boolean} lo              The lower (true) upper triangular (false) flag
   *
   * @return {Number}                 The index for the nonzero pattern
   */
  return function csSpsolve(g, b, k, xi, x, pinv, lo) {
    // g arrays
    var gvalues = g._values;
    var gindex = g._index;
    var gptr = g._ptr;
    var gsize = g._size;
    // columns
    var n = gsize[1];
    // b arrays
    var bvalues = b._values;
    var bindex = b._index;
    var bptr = b._ptr;
    // vars
    var p, p0, p1, q;
    // xi[top..n-1] = csReach(B(:,k))
    var top = csReach(g, b, k, xi, pinv);
    // clear x
    for (p = top; p < n; p++) {
      x[xi[p]] = 0;
    }
    // scatter b
    for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) {
      x[bindex[p]] = bvalues[p];
    }
    // loop columns
    for (var px = top; px < n; px++) {
      // x array index for px
      var j = xi[px];
      // apply permutation vector (U x = b), j maps to column J of G
      var J = pinv ? pinv[j] : j;
      // check column J is empty
      if (J < 0) {
        continue;
      }
      // column value indeces in G, p0 <= p < p1
      p0 = gptr[J];
      p1 = gptr[J + 1];
      // x(j) /= G(j,j)
      x[j] = divideScalar(x[j], gvalues[lo ? p0 : p1 - 1]);
      // first entry L(j,j)
      p = lo ? p0 + 1 : p0;
      q = lo ? p1 : p1 - 1;
      // loop
      for (; p < q; p++) {
        // row
        var i = gindex[p];
        // x(i) -= G(i,j) * x(j)
        x[i] = subtract(x[i], multiply(gvalues[p], x[j]));
      }
    }
    // return top of stack
    return top;
  };
});

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
var name$1g = 'csLu';
var dependencies$1g = ['abs', 'divideScalar', 'multiply', 'subtract', 'larger', 'largerEq', 'SparseMatrix'];
var createCsLu = /* #__PURE__ */factory(name$1g, dependencies$1g, _ref => {
  var {
    abs,
    divideScalar,
    multiply,
    subtract,
    larger,
    largerEq,
    SparseMatrix
  } = _ref;
  var csSpsolve = createCsSpsolve({
    divideScalar,
    multiply,
    subtract
  });

  /**
   * Computes the numeric LU factorization of the sparse matrix A. Implements a Left-looking LU factorization
   * algorithm that computes L and U one column at a tume. At the kth step, it access columns 1 to k-1 of L
   * and column k of A. Given the fill-reducing column ordering q (see parameter s) computes L, U and pinv so
   * L * U = A(p, q), where p is the inverse of pinv.
   *
   * @param {Matrix}  m               The A Matrix to factorize
   * @param {Object}  s               The symbolic analysis from csSqr(). Provides the fill-reducing
   *                                  column ordering q
   * @param {Number}  tol             Partial pivoting threshold (1 for partial pivoting)
   *
   * @return {Number}                 The numeric LU factorization of A or null
   */
  return function csLu(m, s, tol) {
    // validate input
    if (!m) {
      return null;
    }
    // m arrays
    var size = m._size;
    // columns
    var n = size[1];
    // symbolic analysis result
    var q;
    var lnz = 100;
    var unz = 100;
    // update symbolic analysis parameters
    if (s) {
      q = s.q;
      lnz = s.lnz || lnz;
      unz = s.unz || unz;
    }
    // L arrays
    var lvalues = []; // (lnz)
    var lindex = []; // (lnz)
    var lptr = []; // (n + 1)
    // L
    var L = new SparseMatrix({
      values: lvalues,
      index: lindex,
      ptr: lptr,
      size: [n, n]
    });
    // U arrays
    var uvalues = []; // (unz)
    var uindex = []; // (unz)
    var uptr = []; // (n + 1)
    // U
    var U = new SparseMatrix({
      values: uvalues,
      index: uindex,
      ptr: uptr,
      size: [n, n]
    });
    // inverse of permutation vector
    var pinv = []; // (n)
    // vars
    var i, p;
    // allocate arrays
    var x = []; // (n)
    var xi = []; // (2 * n)
    // initialize variables
    for (i = 0; i < n; i++) {
      // clear workspace
      x[i] = 0;
      // no rows pivotal yet
      pinv[i] = -1;
      // no cols of L yet
      lptr[i + 1] = 0;
    }
    // reset number of nonzero elements in L and U
    lnz = 0;
    unz = 0;
    // compute L(:,k) and U(:,k)
    for (var k = 0; k < n; k++) {
      // update ptr
      lptr[k] = lnz;
      uptr[k] = unz;
      // apply column permutations if needed
      var col = q ? q[k] : k;
      // solve triangular system, x = L\A(:,col)
      var top = csSpsolve(L, m, col, xi, x, pinv, 1);
      // find pivot
      var ipiv = -1;
      var a = -1;
      // loop xi[] from top -> n
      for (p = top; p < n; p++) {
        // x[i] is nonzero
        i = xi[p];
        // check row i is not yet pivotal
        if (pinv[i] < 0) {
          // absolute value of x[i]
          var xabs = abs(x[i]);
          // check absoulte value is greater than pivot value
          if (larger(xabs, a)) {
            // largest pivot candidate so far
            a = xabs;
            ipiv = i;
          }
        } else {
          // x(i) is the entry U(pinv[i],k)
          uindex[unz] = pinv[i];
          uvalues[unz++] = x[i];
        }
      }
      // validate we found a valid pivot
      if (ipiv === -1 || a <= 0) {
        return null;
      }
      // update actual pivot column, give preference to diagonal value
      if (pinv[col] < 0 && largerEq(abs(x[col]), multiply(a, tol))) {
        ipiv = col;
      }
      // the chosen pivot
      var pivot = x[ipiv];
      // last entry in U(:,k) is U(k,k)
      uindex[unz] = k;
      uvalues[unz++] = pivot;
      // ipiv is the kth pivot row
      pinv[ipiv] = k;
      // first entry in L(:,k) is L(k,k) = 1
      lindex[lnz] = ipiv;
      lvalues[lnz++] = 1;
      // L(k+1:n,k) = x / pivot
      for (p = top; p < n; p++) {
        // row
        i = xi[p];
        // check x(i) is an entry in L(:,k)
        if (pinv[i] < 0) {
          // save unpermuted row in L
          lindex[lnz] = i;
          // scale pivot column
          lvalues[lnz++] = divideScalar(x[i], pivot);
        }
        // x[0..n-1] = 0 for next k
        x[i] = 0;
      }
    }
    // update ptr
    lptr[n] = lnz;
    uptr[n] = unz;
    // fix row indices of L for final pinv
    for (p = 0; p < lnz; p++) {
      lindex[p] = pinv[lindex[p]];
    }
    // trim arrays
    lvalues.splice(lnz, lvalues.length - lnz);
    lindex.splice(lnz, lindex.length - lnz);
    uvalues.splice(unz, uvalues.length - unz);
    uindex.splice(unz, uindex.length - unz);
    // return LU factor
    return {
      L,
      U,
      pinv
    };
  };
});

var name$1f = 'slu';
var dependencies$1f = ['typed', 'abs', 'add', 'multiply', 'transpose', 'divideScalar', 'subtract', 'larger', 'largerEq', 'SparseMatrix'];
var createSlu = /* #__PURE__ */factory(name$1f, dependencies$1f, _ref => {
  var {
    typed,
    abs,
    add,
    multiply,
    transpose,
    divideScalar,
    subtract,
    larger,
    largerEq,
    SparseMatrix
  } = _ref;
  var csSqr = createCsSqr({
    add,
    multiply,
    transpose
  });
  var csLu = createCsLu({
    abs,
    divideScalar,
    multiply,
    subtract,
    larger,
    largerEq,
    SparseMatrix
  });

  /**
   * 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
   *
   * `P * A * Q = L * U`
   *
   * Syntax:
   *
   *    math.slu(A, order, threshold)
   *
   * Examples:
   *
   *    const A = math.sparse([[4,3], [6, 3]])
   *    math.slu(A, 1, 0.001)
   *    // returns:
   *    // {
   *    //   L: [[1, 0], [1.5, 1]]
   *    //   U: [[4, 3], [0, -1.5]]
   *    //   p: [0, 1]
   *    //   q: [0, 1]
   *    // }
   *
   * See also:
   *
   *    lup, lsolve, usolve, lusolve
   *
   * @param {SparseMatrix} A              A two dimensional sparse matrix for which to get the LU decomposition.
   * @param {Number}       order          The Symbolic Ordering and Analysis order:
   *                                       0 - Natural ordering, no permutation vector q is returned
   *                                       1 - Matrix must be square, symbolic ordering and analisis is performed on M = A + A'
   *                                       2 - Symbolic ordering and analisis is performed on M = A' * A. Dense columns from A' are dropped, A recreated from A'.
   *                                           This is appropriatefor LU factorization of unsymmetric matrices.
   *                                       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.
   *                                           A dense row is a row with more than 10*sqr(columns) entries.
   * @param {Number}       threshold       Partial pivoting threshold (1 for partial pivoting)
   *
   * @return {Object} The lower triangular matrix, the upper triangular matrix and the permutation vectors.
   */
  return typed(name$1f, {
    'SparseMatrix, number, number': function SparseMatrixNumberNumber(a, order, threshold) {
      // verify order
      if (!isInteger(order) || order < 0 || order > 3) {
        throw new Error('Symbolic Ordering and Analysis order must be an integer number in the interval [0, 3]');
      }
      // verify threshold
      if (threshold < 0 || threshold > 1) {
        throw new Error('Partial pivoting threshold must be a number from 0 to 1');
      }

      // perform symbolic ordering and analysis
      var s = csSqr(order, a, false);

      // perform lu decomposition
      var f = csLu(a, s, threshold);

      // return decomposition
      return {
        L: f.L,
        U: f.U,
        p: f.pinv,
        q: s.q,
        toString: function toString() {
          return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\np: ' + this.p.toString() + (this.q ? '\nq: ' + this.q.toString() : '') + '\n';
        }
      };
    }
  });
});

// Copyright (c) 2006-2024, Timothy A. Davis, All Rights Reserved.
// SPDX-License-Identifier: LGPL-2.1+
// https://github.com/DrTimothyAldenDavis/SuiteSparse/tree/dev/CSparse/Source

/**
 * Permutes a vector; x = P'b. In MATLAB notation, x(p)=b.
 *
 * @param {Array} p           The permutation vector of length n. null value denotes identity
 * @param {Array} b           The input vector
 *
 * @return {Array}            The output vector x = P'b
 */
function csIpvec(p, b) {
  // vars
  var k;
  var n = b.length;
  var x = [];
  // check permutation vector was provided, p = null denotes identity
  if (p) {
    // loop vector
    for (k = 0; k < n; k++) {
      // apply permutation
      x[p[k]] = b[k];
    }
  } else {
    // loop vector
    for (k = 0; k < n; k++) {
      // x[i] = b[i]
      x[k] = b[k];
    }
  }
  return x;
}

var name$1e = 'lusolve';
var dependencies$1e = ['typed', 'matrix', 'lup', 'slu', 'usolve', 'lsolve', 'DenseMatrix'];
var createLusolve = /* #__PURE__ */factory(name$1e, dependencies$1e, _ref => {
  var {
    typed,
    matrix,
    lup,
    slu,
    usolve,
    lsolve,
    DenseMatrix
  } = _ref;
  var solveValidation = createSolveValidation({
    DenseMatrix
  });

  /**
   * Solves the linear system `A * x = b` where `A` is an [n x n] matrix and `b` is a [n] column vector.
   *
   * Syntax:
   *
   *    math.lusolve(A, b)     // returns column vector with the solution to the linear system A * x = b
   *    math.lusolve(lup, b)   // returns column vector with the solution to the linear system A * x = b, lup = math.lup(A)
   *
   * Examples:
   *
   *    const m = [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]
   *
   *    const x = math.lusolve(m, [-1, -1, -1, -1])        // x = [[-1], [-0.5], [-1/3], [-0.25]]
   *
   *    const f = math.lup(m)
   *    const x1 = math.lusolve(f, [-1, -1, -1, -1])       // x1 = [[-1], [-0.5], [-1/3], [-0.25]]
   *    const x2 = math.lusolve(f, [1, 2, 1, -1])          // x2 = [[1], [1], [1/3], [-0.25]]
   *
   *    const a = [[-2, 3], [2, 1]]
   *    const b = [11, 9]
   *    const x = math.lusolve(a, b)  // [[2], [5]]
   *
   * See also:
   *
   *    lup, slu, lsolve, usolve
   *
   * @param {Matrix | Array | Object} A      Invertible Matrix or the Matrix LU decomposition
   * @param {Matrix | Array} b               Column Vector
   * @param {number} [order]                 The Symbolic Ordering and Analysis order, see slu for details. Matrix must be a SparseMatrix
   * @param {Number} [threshold]             Partial pivoting threshold (1 for partial pivoting), see slu for details. Matrix must be a SparseMatrix.
   *
   * @return {DenseMatrix | Array}           Column vector with the solution to the linear system A * x = b
   */
  return typed(name$1e, {
    'Array, Array | Matrix': function ArrayArrayMatrix(a, b) {
      a = matrix(a);
      var d = lup(a);
      var x = _lusolve(d.L, d.U, d.p, null, b);
      return x.valueOf();
    },
    'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(a, b) {
      var d = lup(a);
      return _lusolve(d.L, d.U, d.p, null, b);
    },
    'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(a, b) {
      var d = lup(a);
      return _lusolve(d.L, d.U, d.p, null, b);
    },
    'SparseMatrix, Array | Matrix, number, number': function SparseMatrixArrayMatrixNumberNumber(a, b, order, threshold) {
      var d = slu(a, order, threshold);
      return _lusolve(d.L, d.U, d.p, d.q, b);
    },
    'Object, Array | Matrix': function ObjectArrayMatrix(d, b) {
      return _lusolve(d.L, d.U, d.p, d.q, b);
    }
  });
  function _toMatrix(a) {
    if (isMatrix(a)) {
      return a;
    }
    if (isArray(a)) {
      return matrix(a);
    }
    throw new TypeError('Invalid Matrix LU decomposition');
  }
  function _lusolve(l, u, p, q, b) {
    // verify decomposition
    l = _toMatrix(l);
    u = _toMatrix(u);

    // apply row permutations if needed (b is a DenseMatrix)
    if (p) {
      b = solveValidation(l, b, true);
      b._data = csIpvec(p, b._data);
    }

    // use forward substitution to resolve L * y = b
    var y = lsolve(l, b);
    // use backward substitution to resolve U * x = y
    var x = usolve(u, y);

    // apply column permutations if needed (x is a DenseMatrix)
    if (q) {
      x._data = csIpvec(q, x._data);
    }
    return x;
  }
});

var name$1d = 'polynomialRoot';
var dependencies$1d = ['typed', 'isZero', 'equalScalar', 'add', 'subtract', 'multiply', 'divide', 'sqrt', 'unaryMinus', 'cbrt', 'typeOf', 'im', 're'];
var createPolynomialRoot = /* #__PURE__ */factory(name$1d, dependencies$1d, _ref => {
  var {
    typed,
    isZero,
    equalScalar,
    add,
    subtract,
    multiply,
    divide,
    sqrt,
    unaryMinus,
    cbrt,
    typeOf,
    im,
    re
  } = _ref;
  /**
   * Finds the numerical values of the distinct roots of a polynomial with real or complex coefficients.
   * Currently operates only on linear, quadratic, and cubic polynomials using the standard
   * formulas for the roots.
   *
   * Syntax:
   *
   *     math.polynomialRoot(constant, linearCoeff, quadraticCoeff, cubicCoeff)
   *
   * Examples:
   *     // linear
   *     math.polynomialRoot(6, 3)                                        // [-2]
   *     math.polynomialRoot(math.complex(6,3), 3)                        // [-2 - i]
   *     math.polynomialRoot(math.complex(6,3), math.complex(2,1))        // [-3 + 0i]
   *     // quadratic
   *     math.polynomialRoot(2, -3, 1)                                    // [2, 1]
   *     math.polynomialRoot(8, 8, 2)                                     // [-2]
   *     math.polynomialRoot(-2, 0, 1)                                    // [1.4142135623730951, -1.4142135623730951]
   *     math.polynomialRoot(2, -2, 1)                                    // [1 + i, 1 - i]
   *     math.polynomialRoot(math.complex(1,3), math.complex(-3, -2), 1)  // [2 + i, 1 + i]
   *     // cubic
   *     math.polynomialRoot(-6, 11, -6, 1)                               // [1, 3, 2]
   *     math.polynomialRoot(-8, 0, 0, 1)                                 // [-1 - 1.7320508075688774i, 2, -1 + 1.7320508075688774i]
   *     math.polynomialRoot(0, 8, 8, 2)                                  // [0, -2]
   *     math.polynomialRoot(1, 1, 1, 1)                                  // [-1 + 0i, 0 - i, 0 + i]
   *
   * See also:
   *     cbrt, sqrt
   *
   * @param {... number | Complex} coeffs
   *     The coefficients of the polynomial, starting with with the constant coefficent, followed
   *     by the linear coefficient and subsequent coefficients of increasing powers.
   * @return {Array} The distinct roots of the polynomial
   */

  return typed(name$1d, {
    'number|Complex, ...number|Complex': (constant, restCoeffs) => {
      var coeffs = [constant, ...restCoeffs];
      while (coeffs.length > 0 && isZero(coeffs[coeffs.length - 1])) {
        coeffs.pop();
      }
      if (coeffs.length < 2) {
        throw new RangeError("Polynomial [".concat(constant, ", ").concat(restCoeffs, "] must have a non-zero non-constant coefficient"));
      }
      switch (coeffs.length) {
        case 2:
          // linear
          return [unaryMinus(divide(coeffs[0], coeffs[1]))];
        case 3:
          {
            // quadratic
            var [c, b, a] = coeffs;
            var denom = multiply(2, a);
            var d1 = multiply(b, b);
            var d2 = multiply(4, a, c);
            if (equalScalar(d1, d2)) return [divide(unaryMinus(b), denom)];
            var discriminant = sqrt(subtract(d1, d2));
            return [divide(subtract(discriminant, b), denom), divide(subtract(unaryMinus(discriminant), b), denom)];
          }
        case 4:
          {
            // cubic, cf. https://en.wikipedia.org/wiki/Cubic_equation
            var [d, _c, _b, _a] = coeffs;
            var _denom = unaryMinus(multiply(3, _a));
            var D0_1 = multiply(_b, _b);
            var D0_2 = multiply(3, _a, _c);
            var D1_1 = add(multiply(2, _b, _b, _b), multiply(27, _a, _a, d));
            var D1_2 = multiply(9, _a, _b, _c);
            if (equalScalar(D0_1, D0_2) && equalScalar(D1_1, D1_2)) {
              return [divide(_b, _denom)];
            }
            var Delta0 = subtract(D0_1, D0_2);
            var Delta1 = subtract(D1_1, D1_2);
            var discriminant1 = add(multiply(18, _a, _b, _c, d), multiply(_b, _b, _c, _c));
            var discriminant2 = add(multiply(4, _b, _b, _b, d), multiply(4, _a, _c, _c, _c), multiply(27, _a, _a, d, d));
            if (equalScalar(discriminant1, discriminant2)) {
              return [divide(subtract(multiply(4, _a, _b, _c), add(multiply(9, _a, _a, d), multiply(_b, _b, _b))), multiply(_a, Delta0)),
              // simple root
              divide(subtract(multiply(9, _a, d), multiply(_b, _c)), multiply(2, Delta0)) // double root
              ];
            }
            // OK, we have three distinct roots
            var Ccubed;
            if (equalScalar(D0_1, D0_2)) {
              Ccubed = Delta1;
            } else {
              Ccubed = divide(add(Delta1, sqrt(subtract(multiply(Delta1, Delta1), multiply(4, Delta0, Delta0, Delta0)))), 2);
            }
            var allRoots = true;
            var rawRoots = cbrt(Ccubed, allRoots).toArray().map(C => divide(add(_b, C, divide(Delta0, C)), _denom));
            return rawRoots.map(r => {
              if (typeOf(r) === 'Complex' && equalScalar(re(r), re(r) + im(r))) {
                return re(r);
              }
              return r;
            });
          }
        default:
          throw new RangeError("only implemented for cubic or lower-order polynomials, not ".concat(coeffs));
      }
    }
  });
});

var name$1c = 'Help';
var dependencies$1c = ['evaluate'];
var createHelpClass = /* #__PURE__ */factory(name$1c, dependencies$1c, _ref => {
  var {
    evaluate
  } = _ref;
  /**
   * Documentation object
   * @param {Object} doc  Object containing properties:
   *                      {string} name
   *                      {string} category
   *                      {string} description
   *                      {string[]} syntax
   *                      {string[]} examples
   *                      {string[]} seealso
   * @constructor
   */
  function Help(doc) {
    if (!(this instanceof Help)) {
      throw new SyntaxError('Constructor must be called with the new operator');
    }
    if (!doc) throw new Error('Argument "doc" missing');
    this.doc = doc;
  }

  /**
   * Attach type information
   */
  Help.prototype.type = 'Help';
  Help.prototype.isHelp = true;

  /**
   * Generate a string representation of the Help object
   * @return {string} Returns a string
   * @private
   */
  Help.prototype.toString = function () {
    var doc = this.doc || {};
    var desc = '\n';
    if (doc.name) {
      desc += 'Name: ' + doc.name + '\n\n';
    }
    if (doc.category) {
      desc += 'Category: ' + doc.category + '\n\n';
    }
    if (doc.description) {
      desc += 'Description:\n    ' + doc.description + '\n\n';
    }
    if (doc.syntax) {
      desc += 'Syntax:\n    ' + doc.syntax.join('\n    ') + '\n\n';
    }
    if (doc.examples) {
      desc += 'Examples:\n';

      // after evaluating the examples, we restore config in case the examples
      // did change the config.
      var configChanged = false;
      var originalConfig = evaluate('config()');
      var scope = {
        config: newConfig => {
          configChanged = true;
          return evaluate('config(newConfig)', {
            newConfig
          });
        }
      };
      for (var i = 0; i < doc.examples.length; i++) {
        var expr = doc.examples[i];
        desc += '    ' + expr + '\n';
        var res = void 0;
        try {
          // note: res can be undefined when `expr` is an empty string
          res = evaluate(expr, scope);
        } catch (e) {
          res = e;
        }
        if (res !== undefined && !isHelp(res)) {
          desc += '        ' + format(res, {
            precision: 14
          }) + '\n';
        }
      }
      desc += '\n';
      if (configChanged) {
        evaluate('config(originalConfig)', {
          originalConfig
        });
      }
    }
    if (doc.mayThrow && doc.mayThrow.length) {
      desc += 'Throws: ' + doc.mayThrow.join(', ') + '\n\n';
    }
    if (doc.seealso && doc.seealso.length) {
      desc += 'See also: ' + doc.seealso.join(', ') + '\n';
    }
    return desc;
  };

  /**
   * Export the help object to JSON
   */
  Help.prototype.toJSON = function () {
    var obj = clone$2(this.doc);
    obj.mathjs = 'Help';
    return obj;
  };

  /**
   * Instantiate a Help object from a JSON object
   * @param {Object} json
   * @returns {Help} Returns a new Help object
   */
  Help.fromJSON = function (json) {
    var doc = {};
    Object.keys(json).filter(prop => prop !== 'mathjs').forEach(prop => {
      doc[prop] = json[prop];
    });
    return new Help(doc);
  };

  /**
   * Returns a string representation of the Help object
   */
  Help.prototype.valueOf = Help.prototype.toString;
  return Help;
}, {
  isClass: true
});

var name$1b = 'Chain';
var dependencies$1b = ['?on', 'math', 'typed'];
var createChainClass = /* #__PURE__ */factory(name$1b, dependencies$1b, _ref => {
  var {
    on,
    math,
    typed
  } = _ref;
  /**
   * @constructor Chain
   * Wrap any value in a chain, allowing to perform chained operations on
   * the value.
   *
   * All methods available in the math.js library can be called upon the chain,
   * and then will be evaluated with the value itself as first argument.
   * The chain can be closed by executing chain.done(), which will return
   * the final value.
   *
   * The Chain has a number of special functions:
   * - done()             Finalize the chained operation and return the
   *                      chain's value.
   * - valueOf()          The same as done()
   * - toString()         Returns a string representation of the chain's value.
   *
   * @param {*} [value]
   */
  function Chain(value) {
    if (!(this instanceof Chain)) {
      throw new SyntaxError('Constructor must be called with the new operator');
    }
    if (isChain(value)) {
      this.value = value.value;
    } else {
      this.value = value;
    }
  }

  /**
   * Attach type information
   */
  Chain.prototype.type = 'Chain';
  Chain.prototype.isChain = true;

  /**
   * Close the chain. Returns the final value.
   * Does the same as method valueOf()
   * @returns {*} value
   */
  Chain.prototype.done = function () {
    return this.value;
  };

  /**
   * Close the chain. Returns the final value.
   * Does the same as method done()
   * @returns {*} value
   */
  Chain.prototype.valueOf = function () {
    return this.value;
  };

  /**
   * Get a string representation of the value in the chain
   * @returns {string}
   */
  Chain.prototype.toString = function () {
    return format(this.value);
  };

  /**
   * Get a JSON representation of the chain
   * @returns {Object}
   */
  Chain.prototype.toJSON = function () {
    return {
      mathjs: 'Chain',
      value: this.value
    };
  };

  /**
   * Instantiate a Chain from its JSON representation
   * @param {Object} json  An object structured like
   *                       `{"mathjs": "Chain", value: ...}`,
   *                       where mathjs is optional
   * @returns {Chain}
   */
  Chain.fromJSON = function (json) {
    return new Chain(json.value);
  };

  /**
   * Create a proxy method for the chain
   * @param {string} name
   * @param {Function} fn      The function to be proxied
   *                           If fn is no function, it is silently ignored.
   * @private
   */
  function createProxy(name, fn) {
    if (typeof fn === 'function') {
      Chain.prototype[name] = chainify(fn);
    }
  }

  /**
   * Create a proxy method for the chain
   * @param {string} name
   * @param {function} resolver   The function resolving with the
   *                              function to be proxied
   * @private
   */
  function createLazyProxy(name, resolver) {
    lazy(Chain.prototype, name, function outerResolver() {
      var fn = resolver();
      if (typeof fn === 'function') {
        return chainify(fn);
      }
      return undefined; // if not a function, ignore
    });
  }

  /**
   * Make a function chainable
   * @param {function} fn
   * @return {Function} chain function
   * @private
   */
  function chainify(fn) {
    return function () {
      // Here, `this` will be the context of a Chain instance
      if (arguments.length === 0) {
        return new Chain(fn(this.value));
      }
      var args = [this.value];
      for (var i = 0; i < arguments.length; i++) {
        args[i + 1] = arguments[i];
      }
      if (typed.isTypedFunction(fn)) {
        var sigObject = typed.resolve(fn, args);
        // We want to detect if a rest parameter has matched across the
        // value in the chain and the current arguments of this call.
        // That is the case if and only if the matching signature has
        // exactly one parameter (which then must be a rest parameter
        // as it is matching at least two actual arguments).
        if (sigObject.params.length === 1) {
          throw new Error('chain function ' + fn.name + ' cannot match rest parameter between chain value and additional arguments.');
        }
        return new Chain(sigObject.implementation.apply(fn, args));
      }
      return new Chain(fn.apply(fn, args));
    };
  }

  /**
   * Create a proxy for a single method, or an object with multiple methods.
   * Example usage:
   *
   *   Chain.createProxy('add', function add (x, y) {...})
   *   Chain.createProxy({
   *     add:      function add (x, y) {...},
   *     subtract: function subtract (x, y) {...}
   *   }
   *
   * @param {string | Object} arg0   A name (string), or an object with
   *                                 functions
   * @param {*} [arg1]               A function, when arg0 is a name
   */
  Chain.createProxy = function (arg0, arg1) {
    if (typeof arg0 === 'string') {
      // createProxy(name, value)
      createProxy(arg0, arg1);
    } else {
      var _loop = function _loop(_name) {
        if (hasOwnProperty(arg0, _name) && excludedNames[_name] === undefined) {
          createLazyProxy(_name, () => arg0[_name]);
        }
      };
      // createProxy(values)
      for (var _name in arg0) {
        _loop(_name);
      }
    }
  };
  var excludedNames = {
    expression: true,
    docs: true,
    type: true,
    classes: true,
    json: true,
    error: true,
    isChain: true // conflicts with the property isChain of a Chain instance
  };

  // create proxy for everything that is in math.js
  Chain.createProxy(math);

  // register on the import event, automatically add a proxy for every imported function.
  if (on) {
    on('import', function (name, resolver, path) {
      if (!path) {
        // an imported function (not a data type or something special)
        createLazyProxy(name, resolver);
      }
    });
  }
  return Chain;
}, {
  isClass: true
});

var eDocs = {
  name: 'e',
  category: 'Constants',
  syntax: ['e'],
  description: 'Euler\'s number, the base of the natural logarithm. Approximately equal to 2.71828',
  examples: ['e', 'e ^ 2', 'exp(2)', 'log(e)'],
  seealso: ['exp']
};

var falseDocs = {
  name: 'false',
  category: 'Constants',
  syntax: ['false'],
  description: 'Boolean value false',
  examples: ['false'],
  seealso: ['true']
};

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

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

var LN10Docs = {
  name: 'LN10',
  category: 'Constants',
  syntax: ['LN10'],
  description: 'Returns the natural logarithm of 10, approximately equal to 2.302',
  examples: ['LN10', 'log(10)'],
  seealso: []
};

var LN2Docs = {
  name: 'LN2',
  category: 'Constants',
  syntax: ['LN2'],
  description: 'Returns the natural logarithm of 2, approximately equal to 0.693',
  examples: ['LN2', 'log(2)'],
  seealso: []
};

var LOG10EDocs = {
  name: 'LOG10E',
  category: 'Constants',
  syntax: ['LOG10E'],
  description: 'Returns the base-10 logarithm of E, approximately equal to 0.434',
  examples: ['LOG10E', 'log(e, 10)'],
  seealso: []
};

var LOG2EDocs = {
  name: 'LOG2E',
  category: 'Constants',
  syntax: ['LOG2E'],
  description: 'Returns the base-2 logarithm of E, approximately equal to 1.442',
  examples: ['LOG2E', 'log(e, 2)'],
  seealso: []
};

var NaNDocs = {
  name: 'NaN',
  category: 'Constants',
  syntax: ['NaN'],
  description: 'Not a number',
  examples: ['NaN', '0 / 0'],
  seealso: []
};

var nullDocs = {
  name: 'null',
  category: 'Constants',
  syntax: ['null'],
  description: 'Value null',
  examples: ['null'],
  seealso: ['true', 'false']
};

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

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

var SQRT12Docs = {
  name: 'SQRT1_2',
  category: 'Constants',
  syntax: ['SQRT1_2'],
  description: 'Returns the square root of 1/2, approximately equal to 0.707',
  examples: ['SQRT1_2', 'sqrt(1/2)'],
  seealso: []
};

var SQRT2Docs = {
  name: 'SQRT2',
  category: 'Constants',
  syntax: ['SQRT2'],
  description: 'Returns the square root of 2, approximately equal to 1.414',
  examples: ['SQRT2', 'sqrt(2)'],
  seealso: []
};

var tauDocs = {
  name: 'tau',
  category: 'Constants',
  syntax: ['tau'],
  description: 'Tau is the ratio constant of a circle\'s circumference to radius, equal to 2 * pi, approximately 6.2832.',
  examples: ['tau', '2 * pi'],
  seealso: ['pi']
};

var trueDocs = {
  name: 'true',
  category: 'Constants',
  syntax: ['true'],
  description: 'Boolean value true',
  examples: ['true'],
  seealso: ['false']
};

var versionDocs = {
  name: 'version',
  category: 'Constants',
  syntax: ['version'],
  description: 'A string with the version number of math.js',
  examples: ['version'],
  seealso: []
};

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

var bigintDocs = {
  name: 'bigint',
  category: 'Construction',
  syntax: ['bigint(x)'],
  description: 'Create a bigint, an integer with an arbitrary number of digits, from a number or string.',
  examples: ['123123123123123123 # a large number will lose digits', 'bigint("123123123123123123")', 'bignumber(["1", "3", "5"])'],
  seealso: ['boolean', 'bignumber', 'number', 'complex', 'fraction', 'index', 'matrix', 'string', 'unit']
};

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

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

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

var fractionDocs = {
  name: 'fraction',
  category: 'Construction',
  syntax: ['fraction(num)', 'fraction(matrix)', 'fraction(num,den)', 'fraction({n: num, d: den})'],
  description: 'Create a fraction from a number or from integer numerator and denominator.',
  examples: ['fraction(0.125)', 'fraction(1, 3) + fraction(2, 5)', 'fraction({n: 333, d: 53})', 'fraction([sqrt(9), sqrt(10), sqrt(11)])'],
  seealso: ['bignumber', 'boolean', 'complex', 'index', 'matrix', 'string', 'unit']
};

var indexDocs = {
  name: 'index',
  category: 'Construction',
  syntax: ['[start]', '[start:end]', '[start:step:end]', '[start1, start 2, ...]', '[start1:end1, start2:end2, ...]', '[start1:step1:end1, start2:step2:end2, ...]'],
  description: 'Create an index to get or replace a subset of a matrix',
  examples: ['A = [1, 2, 3; 4, 5, 6]', 'A[1, :]', 'A[1, 2] = 50', 'A[1:2, 1:2] = 1', 'B = [1, 2, 3]', 'B[B>1 and B<3]'],
  seealso: ['bignumber', 'boolean', 'complex', 'matrix,', 'number', 'range', 'string', 'unit']
};

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

var numberDocs = {
  name: 'number',
  category: 'Construction',
  syntax: ['x', 'number(x)', 'number(unit, valuelessUnit)'],
  description: 'Create a number or convert a string or boolean into a number.',
  examples: ['2', '2e3', '4.05', 'number(2)', 'number("7.2")', 'number(true)', 'number([true, false, true, true])', 'number(unit("52cm"), "m")'],
  seealso: ['bignumber', 'bigint', 'boolean', 'complex', 'fraction', 'index', 'matrix', 'string', 'unit']
};

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

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

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

var unitDocs = {
  name: 'unit',
  category: 'Construction',
  syntax: ['value unit', 'unit(value, unit)', 'unit(string)'],
  description: 'Create a unit.',
  examples: ['5.5 mm', '3 inch', 'unit(7.1, "kilogram")', 'unit("23 deg")'],
  seealso: ['bignumber', 'boolean', 'complex', 'index', 'matrix', 'number', 'string']
};

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

var importDocs = {
  name: 'import',
  category: 'Core',
  syntax: ['import(functions)', 'import(functions, options)'],
  description: 'Import functions or constants from an object.',
  examples: ['import({myFn: f(x)=x^2, myConstant: 32 })', 'myFn(2)', 'myConstant'],
  seealso: []
};

var typedDocs = {
  name: 'typed',
  category: 'Core',
  syntax: ['typed(signatures)', 'typed(name, signatures)'],
  description: 'Create a typed function.',
  examples: ['double = typed({ "number": f(x)=x+x, "string": f(x)=concat(x,x) })', 'double(2)', 'double("hello")'],
  seealso: []
};

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

var leafCountDocs = {
  name: 'leafCount',
  category: 'Algebra',
  syntax: ['leafCount(expr)'],
  description: 'Computes the number of leaves in the parse tree of the given expression',
  examples: ['leafCount("e^(i*pi)-1")', 'leafCount(parse("{a: 22/7, b: 10^(1/2)}"))'],
  seealso: ['simplify']
};

var lsolveDocs = {
  name: 'lsolve',
  category: 'Algebra',
  syntax: ['x=lsolve(L, b)'],
  description: 'Finds one solution of the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.',
  examples: ['a = [-2, 3; 2, 1]', 'b = [11, 9]', 'x = lsolve(a, b)'],
  seealso: ['lsolveAll', 'lup', 'lusolve', 'usolve', 'matrix', 'sparse']
};

var lsolveAllDocs = {
  name: 'lsolveAll',
  category: 'Algebra',
  syntax: ['x=lsolveAll(L, b)'],
  description: 'Finds all solutions of the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.',
  examples: ['a = [-2, 3; 2, 1]', 'b = [11, 9]', 'x = lsolve(a, b)'],
  seealso: ['lsolve', 'lup', 'lusolve', 'usolve', 'matrix', 'sparse']
};

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

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

var polynomialRootDocs = {
  name: 'polynomialRoot',
  category: 'Algebra',
  syntax: ['x=polynomialRoot(-6, 3)', 'x=polynomialRoot(4, -4, 1)', 'x=polynomialRoot(-8, 12, -6, 1)'],
  description: 'Finds the roots of a univariate polynomial given by its coefficients starting from constant, linear, and so on, increasing in degree.',
  examples: ['a = polynomialRoot(-6, 11, -6, 1)'],
  seealso: ['cbrt', 'sqrt']
};

var qrDocs = {
  name: 'qr',
  category: 'Algebra',
  syntax: ['qr(A)'],
  description: 'Calculates the Matrix QR decomposition. Matrix `A` is decomposed in two matrices (`Q`, `R`) where `Q` is an orthogonal matrix and `R` is an upper triangular matrix.',
  examples: ['qr([[1, -1,  4], [1,  4, -2], [1,  4,  2], [1,  -1, 0]])'],
  seealso: ['lup', 'slu', 'matrix']
};

var rationalizeDocs = {
  name: 'rationalize',
  category: 'Algebra',
  syntax: ['rationalize(expr)', 'rationalize(expr, scope)', 'rationalize(expr, scope, detailed)'],
  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.',
  examples: ['rationalize("2x/y - y/(x+1)")', 'rationalize("2x/y - y/(x+1)", true)'],
  seealso: ['simplify']
};

var resolveDocs = {
  name: 'resolve',
  category: 'Algebra',
  syntax: ['resolve(node, scope)'],
  description: 'Recursively substitute variables in an expression tree.',
  examples: ['resolve(parse("1 + x"), { x: 7 })', 'resolve(parse("size(text)"), { text: "Hello World" })', 'resolve(parse("x + y"), { x: parse("3z") })', 'resolve(parse("3x"), { x: parse("y+z"), z: parse("w^y") })'],
  seealso: ['simplify', 'evaluate'],
  mayThrow: ['ReferenceError']
};

var simplifyDocs = {
  name: 'simplify',
  category: 'Algebra',
  syntax: ['simplify(expr)', 'simplify(expr, rules)'],
  description: 'Simplify an expression tree.',
  examples: ['simplify("3 + 2 / 4")', 'simplify("2x + x")', 'f = parse("x * (x + 2 + x)")', 'simplified = simplify(f)', 'simplified.evaluate({x: 2})'],
  seealso: ['simplifyCore', 'derivative', 'evaluate', 'parse', 'rationalize', 'resolve']
};

var simplifyConstantDocs = {
  name: 'simplifyConstant',
  category: 'Algebra',
  syntax: ['simplifyConstant(expr)', 'simplifyConstant(expr, options)'],
  description: 'Replace constant subexpressions of node with their values.',
  examples: ['simplifyConstant("(3-3)*x")', 'simplifyConstant(parse("z-cos(tau/8)"))'],
  seealso: ['simplify', 'simplifyCore', 'evaluate']
};

var simplifyCoreDocs = {
  name: 'simplifyCore',
  category: 'Algebra',
  syntax: ['simplifyCore(node)'],
  description: 'Perform simple one-pass simplifications on an expression tree.',
  examples: ['simplifyCore(parse("0*x"))', 'simplifyCore(parse("(x+0)*2"))'],
  seealso: ['simplify', 'simplifyConstant', 'evaluate']
};

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

var symbolicEqualDocs = {
  name: 'symbolicEqual',
  category: 'Algebra',
  syntax: ['symbolicEqual(expr1, expr2)', 'symbolicEqual(expr1, expr2, options)'],
  description: 'Returns true if the difference of the expressions simplifies to 0',
  examples: ['symbolicEqual("x*y","y*x")', 'symbolicEqual("abs(x^2)", "x^2")', 'symbolicEqual("abs(x)", "x", {context: {abs: {trivial: true}}})'],
  seealso: ['simplify', 'evaluate']
};

var usolveDocs = {
  name: 'usolve',
  category: 'Algebra',
  syntax: ['x=usolve(U, b)'],
  description: 'Finds one solution of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.',
  examples: ['x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])'],
  seealso: ['usolveAll', 'lup', 'lusolve', 'lsolve', 'matrix', 'sparse']
};

var usolveAllDocs = {
  name: 'usolveAll',
  category: 'Algebra',
  syntax: ['x=usolve(U, b)'],
  description: 'Finds all solutions of the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.',
  examples: ['x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])'],
  seealso: ['usolve', 'lup', 'lusolve', 'lsolve', 'matrix', 'sparse']
};

var absDocs = {
  name: 'abs',
  category: 'Arithmetic',
  syntax: ['abs(x)'],
  description: 'Compute the absolute value.',
  examples: ['abs(3.5)', 'abs(-4.2)'],
  seealso: ['sign']
};

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

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

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

var cubeDocs = {
  name: 'cube',
  category: 'Arithmetic',
  syntax: ['cube(x)'],
  description: 'Compute the cube of a value. The cube of x is x * x * x.',
  examples: ['cube(2)', '2^3', '2 * 2 * 2'],
  seealso: ['multiply', 'square', 'pow']
};

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

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

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

var dotPowDocs = {
  name: 'dotPow',
  category: 'Operators',
  syntax: ['x .^ y', 'dotPow(x, y)'],
  description: 'Calculates the power of x to y element wise.',
  examples: ['a = [1, 2, 3; 4, 5, 6]', 'a .^ 2'],
  seealso: ['pow']
};

var expDocs = {
  name: 'exp',
  category: 'Arithmetic',
  syntax: ['exp(x)'],
  description: 'Calculate the exponent of a value.',
  examples: ['exp(1.3)', 'e ^ 1.3', 'log(exp(1.3))', 'x = 2.4', '(exp(i*x) == cos(x) + i*sin(x))   # Euler\'s formula'],
  seealso: ['expm', 'expm1', 'pow', 'log']
};

var expmDocs = {
  name: 'expm',
  category: 'Arithmetic',
  syntax: ['exp(x)'],
  description: 'Compute the matrix exponential, expm(A) = e^A. ' + 'The matrix must be square. ' + 'Not to be confused with exp(a), which performs element-wise exponentiation.',
  examples: ['expm([[0,2],[0,0]])'],
  seealso: ['exp']
};

var expm1Docs = {
  name: 'expm1',
  category: 'Arithmetic',
  syntax: ['expm1(x)'],
  description: 'Calculate the value of subtracting 1 from the exponential value.',
  examples: ['expm1(2)', 'pow(e, 2) - 1', 'log(expm1(2) + 1)'],
  seealso: ['exp', 'pow', 'log']
};

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

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

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

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

var invmodDocs = {
  name: 'invmod',
  category: 'Arithmetic',
  syntax: ['invmod(a, b)'],
  description: 'Calculate the (modular) multiplicative inverse of a modulo b. Solution to the equation ax ≣ 1 (mod b)',
  examples: ['invmod(8, 12)', 'invmod(7, 13)', 'invmod(15151, 15122)'],
  seealso: ['gcd', 'xgcd']
};

var lcmDocs = {
  name: 'lcm',
  category: 'Arithmetic',
  syntax: ['lcm(x, y)'],
  description: 'Compute the least common multiple.',
  examples: ['lcm(4, 6)', 'lcm(6, 21)', 'lcm(6, 21, 5)'],
  seealso: ['gcd']
};

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

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

var log1pDocs = {
  name: 'log1p',
  category: 'Arithmetic',
  syntax: ['log1p(x)', 'log1p(x, base)'],
  description: 'Calculate the logarithm of a `value+1`',
  examples: ['log1p(2.5)', 'exp(log1p(1.4))', 'pow(10, 4)', 'log1p(9999, 10)', 'log1p(9999) / log(10)'],
  seealso: ['exp', 'log', 'log2', 'log10']
};

var log2Docs = {
  name: 'log2',
  category: 'Arithmetic',
  syntax: ['log2(x)'],
  description: 'Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`.',
  examples: ['log2(0.03125)', 'log2(16)', 'log2(16) / log2(2)', 'pow(2, 4)'],
  seealso: ['exp', 'log1p', 'log', 'log10']
};

var modDocs = {
  name: 'mod',
  category: 'Operators',
  syntax: ['x % y', 'x mod y', 'mod(x, y)'],
  description: 'Calculates the modulus, the remainder of an integer division.',
  examples: ['7 % 3', '11 % 2', '10 mod 4', 'isOdd(x) = x % 2', 'isOdd(2)', 'isOdd(3)'],
  seealso: ['divide']
};

var multiplyDocs = {
  name: 'multiply',
  category: 'Operators',
  syntax: ['x * y', 'multiply(x, y)'],
  description: 'multiply two values.',
  examples: ['a = 2.1 * 3.4', 'a / 3.4', '2 * 3 + 4', '2 * (3 + 4)', '3 * 2.1 km'],
  seealso: ['divide']
};

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

var nthRootDocs = {
  name: 'nthRoot',
  category: 'Arithmetic',
  syntax: ['nthRoot(a)', 'nthRoot(a, root)'],
  description: 'Calculate the nth root of a value. ' + 'The principal nth root of a positive real number A, ' + 'is the positive real solution of the equation "x^root = A".',
  examples: ['4 ^ 3', 'nthRoot(64, 3)', 'nthRoot(9, 2)', 'sqrt(9)'],
  seealso: ['nthRoots', 'pow', 'sqrt']
};

var nthRootsDocs = {
  name: 'nthRoots',
  category: 'Arithmetic',
  syntax: ['nthRoots(A)', 'nthRoots(A, root)'],
  description: '' + 'Calculate the nth roots of a value. ' + 'An nth root of a positive real number A, ' + 'is a positive real solution of the equation "x^root = A". ' + 'This function returns an array of complex values.',
  examples: ['nthRoots(1)', 'nthRoots(1, 3)'],
  seealso: ['sqrt', 'pow', 'nthRoot']
};

var powDocs = {
  name: 'pow',
  category: 'Operators',
  syntax: ['x ^ y', 'pow(x, y)'],
  description: 'Calculates the power of x to y, x^y.',
  examples: ['2^3', '2*2*2', '1 + e ^ (pi * i)', 'pow([[1, 2], [4, 3]], 2)', 'pow([[1, 2], [4, 3]], -1)'],
  seealso: ['multiply', 'nthRoot', 'nthRoots', 'sqrt']
};

var roundDocs = {
  name: 'round',
  category: 'Arithmetic',
  syntax: ['round(x)', 'round(x, n)', 'round(unit, valuelessUnit)', 'round(unit, n, valuelessUnit)'],
  description: 'round a value towards the nearest integer.If x is complex, both real and imaginary part are rounded towards the nearest integer. When n is specified, the value is rounded to n decimals.',
  examples: ['round(3.2)', 'round(3.8)', 'round(-4.2)', 'round(-4.8)', 'round(pi, 3)', 'round(123.45678, 2)', 'round(3.241cm, 2, cm)', 'round([3.2, 3.8, -4.7])'],
  seealso: ['ceil', 'floor', 'fix']
};

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

var sqrtDocs = {
  name: 'sqrt',
  category: 'Arithmetic',
  syntax: ['sqrt(x)'],
  description: 'Compute the square root value. If x = y * y, then y is the square root of x.',
  examples: ['sqrt(25)', '5 * 5', 'sqrt(-1)'],
  seealso: ['square', 'sqrtm', 'multiply', 'nthRoot', 'nthRoots', 'pow']
};

var sqrtmDocs = {
  name: 'sqrtm',
  category: 'Arithmetic',
  syntax: ['sqrtm(x)'],
  description: 'Calculate the principal square root of a square matrix. The principal square root matrix `X` of another matrix `A` is such that `X * X = A`.',
  examples: ['sqrtm([[33, 24], [48, 57]])'],
  seealso: ['sqrt', 'abs', 'square', 'multiply']
};

var sylvesterDocs = {
  name: 'sylvester',
  category: 'Algebra',
  syntax: ['sylvester(A,B,C)'],
  description: 'Solves the real-valued Sylvester equation AX+XB=C for X',
  examples: ['sylvester([[-1, -2], [1, 1]], [[-2, 1], [-1, 2]], [[-3, 2], [3, 0]])', 'A = [[-1, -2], [1, 1]]; B = [[2, -1], [1, -2]]; C = [[-3, 2], [3, 0]]', 'sylvester(A, B, C)'],
  seealso: ['schur', 'lyap']
};

var schurDocs = {
  name: 'schur',
  category: 'Algebra',
  syntax: ['schur(A)'],
  description: 'Performs a real Schur decomposition of the real matrix A = UTU\'',
  examples: ['schur([[1, 0], [-4, 3]])', 'A = [[1, 0], [-4, 3]]', 'schur(A)'],
  seealso: ['lyap', 'sylvester']
};

var lyapDocs = {
  name: 'lyap',
  category: 'Algebra',
  syntax: ['lyap(A,Q)'],
  description: 'Solves the Continuous-time Lyapunov equation AP+PA\'+Q=0 for P',
  examples: ['lyap([[-2, 0], [1, -4]], [[3, 1], [1, 3]])', 'A = [[-2, 0], [1, -4]]', 'Q = [[3, 1], [1, 3]]', 'lyap(A,Q)'],
  seealso: ['schur', 'sylvester']
};

var squareDocs = {
  name: 'square',
  category: 'Arithmetic',
  syntax: ['square(x)'],
  description: 'Compute the square of a value. The square of x is x * x.',
  examples: ['square(3)', 'sqrt(9)', '3^2', '3 * 3'],
  seealso: ['multiply', 'pow', 'sqrt', 'cube']
};

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

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

var unaryPlusDocs = {
  name: 'unaryPlus',
  category: 'Operators',
  syntax: ['+x', 'unaryPlus(x)'],
  description: 'Converts booleans and strings to numbers.',
  examples: ['+true', '+"2"'],
  seealso: ['add', 'subtract', 'unaryMinus']
};

var xgcdDocs = {
  name: 'xgcd',
  category: 'Arithmetic',
  syntax: ['xgcd(a, b)'],
  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.',
  examples: ['xgcd(8, 12)', 'gcd(8, 12)', 'xgcd(36163, 21199)'],
  seealso: ['gcd', 'lcm']
};

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

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

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

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

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

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

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

var bellNumbersDocs = {
  name: 'bellNumbers',
  category: 'Combinatorics',
  syntax: ['bellNumbers(n)'],
  description: 'The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S. `bellNumbers` only takes integer arguments. The following condition must be enforced: n >= 0.',
  examples: ['bellNumbers(3)', 'bellNumbers(8)'],
  seealso: ['stirlingS2']
};

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

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

var stirlingS2Docs = {
  name: 'stirlingS2',
  category: 'Combinatorics',
  syntax: ['stirlingS2(n, k)'],
  description: 'he Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. `stirlingS2` only takes integer arguments. The following condition must be enforced: k <= n. If n = k or k = 1, then s(n,k) = 1.',
  examples: ['stirlingS2(5, 3)'],
  seealso: ['bellNumbers']
};

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

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

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

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

var evaluateDocs = {
  name: 'evaluate',
  category: 'Expression',
  syntax: ['evaluate(expression)', 'evaluate(expression, scope)', 'evaluate([expr1, expr2, expr3, ...])', 'evaluate([expr1, expr2, expr3, ...], scope)'],
  description: 'Evaluate an expression or an array with expressions.',
  examples: ['evaluate("2 + 3")', 'evaluate("sqrt(16)")', 'evaluate("2 inch to cm")', 'evaluate("sin(x * pi)", { "x": 1/2 })', 'evaluate(["width=2", "height=4","width*height"])'],
  seealso: []
};

var helpDocs = {
  name: 'help',
  category: 'Expression',
  syntax: ['help(object)', 'help(string)'],
  description: 'Display documentation on a function or data type.',
  examples: ['help(sqrt)', 'help("complex")'],
  seealso: []
};

var distanceDocs = {
  name: 'distance',
  category: 'Geometry',
  syntax: ['distance([x1, y1], [x2, y2])', 'distance([[x1, y1], [x2, y2]])'],
  description: 'Calculates the Euclidean distance between two points.',
  examples: ['distance([0,0], [4,4])', 'distance([[0,0], [4,4]])'],
  seealso: []
};

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

var andDocs = {
  name: 'and',
  category: 'Logical',
  syntax: ['x and y', 'and(x, y)'],
  description: 'Logical and. Test whether two values are both defined with a nonzero/nonempty value.',
  examples: ['true and false', 'true and true', '2 and 4'],
  seealso: ['not', 'or', 'xor']
};

var notDocs = {
  name: 'not',
  category: 'Logical',
  syntax: ['not x', 'not(x)'],
  description: 'Logical not. Flips the boolean value of given argument.',
  examples: ['not true', 'not false', 'not 2', 'not 0'],
  seealso: ['and', 'or', 'xor']
};

var orDocs = {
  name: 'or',
  category: 'Logical',
  syntax: ['x or y', 'or(x, y)'],
  description: 'Logical or. Test if at least one value is defined with a nonzero/nonempty value.',
  examples: ['true or false', 'false or false', '0 or 4'],
  seealso: ['not', 'and', 'xor']
};

var xorDocs = {
  name: 'xor',
  category: 'Logical',
  syntax: ['x xor y', 'xor(x, y)'],
  description: 'Logical exclusive or, xor. Test whether one and only one value is defined with a nonzero/nonempty value.',
  examples: ['true xor false', 'false xor false', 'true xor true', '0 xor 4'],
  seealso: ['not', 'and', 'or']
};

var columnDocs = {
  name: 'column',
  category: 'Matrix',
  syntax: ['column(x, index)'],
  description: 'Return a column from a matrix or array.',
  examples: ['A = [[1, 2], [3, 4]]', 'column(A, 1)', 'column(A, 2)'],
  seealso: ['row', 'matrixFromColumns']
};

var concatDocs = {
  name: 'concat',
  category: 'Matrix',
  syntax: ['concat(A, B, C, ...)', 'concat(A, B, C, ..., dim)'],
  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.',
  examples: ['A = [1, 2; 5, 6]', 'B = [3, 4; 7, 8]', 'concat(A, B)', 'concat(A, B, 1)', 'concat(A, B, 2)'],
  seealso: ['det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
};

var countDocs = {
  name: 'count',
  category: 'Matrix',
  syntax: ['count(x)'],
  description: 'Count the number of elements of a matrix, array or string.',
  examples: ['a = [1, 2; 3, 4; 5, 6]', 'count(a)', 'size(a)', 'count("hello world")'],
  seealso: ['size']
};

var crossDocs = {
  name: 'cross',
  category: 'Matrix',
  syntax: ['cross(A, B)'],
  description: 'Calculate the cross product for two vectors in three dimensional space.',
  examples: ['cross([1, 1, 0],  [0, 1, 1])', 'cross([3, -3, 1], [4, 9, 2])', 'cross([2, 3, 4],  [5, 6, 7])'],
  seealso: ['multiply', 'dot']
};

var ctransposeDocs = {
  name: 'ctranspose',
  category: 'Matrix',
  syntax: ['x\'', 'ctranspose(x)'],
  description: 'Complex Conjugate and Transpose a matrix',
  examples: ['a = [1, 2, 3; 4, 5, 6]', 'a\'', 'ctranspose(a)'],
  seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'zeros']
};

var detDocs = {
  name: 'det',
  category: 'Matrix',
  syntax: ['det(x)'],
  description: 'Calculate the determinant of a matrix',
  examples: ['det([1, 2; 3, 4])', 'det([-2, 2, 3; -1, 1, 3; 2, 0, -1])'],
  seealso: ['concat', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
};

var diagDocs = {
  name: 'diag',
  category: 'Matrix',
  syntax: ['diag(x)', 'diag(x, k)'],
  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.',
  examples: ['diag(1:3)', 'diag(1:3, 1)', 'a = [1, 2, 3; 4, 5, 6; 7, 8, 9]', 'diag(a)'],
  seealso: ['concat', 'det', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
};

var diffDocs = {
  name: 'diff',
  category: 'Matrix',
  syntax: ['diff(arr)', 'diff(arr, dim)'],
  description: ['Create a new matrix or array with the difference of the passed matrix or array.', 'Dim parameter is optional and used to indicant the dimension of the array/matrix to apply the difference', 'If no dimension parameter is passed it is assumed as dimension 0', 'Dimension is zero-based in javascript and one-based in the parser', 'Arrays must be \'rectangular\' meaning arrays like [1, 2]', 'If something is passed as a matrix it will be returned as a matrix but other than that all matrices are converted to arrays'],
  examples: ['A = [1, 2, 4, 7, 0]', 'diff(A)', 'diff(A, 1)', 'B = [[1, 2], [3, 4]]', 'diff(B)', 'diff(B, 1)', 'diff(B, 2)', 'diff(B, bignumber(2))', 'diff([[1, 2], matrix([3, 4])], 2)'],
  seealso: ['subtract', 'partitionSelect']
};

var dotDocs = {
  name: 'dot',
  category: 'Matrix',
  syntax: ['dot(A, B)', 'A * B'],
  description: 'Calculate the dot product of two vectors. ' + 'The dot product of A = [a1, a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] ' + 'is defined as dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn',
  examples: ['dot([2, 4, 1], [2, 2, 3])', '[2, 4, 1] * [2, 2, 3]'],
  seealso: ['multiply', 'cross']
};

var eigsDocs = {
  name: 'eigs',
  category: 'Matrix',
  syntax: ['eigs(x)'],
  description: 'Calculate the eigenvalues and optionally eigenvectors of a square matrix',
  examples: ['eigs([[5, 2.3], [2.3, 1]])', 'eigs([[1, 2, 3], [4, 5, 6], [7, 8, 9]], { precision: 1e-6, eigenvectors: false })'],
  seealso: ['inv']
};

var filterDocs = {
  name: 'filter',
  category: 'Matrix',
  syntax: ['filter(x, test)'],
  description: 'Filter items in a matrix.',
  examples: ['isPositive(x) = x > 0', 'filter([6, -2, -1, 4, 3], isPositive)', 'filter([6, -2, 0, 1, 0], x != 0)'],
  seealso: ['sort', 'map', 'forEach']
};

var flattenDocs = {
  name: 'flatten',
  category: 'Matrix',
  syntax: ['flatten(x)'],
  description: 'Flatten a multi dimensional matrix into a single dimensional matrix.',
  examples: ['a = [1, 2, 3; 4, 5, 6]', 'size(a)', 'b = flatten(a)', 'size(b)'],
  seealso: ['concat', 'resize', 'size', 'squeeze']
};

var forEachDocs = {
  name: 'forEach',
  category: 'Matrix',
  syntax: ['forEach(x, callback)'],
  description: 'Iterates over all elements of a matrix/array, and executes the given callback function.',
  examples: ['numberOfPets = {}', 'addPet(n) = numberOfPets[n] = (numberOfPets[n] ? numberOfPets[n]:0 ) + 1;', 'forEach(["Dog","Cat","Cat"], addPet)', 'numberOfPets'],
  seealso: ['map', 'sort', 'filter']
};

var getMatrixDataTypeDocs = {
  name: 'getMatrixDataType',
  category: 'Matrix',
  syntax: ['getMatrixDataType(x)'],
  description: 'Find the data type of all elements in a matrix or array, ' + 'for example "number" if all items are a number ' + 'and "Complex" if all values are complex numbers. ' + 'If a matrix contains more than one data type, it will return "mixed".',
  examples: ['getMatrixDataType([1, 2, 3])', 'getMatrixDataType([[5 cm], [2 inch]])', 'getMatrixDataType([1, "text"])', 'getMatrixDataType([1, bignumber(4)])'],
  seealso: ['matrix', 'sparse', 'typeOf']
};

var identityDocs = {
  name: 'identity',
  category: 'Matrix',
  syntax: ['identity(n)', 'identity(m, n)', 'identity([m, n])'],
  description: 'Returns the identity matrix with size m-by-n. The matrix has ones on the diagonal and zeros elsewhere.',
  examples: ['identity(3)', 'identity(3, 5)', 'a = [1, 2, 3; 4, 5, 6]', 'identity(size(a))'],
  seealso: ['concat', 'det', 'diag', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
};

var invDocs = {
  name: 'inv',
  category: 'Matrix',
  syntax: ['inv(x)'],
  description: 'Calculate the inverse of a matrix',
  examples: ['inv([1, 2; 3, 4])', 'inv(4)', '1 / 4'],
  seealso: ['concat', 'det', 'diag', 'identity', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
};

var pinvDocs = {
  name: 'pinv',
  category: 'Matrix',
  syntax: ['pinv(x)'],
  description: 'Calculate the Moore–Penrose inverse of a matrix',
  examples: ['pinv([1, 2; 3, 4])', 'pinv([[1, 0], [0, 1], [0, 1]])', 'pinv(4)'],
  seealso: ['inv']
};

var kronDocs = {
  name: 'kron',
  category: 'Matrix',
  syntax: ['kron(x, y)'],
  description: 'Calculates the kronecker product of 2 matrices or vectors.',
  examples: ['kron([[1, 0], [0, 1]], [[1, 2], [3, 4]])', 'kron([1,1], [2,3,4])'],
  seealso: ['multiply', 'dot', 'cross']
};

var mapDocs = {
  name: 'map',
  category: 'Matrix',
  syntax: ['map(x, callback)'],
  description: 'Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array.',
  examples: ['map([1, 2, 3], square)'],
  seealso: ['filter', 'forEach']
};

var matrixFromColumnsDocs = {
  name: 'matrixFromColumns',
  category: 'Matrix',
  syntax: ['matrixFromColumns(...arr)', 'matrixFromColumns(row1, row2)', 'matrixFromColumns(row1, row2, row3)'],
  description: 'Create a dense matrix from vectors as individual columns.',
  examples: ['matrixFromColumns([1, 2, 3], [[4],[5],[6]])'],
  seealso: ['matrix', 'matrixFromRows', 'matrixFromFunction', 'zeros']
};

var matrixFromFunctionDocs = {
  name: 'matrixFromFunction',
  category: 'Matrix',
  syntax: ['matrixFromFunction(size, fn)', 'matrixFromFunction(size, fn, format)', 'matrixFromFunction(size, fn, format, datatype)', 'matrixFromFunction(size, format, fn)', 'matrixFromFunction(size, format, datatype, fn)'],
  description: 'Create a matrix by evaluating a generating function at each index.',
  examples: ['f(I) = I[1] - I[2]', 'matrixFromFunction([3,3], f)', 'g(I) = I[1] - I[2] == 1 ? 4 : 0', 'matrixFromFunction([100, 100], "sparse", g)', 'matrixFromFunction([5], random)'],
  seealso: ['matrix', 'matrixFromRows', 'matrixFromColumns', 'zeros']
};

var matrixFromRowsDocs = {
  name: 'matrixFromRows',
  category: 'Matrix',
  syntax: ['matrixFromRows(...arr)', 'matrixFromRows(row1, row2)', 'matrixFromRows(row1, row2, row3)'],
  description: 'Create a dense matrix from vectors as individual rows.',
  examples: ['matrixFromRows([1, 2, 3], [[4],[5],[6]])'],
  seealso: ['matrix', 'matrixFromColumns', 'matrixFromFunction', 'zeros']
};

var onesDocs = {
  name: 'ones',
  category: 'Matrix',
  syntax: ['ones(m)', 'ones(m, n)', 'ones(m, n, p, ...)', 'ones([m])', 'ones([m, n])', 'ones([m, n, p, ...])'],
  description: 'Create a matrix containing ones.',
  examples: ['ones(3)', 'ones(3, 5)', 'ones([2,3]) * 4.5', 'a = [1, 2, 3; 4, 5, 6]', 'ones(size(a))'],
  seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
};

var partitionSelectDocs = {
  name: 'partitionSelect',
  category: 'Matrix',
  syntax: ['partitionSelect(x, k)', 'partitionSelect(x, k, compare)'],
  description: 'Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect.',
  examples: ['partitionSelect([5, 10, 1], 2)', 'partitionSelect(["C", "B", "A", "D"], 1, compareText)', 'arr = [5, 2, 1]', 'partitionSelect(arr, 0) # returns 1, arr is now: [1, 2, 5]', 'arr', 'partitionSelect(arr, 1, \'desc\') # returns 2, arr is now: [5, 2, 1]', 'arr'],
  seealso: ['sort']
};

var rangeDocs = {
  name: 'range',
  category: 'Type',
  syntax: ['start:end', 'start:step:end', 'range(start, end)', 'range(start, end, step)', 'range(string)'],
  description: 'Create a range. Lower bound of the range is included, upper bound is excluded.',
  examples: ['1:5', '3:-1:-3', 'range(3, 7)', 'range(0, 12, 2)', 'range("4:10")', 'range(1m, 1m, 3m)', 'a = [1, 2, 3, 4; 5, 6, 7, 8]', 'a[1:2, 1:2]'],
  seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
};

var reshapeDocs = {
  name: 'reshape',
  category: 'Matrix',
  syntax: ['reshape(x, sizes)'],
  description: 'Reshape a multi dimensional array to fit the specified dimensions.',
  examples: ['reshape([1, 2, 3, 4, 5, 6], [2, 3])', 'reshape([[1, 2], [3, 4]], [1, 4])', 'reshape([[1, 2], [3, 4]], [4])', 'reshape([1, 2, 3, 4], [-1, 2])'],
  seealso: ['size', 'squeeze', 'resize']
};

var resizeDocs = {
  name: 'resize',
  category: 'Matrix',
  syntax: ['resize(x, size)', 'resize(x, size, defaultValue)'],
  description: 'Resize a matrix.',
  examples: ['resize([1,2,3,4,5], [3])', 'resize([1,2,3], [5])', 'resize([1,2,3], [5], -1)', 'resize(2, [2, 3])', 'resize("hello", [8], "!")'],
  seealso: ['size', 'subset', 'squeeze', 'reshape']
};

var rotateDocs = {
  name: 'rotate',
  category: 'Matrix',
  syntax: ['rotate(w, theta)', 'rotate(w, theta, v)'],
  description: 'Returns a 2-D rotation matrix (2x2) for a given angle (in radians). ' + 'Returns a 2-D rotation matrix (3x3) of a given angle (in radians) around given axis.',
  examples: ['rotate([1, 0], pi / 2)', 'rotate(matrix([1, 0]), unit("35deg"))', 'rotate([1, 0, 0], unit("90deg"), [0, 0, 1])', 'rotate(matrix([1, 0, 0]), unit("90deg"), matrix([0, 0, 1]))'],
  seealso: ['matrix', 'rotationMatrix']
};

var rotationMatrixDocs = {
  name: 'rotationMatrix',
  category: 'Matrix',
  syntax: ['rotationMatrix(theta)', 'rotationMatrix(theta, v)', 'rotationMatrix(theta, v, format)'],
  description: 'Returns a 2-D rotation matrix (2x2) for a given angle (in radians). ' + 'Returns a 2-D rotation matrix (3x3) of a given angle (in radians) around given axis.',
  examples: ['rotationMatrix(pi / 2)', 'rotationMatrix(unit("45deg"), [0, 0, 1])', 'rotationMatrix(1, matrix([0, 0, 1]), "sparse")'],
  seealso: ['cos', 'sin']
};

var rowDocs = {
  name: 'row',
  category: 'Matrix',
  syntax: ['row(x, index)'],
  description: 'Return a row from a matrix or array.',
  examples: ['A = [[1, 2], [3, 4]]', 'row(A, 1)', 'row(A, 2)'],
  seealso: ['column', 'matrixFromRows']
};

var sizeDocs = {
  name: 'size',
  category: 'Matrix',
  syntax: ['size(x)'],
  description: 'Calculate the size of a matrix.',
  examples: ['size(2.3)', 'size("hello world")', 'a = [1, 2; 3, 4; 5, 6]', 'size(a)', 'size(1:6)'],
  seealso: ['concat', 'count', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
};

var sortDocs = {
  name: 'sort',
  category: 'Matrix',
  syntax: ['sort(x)', 'sort(x, compare)'],
  description: 'Sort the items in a matrix. Compare can be a string "asc", "desc", "natural", or a custom sort function.',
  examples: ['sort([5, 10, 1])', 'sort(["C", "B", "A", "D"], "natural")', 'sortByLength(a, b) = size(a)[1] - size(b)[1]', 'sort(["Langdon", "Tom", "Sara"], sortByLength)', 'sort(["10", "1", "2"], "natural")'],
  seealso: ['map', 'filter', 'forEach']
};

var squeezeDocs = {
  name: 'squeeze',
  category: 'Matrix',
  syntax: ['squeeze(x)'],
  description: 'Remove inner and outer singleton dimensions from a matrix.',
  examples: ['a = zeros(3,2,1)', 'size(squeeze(a))', 'b = zeros(1,1,3)', 'size(squeeze(b))'],
  seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'subset', 'trace', 'transpose', 'zeros']
};

var subsetDocs = {
  name: 'subset',
  category: 'Matrix',
  syntax: ['value(index)', 'value(index) = replacement', 'subset(value, [index])', 'subset(value, [index], replacement)'],
  description: 'Get or set a subset of the entries of a matrix or ' + 'characters of a string. ' + 'Indexes are one-based. There should be one index specification for ' + 'each dimension of the target. Each specification can be a single ' + 'index, a list of indices, or a range in colon notation `l:u`. ' + 'In a range, both the lower bound l and upper bound u are included; ' + 'and if a bound is omitted it defaults to the most extreme valid value. ' + 'The cartesian product of the indices specified in each dimension ' + 'determines the target of the operation.',
  examples: ['d = [1, 2; 3, 4]', 'e = []', 'e[1, 1:2] = [5, 6]', 'e[2, :] = [7, 8]', 'f = d * e', 'f[2, 1]', 'f[:, 1]', 'f[[1,2], [1,3]] = [9, 10; 11, 12]', 'f'],
  seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'trace', 'transpose', 'zeros']
};

var traceDocs = {
  name: 'trace',
  category: 'Matrix',
  syntax: ['trace(A)'],
  description: 'Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix.',
  examples: ['A = [1, 2, 3; -1, 2, 3; 2, 0, 3]', 'trace(A)'],
  seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'transpose', 'zeros']
};

var transposeDocs = {
  name: 'transpose',
  category: 'Matrix',
  syntax: ['x\'', 'transpose(x)'],
  description: 'Transpose a matrix',
  examples: ['a = [1, 2, 3; 4, 5, 6]', 'a\'', 'transpose(a)'],
  seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'zeros']
};

var zerosDocs = {
  name: 'zeros',
  category: 'Matrix',
  syntax: ['zeros(m)', 'zeros(m, n)', 'zeros(m, n, p, ...)', 'zeros([m])', 'zeros([m, n])', 'zeros([m, n, p, ...])'],
  description: 'Create a matrix containing zeros.',
  examples: ['zeros(3)', 'zeros(3, 5)', 'a = [1, 2, 3; 4, 5, 6]', 'zeros(size(a))'],
  seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose']
};

var fftDocs = {
  name: 'fft',
  category: 'Matrix',
  syntax: ['fft(x)'],
  description: 'Calculate N-dimensional fourier transform',
  examples: ['fft([[1, 0], [1, 0]])'],
  seealso: ['ifft']
};

var ifftDocs = {
  name: 'ifft',
  category: 'Matrix',
  syntax: ['ifft(x)'],
  description: 'Calculate N-dimensional inverse fourier transform',
  examples: ['ifft([[2, 2], [0, 0]])'],
  seealso: ['fft']
};

var combinationsDocs = {
  name: 'combinations',
  category: 'Probability',
  syntax: ['combinations(n, k)'],
  description: 'Compute the number of combinations of n items taken k at a time',
  examples: ['combinations(7, 5)'],
  seealso: ['combinationsWithRep', 'permutations', 'factorial']
};

var combinationsWithRepDocs = {
  name: 'combinationsWithRep',
  category: 'Probability',
  syntax: ['combinationsWithRep(n, k)'],
  description: 'Compute the number of combinations of n items taken k at a time with replacements.',
  examples: ['combinationsWithRep(7, 5)'],
  seealso: ['combinations', 'permutations', 'factorial']
};

var factorialDocs = {
  name: 'factorial',
  category: 'Probability',
  syntax: ['n!', 'factorial(n)'],
  description: 'Compute the factorial of a value',
  examples: ['5!', '5 * 4 * 3 * 2 * 1', '3!'],
  seealso: ['combinations', 'combinationsWithRep', 'permutations', 'gamma']
};

var gammaDocs = {
  name: 'gamma',
  category: 'Probability',
  syntax: ['gamma(n)'],
  description: 'Compute the gamma function. For small values, the Lanczos approximation is used, and for large values the extended Stirling approximation.',
  examples: ['gamma(4)', '3!', 'gamma(1/2)', 'sqrt(pi)'],
  seealso: ['factorial']
};

var lgammaDocs = {
  name: 'lgamma',
  category: 'Probability',
  syntax: ['lgamma(n)'],
  description: 'Logarithm of the gamma function for real, positive numbers and complex numbers, ' + 'using Lanczos approximation for numbers and Stirling series for complex numbers.',
  examples: ['lgamma(4)', 'lgamma(1/2)', 'lgamma(i)', 'lgamma(complex(1.1, 2))'],
  seealso: ['gamma']
};

var kldivergenceDocs = {
  name: 'kldivergence',
  category: 'Probability',
  syntax: ['kldivergence(x, y)'],
  description: 'Calculate the Kullback-Leibler (KL) divergence  between two distributions.',
  examples: ['kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5])'],
  seealso: []
};

var multinomialDocs = {
  name: 'multinomial',
  category: 'Probability',
  syntax: ['multinomial(A)'],
  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.',
  examples: ['multinomial([1, 2, 1])'],
  seealso: ['combinations', 'factorial']
};

var permutationsDocs = {
  name: 'permutations',
  category: 'Probability',
  syntax: ['permutations(n)', 'permutations(n, k)'],
  description: 'Compute the number of permutations of n items taken k at a time',
  examples: ['permutations(5)', 'permutations(5, 3)'],
  seealso: ['combinations', 'combinationsWithRep', 'factorial']
};

var pickRandomDocs = {
  name: 'pickRandom',
  category: 'Probability',
  syntax: ['pickRandom(array)', 'pickRandom(array, number)', 'pickRandom(array, weights)', 'pickRandom(array, number, weights)', 'pickRandom(array, weights, number)'],
  description: 'Pick a random entry from a given array.',
  examples: ['pickRandom(0:10)', 'pickRandom([1, 3, 1, 6])', 'pickRandom([1, 3, 1, 6], 2)', 'pickRandom([1, 3, 1, 6], [2, 3, 2, 1])', 'pickRandom([1, 3, 1, 6], 2, [2, 3, 2, 1])', 'pickRandom([1, 3, 1, 6], [2, 3, 2, 1], 2)'],
  seealso: ['random', 'randomInt']
};

var randomDocs = {
  name: 'random',
  category: 'Probability',
  syntax: ['random()', 'random(max)', 'random(min, max)', 'random(size)', 'random(size, max)', 'random(size, min, max)'],
  description: 'Return a random number.',
  examples: ['random()', 'random(10, 20)', 'random([2, 3])'],
  seealso: ['pickRandom', 'randomInt']
};

var randomIntDocs = {
  name: 'randomInt',
  category: 'Probability',
  syntax: ['randomInt(max)', 'randomInt(min, max)', 'randomInt(size)', 'randomInt(size, max)', 'randomInt(size, min, max)'],
  description: 'Return a random integer number',
  examples: ['randomInt(10, 20)', 'randomInt([2, 3], 10)'],
  seealso: ['pickRandom', 'random']
};

var compareDocs = {
  name: 'compare',
  category: 'Relational',
  syntax: ['compare(x, y)'],
  description: 'Compare two values. ' + 'Returns 1 when x > y, -1 when x < y, and 0 when x == y.',
  examples: ['compare(2, 3)', 'compare(3, 2)', 'compare(2, 2)', 'compare(5cm, 40mm)', 'compare(2, [1, 2, 3])'],
  seealso: ['equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compareNatural', 'compareText']
};

var compareNaturalDocs = {
  name: 'compareNatural',
  category: 'Relational',
  syntax: ['compareNatural(x, y)'],
  description: 'Compare two values of any type in a deterministic, natural way. ' + 'Returns 1 when x > y, -1 when x < y, and 0 when x == y.',
  examples: ['compareNatural(2, 3)', 'compareNatural(3, 2)', 'compareNatural(2, 2)', 'compareNatural(5cm, 40mm)', 'compareNatural("2", "10")', 'compareNatural(2 + 3i, 2 + 4i)', 'compareNatural([1, 2, 4], [1, 2, 3])', 'compareNatural([1, 5], [1, 2, 3])', 'compareNatural([1, 2], [1, 2])', 'compareNatural({a: 2}, {a: 4})'],
  seealso: ['equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compare', 'compareText']
};

var compareTextDocs = {
  name: 'compareText',
  category: 'Relational',
  syntax: ['compareText(x, y)'],
  description: 'Compare two strings lexically. Comparison is case sensitive. ' + 'Returns 1 when x > y, -1 when x < y, and 0 when x == y.',
  examples: ['compareText("B", "A")', 'compareText("A", "B")', 'compareText("A", "A")', 'compareText("2", "10")', 'compare("2", "10")', 'compare(2, 10)', 'compareNatural("2", "10")', 'compareText("B", ["A", "B", "C"])'],
  seealso: ['compare', 'compareNatural']
};

var deepEqualDocs = {
  name: 'deepEqual',
  category: 'Relational',
  syntax: ['deepEqual(x, y)'],
  description: 'Check equality of two matrices element wise. Returns true if the size of both matrices is equal and when and each of the elements are equal.',
  examples: ['deepEqual([1,3,4], [1,3,4])', 'deepEqual([1,3,4], [1,3])'],
  seealso: ['equal', 'unequal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare']
};

var equalDocs = {
  name: 'equal',
  category: 'Relational',
  syntax: ['x == y', 'equal(x, y)'],
  description: 'Check equality of two values. Returns true if the values are equal, and false if not.',
  examples: ['2+2 == 3', '2+2 == 4', 'a = 3.2', 'b = 6-2.8', 'a == b', '50cm == 0.5m'],
  seealso: ['unequal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare', 'deepEqual', 'equalText']
};

var equalTextDocs = {
  name: 'equalText',
  category: 'Relational',
  syntax: ['equalText(x, y)'],
  description: 'Check equality of two strings. Comparison is case sensitive. Returns true if the values are equal, and false if not.',
  examples: ['equalText("Hello", "Hello")', 'equalText("a", "A")', 'equal("2e3", "2000")', 'equalText("2e3", "2000")', 'equalText("B", ["A", "B", "C"])'],
  seealso: ['compare', 'compareNatural', 'compareText', 'equal']
};

var largerDocs = {
  name: 'larger',
  category: 'Relational',
  syntax: ['x > y', 'larger(x, y)'],
  description: 'Check if value x is larger than y. Returns true if x is larger than y, and false if not.',
  examples: ['2 > 3', '5 > 2*2', 'a = 3.3', 'b = 6-2.8', '(a > b)', '(b < a)', '5 cm > 2 inch'],
  seealso: ['equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compare']
};

var largerEqDocs = {
  name: 'largerEq',
  category: 'Relational',
  syntax: ['x >= y', 'largerEq(x, y)'],
  description: 'Check if value x is larger or equal to y. Returns true if x is larger or equal to y, and false if not.',
  examples: ['2 >= 1+1', '2 > 1+1', 'a = 3.2', 'b = 6-2.8', '(a >= b)'],
  seealso: ['equal', 'unequal', 'smallerEq', 'smaller', 'compare']
};

var smallerDocs = {
  name: 'smaller',
  category: 'Relational',
  syntax: ['x < y', 'smaller(x, y)'],
  description: 'Check if value x is smaller than value y. Returns true if x is smaller than y, and false if not.',
  examples: ['2 < 3', '5 < 2*2', 'a = 3.3', 'b = 6-2.8', '(a < b)', '5 cm < 2 inch'],
  seealso: ['equal', 'unequal', 'larger', 'smallerEq', 'largerEq', 'compare']
};

var smallerEqDocs = {
  name: 'smallerEq',
  category: 'Relational',
  syntax: ['x <= y', 'smallerEq(x, y)'],
  description: 'Check if value x is smaller or equal to value y. Returns true if x is smaller than y, and false if not.',
  examples: ['2 <= 1+1', '2 < 1+1', 'a = 3.2', 'b = 6-2.8', '(a <= b)'],
  seealso: ['equal', 'unequal', 'larger', 'smaller', 'largerEq', 'compare']
};

var unequalDocs = {
  name: 'unequal',
  category: 'Relational',
  syntax: ['x != y', 'unequal(x, y)'],
  description: 'Check unequality of two values. Returns true if the values are unequal, and false if they are equal.',
  examples: ['2+2 != 3', '2+2 != 4', 'a = 3.2', 'b = 6-2.8', 'a != b', '50cm != 0.5m', '5 cm != 2 inch'],
  seealso: ['equal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare', 'deepEqual']
};

var setCartesianDocs = {
  name: 'setCartesian',
  category: 'Set',
  syntax: ['setCartesian(set1, set2)'],
  description: 'Create the cartesian product of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays and the values will be sorted in ascending order before the operation.',
  examples: ['setCartesian([1, 2], [3, 4])'],
  seealso: ['setUnion', 'setIntersect', 'setDifference', 'setPowerset']
};

var setDifferenceDocs = {
  name: 'setDifference',
  category: 'Set',
  syntax: ['setDifference(set1, set2)'],
  description: 'Create the difference of two (multi)sets: every element of set1, that is not the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
  examples: ['setDifference([1, 2, 3, 4], [3, 4, 5, 6])', 'setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])'],
  seealso: ['setUnion', 'setIntersect', 'setSymDifference']
};

var setDistinctDocs = {
  name: 'setDistinct',
  category: 'Set',
  syntax: ['setDistinct(set)'],
  description: 'Collect the distinct elements of a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.',
  examples: ['setDistinct([1, 1, 1, 2, 2, 3])'],
  seealso: ['setMultiplicity']
};

var setIntersectDocs = {
  name: 'setIntersect',
  category: 'Set',
  syntax: ['setIntersect(set1, set2)'],
  description: 'Create the intersection of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
  examples: ['setIntersect([1, 2, 3, 4], [3, 4, 5, 6])', 'setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]])'],
  seealso: ['setUnion', 'setDifference']
};

var setIsSubsetDocs = {
  name: 'setIsSubset',
  category: 'Set',
  syntax: ['setIsSubset(set1, set2)'],
  description: 'Check whether a (multi)set is a subset of another (multi)set: every element of set1 is the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
  examples: ['setIsSubset([1, 2], [3, 4, 5, 6])', 'setIsSubset([3, 4], [3, 4, 5, 6])'],
  seealso: ['setUnion', 'setIntersect', 'setDifference']
};

var setMultiplicityDocs = {
  name: 'setMultiplicity',
  category: 'Set',
  syntax: ['setMultiplicity(element, set)'],
  description: 'Count the multiplicity of an element in a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.',
  examples: ['setMultiplicity(1, [1, 2, 2, 4])', 'setMultiplicity(2, [1, 2, 2, 4])'],
  seealso: ['setDistinct', 'setSize']
};

var setPowersetDocs = {
  name: 'setPowerset',
  category: 'Set',
  syntax: ['setPowerset(set)'],
  description: 'Create the powerset of a (multi)set: the powerset contains very possible subsets of a (multi)set. A multi-dimension array will be converted to a single-dimension array before the operation.',
  examples: ['setPowerset([1, 2, 3])'],
  seealso: ['setCartesian']
};

var setSizeDocs = {
  name: 'setSize',
  category: 'Set',
  syntax: ['setSize(set)', 'setSize(set, unique)'],
  description: 'Count the number of elements of a (multi)set. When the second parameter "unique" is true, count only the unique values. A multi-dimension array will be converted to a single-dimension array before the operation.',
  examples: ['setSize([1, 2, 2, 4])', 'setSize([1, 2, 2, 4], true)'],
  seealso: ['setUnion', 'setIntersect', 'setDifference']
};

var setSymDifferenceDocs = {
  name: 'setSymDifference',
  category: 'Set',
  syntax: ['setSymDifference(set1, set2)'],
  description: 'Create the symmetric difference of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
  examples: ['setSymDifference([1, 2, 3, 4], [3, 4, 5, 6])', 'setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])'],
  seealso: ['setUnion', 'setIntersect', 'setDifference']
};

var setUnionDocs = {
  name: 'setUnion',
  category: 'Set',
  syntax: ['setUnion(set1, set2)'],
  description: 'Create the union of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
  examples: ['setUnion([1, 2, 3, 4], [3, 4, 5, 6])', 'setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]])'],
  seealso: ['setIntersect', 'setDifference']
};

var zpk2tfDocs = {
  name: 'zpk2tf',
  category: 'Signal',
  syntax: ['zpk2tf(z, p, k)'],
  description: 'Compute the transfer function of a zero-pole-gain model.',
  examples: ['zpk2tf([1, 2], [-1, -2], 1)', 'zpk2tf([1, 2], [-1, -2])', 'zpk2tf([1 - 3i, 2 + 2i], [-1, -2])'],
  seealso: []
};

var freqzDocs = {
  name: 'freqz',
  category: 'Signal',
  syntax: ['freqz(b, a)', 'freqz(b, a, w)'],
  description: 'Calculates the frequency response of a filter given its numerator and denominator coefficients.',
  examples: ['freqz([1, 2], [1, 2, 3])', 'freqz([1, 2], [1, 2, 3], [0, 1])', 'freqz([1, 2], [1, 2, 3], 512)'],
  seealso: []
};

var erfDocs = {
  name: 'erf',
  category: 'Special',
  syntax: ['erf(x)'],
  description: 'Compute the erf function of a value using a rational Chebyshev approximations for different intervals of x',
  examples: ['erf(0.2)', 'erf(-0.5)', 'erf(4)'],
  seealso: []
};

var zetaDocs = {
  name: 'zeta',
  category: 'Special',
  syntax: ['zeta(s)'],
  description: 'Compute the Riemann Zeta Function using an infinite series and Riemanns Functional Equation for the entire complex plane',
  examples: ['zeta(0.2)', 'zeta(-0.5)', 'zeta(4)'],
  seealso: []
};

var madDocs = {
  name: 'mad',
  category: 'Statistics',
  syntax: ['mad(a, b, c, ...)', 'mad(A)'],
  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.',
  examples: ['mad(10, 20, 30)', 'mad([1, 2, 3])'],
  seealso: ['mean', 'median', 'std', 'abs']
};

var maxDocs = {
  name: 'max',
  category: 'Statistics',
  syntax: ['max(a, b, c, ...)', 'max(A)', 'max(A, dimension)'],
  description: 'Compute the maximum value of a list of values.',
  examples: ['max(2, 3, 4, 1)', 'max([2, 3, 4, 1])', 'max([2, 5; 4, 3])', 'max([2, 5; 4, 3], 1)', 'max([2, 5; 4, 3], 2)', 'max(2.7, 7.1, -4.5, 2.0, 4.1)', 'min(2.7, 7.1, -4.5, 2.0, 4.1)'],
  seealso: ['mean', 'median', 'min', 'prod', 'std', 'sum', 'variance']
};

var meanDocs = {
  name: 'mean',
  category: 'Statistics',
  syntax: ['mean(a, b, c, ...)', 'mean(A)', 'mean(A, dimension)'],
  description: 'Compute the arithmetic mean of a list of values.',
  examples: ['mean(2, 3, 4, 1)', 'mean([2, 3, 4, 1])', 'mean([2, 5; 4, 3])', 'mean([2, 5; 4, 3], 1)', 'mean([2, 5; 4, 3], 2)', 'mean([1.0, 2.7, 3.2, 4.0])'],
  seealso: ['max', 'median', 'min', 'prod', 'std', 'sum', 'variance']
};

var medianDocs = {
  name: 'median',
  category: 'Statistics',
  syntax: ['median(a, b, c, ...)', 'median(A)'],
  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.',
  examples: ['median(5, 2, 7)', 'median([3, -1, 5, 7])'],
  seealso: ['max', 'mean', 'min', 'prod', 'std', 'sum', 'variance', 'quantileSeq']
};

var minDocs = {
  name: 'min',
  category: 'Statistics',
  syntax: ['min(a, b, c, ...)', 'min(A)', 'min(A, dimension)'],
  description: 'Compute the minimum value of a list of values.',
  examples: ['min(2, 3, 4, 1)', 'min([2, 3, 4, 1])', 'min([2, 5; 4, 3])', 'min([2, 5; 4, 3], 1)', 'min([2, 5; 4, 3], 2)', 'min(2.7, 7.1, -4.5, 2.0, 4.1)', 'max(2.7, 7.1, -4.5, 2.0, 4.1)'],
  seealso: ['max', 'mean', 'median', 'prod', 'std', 'sum', 'variance']
};

var modeDocs = {
  name: 'mode',
  category: 'Statistics',
  syntax: ['mode(a, b, c, ...)', 'mode(A)', 'mode(A, a, b, B, c, ...)'],
  description: 'Computes the mode of all values as an array. In case mode being more than one, multiple values are returned in an array.',
  examples: ['mode(2, 1, 4, 3, 1)', 'mode([1, 2.7, 3.2, 4, 2.7])', 'mode(1, 4, 6, 1, 6)'],
  seealso: ['max', 'mean', 'min', 'median', 'prod', 'std', 'sum', 'variance']
};

var prodDocs = {
  name: 'prod',
  category: 'Statistics',
  syntax: ['prod(a, b, c, ...)', 'prod(A)'],
  description: 'Compute the product of all values.',
  examples: ['prod(2, 3, 4)', 'prod([2, 3, 4])', 'prod([2, 5; 4, 3])'],
  seealso: ['max', 'mean', 'min', 'median', 'min', 'std', 'sum', 'variance']
};

var quantileSeqDocs = {
  name: 'quantileSeq',
  category: 'Statistics',
  syntax: ['quantileSeq(A, prob[, sorted])', 'quantileSeq(A, [prob1, prob2, ...][, sorted])', 'quantileSeq(A, N[, sorted])'],
  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.',
  examples: ['quantileSeq([3, -1, 5, 7], 0.5)', 'quantileSeq([3, -1, 5, 7], [1/3, 2/3])', 'quantileSeq([3, -1, 5, 7], 2)', 'quantileSeq([-1, 3, 5, 7], 0.5, true)'],
  seealso: ['mean', 'median', 'min', 'max', 'prod', 'std', 'sum', 'variance']
};

var stdDocs = {
  name: 'std',
  category: 'Statistics',
  syntax: ['std(a, b, c, ...)', 'std(A)', 'std(A, dimension)', 'std(A, normalization)', 'std(A, dimension, normalization)'],
  description: 'Compute the standard deviation of all values, defined as std(A) = sqrt(variance(A)). Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',
  examples: ['std(2, 4, 6)', 'std([2, 4, 6, 8])', 'std([2, 4, 6, 8], "uncorrected")', 'std([2, 4, 6, 8], "biased")', 'std([1, 2, 3; 4, 5, 6])'],
  seealso: ['max', 'mean', 'min', 'median', 'prod', 'sum', 'variance']
};

var cumSumDocs = {
  name: 'cumsum',
  category: 'Statistics',
  syntax: ['cumsum(a, b, c, ...)', 'cumsum(A)'],
  description: 'Compute the cumulative sum of all values.',
  examples: ['cumsum(2, 3, 4, 1)', 'cumsum([2, 3, 4, 1])', 'cumsum([1, 2; 3, 4])', 'cumsum([1, 2; 3, 4], 1)', 'cumsum([1, 2; 3, 4], 2)'],
  seealso: ['max', 'mean', 'median', 'min', 'prod', 'std', 'sum', 'variance']
};

var sumDocs = {
  name: 'sum',
  category: 'Statistics',
  syntax: ['sum(a, b, c, ...)', 'sum(A)', 'sum(A, dimension)'],
  description: 'Compute the sum of all values.',
  examples: ['sum(2, 3, 4, 1)', 'sum([2, 3, 4, 1])', 'sum([2, 5; 4, 3])'],
  seealso: ['max', 'mean', 'median', 'min', 'prod', 'std', 'sum', 'variance']
};

var varianceDocs = {
  name: 'variance',
  category: 'Statistics',
  syntax: ['variance(a, b, c, ...)', 'variance(A)', 'variance(A, dimension)', 'variance(A, normalization)', 'variance(A, dimension, normalization)'],
  description: 'Compute the variance of all values. Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',
  examples: ['variance(2, 4, 6)', 'variance([2, 4, 6, 8])', 'variance([2, 4, 6, 8], "uncorrected")', 'variance([2, 4, 6, 8], "biased")', 'variance([1, 2, 3; 4, 5, 6])'],
  seealso: ['max', 'mean', 'min', 'median', 'min', 'prod', 'std', 'sum']
};

var corrDocs = {
  name: 'corr',
  category: 'Statistics',
  syntax: ['corr(A,B)'],
  description: 'Compute the correlation coefficient of a two list with values, For matrices, the matrix correlation coefficient is calculated.',
  examples: ['corr([2, 4, 6, 8],[1, 2, 3, 6])', 'corr(matrix([[1, 2.2, 3, 4.8, 5], [1, 2, 3, 4, 5]]), matrix([[4, 5.3, 6.6, 7, 8], [1, 2, 3, 4, 5]]))'],
  seealso: ['max', 'mean', 'min', 'median', 'min', 'prod', 'std', 'sum']
};

var acosDocs = {
  name: 'acos',
  category: 'Trigonometry',
  syntax: ['acos(x)'],
  description: 'Compute the inverse cosine of a value in radians.',
  examples: ['acos(0.5)', 'acos(cos(2.3))'],
  seealso: ['cos', 'atan', 'asin']
};

var acoshDocs = {
  name: 'acosh',
  category: 'Trigonometry',
  syntax: ['acosh(x)'],
  description: 'Calculate the hyperbolic arccos of a value, defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.',
  examples: ['acosh(1.5)'],
  seealso: ['cosh', 'asinh', 'atanh']
};

var acotDocs = {
  name: 'acot',
  category: 'Trigonometry',
  syntax: ['acot(x)'],
  description: 'Calculate the inverse cotangent of a value.',
  examples: ['acot(0.5)', 'acot(cot(0.5))', 'acot(2)'],
  seealso: ['cot', 'atan']
};

var acothDocs = {
  name: 'acoth',
  category: 'Trigonometry',
  syntax: ['acoth(x)'],
  description: 'Calculate the hyperbolic arccotangent of a value, defined as `acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.',
  examples: ['acoth(2)', 'acoth(0.5)'],
  seealso: ['acsch', 'asech']
};

var acscDocs = {
  name: 'acsc',
  category: 'Trigonometry',
  syntax: ['acsc(x)'],
  description: 'Calculate the inverse cotangent of a value.',
  examples: ['acsc(2)', 'acsc(csc(0.5))', 'acsc(0.5)'],
  seealso: ['csc', 'asin', 'asec']
};

var acschDocs = {
  name: 'acsch',
  category: 'Trigonometry',
  syntax: ['acsch(x)'],
  description: 'Calculate the hyperbolic arccosecant of a value, defined as `acsch(x) = ln(1/x + sqrt(1/x^2 + 1))`.',
  examples: ['acsch(0.5)'],
  seealso: ['asech', 'acoth']
};

var asecDocs = {
  name: 'asec',
  category: 'Trigonometry',
  syntax: ['asec(x)'],
  description: 'Calculate the inverse secant of a value.',
  examples: ['asec(0.5)', 'asec(sec(0.5))', 'asec(2)'],
  seealso: ['acos', 'acot', 'acsc']
};

var asechDocs = {
  name: 'asech',
  category: 'Trigonometry',
  syntax: ['asech(x)'],
  description: 'Calculate the inverse secant of a value.',
  examples: ['asech(0.5)'],
  seealso: ['acsch', 'acoth']
};

var asinDocs = {
  name: 'asin',
  category: 'Trigonometry',
  syntax: ['asin(x)'],
  description: 'Compute the inverse sine of a value in radians.',
  examples: ['asin(0.5)', 'asin(sin(0.5))'],
  seealso: ['sin', 'acos', 'atan']
};

var asinhDocs = {
  name: 'asinh',
  category: 'Trigonometry',
  syntax: ['asinh(x)'],
  description: 'Calculate the hyperbolic arcsine of a value, defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.',
  examples: ['asinh(0.5)'],
  seealso: ['acosh', 'atanh']
};

var atanDocs = {
  name: 'atan',
  category: 'Trigonometry',
  syntax: ['atan(x)'],
  description: 'Compute the inverse tangent of a value in radians.',
  examples: ['atan(0.5)', 'atan(tan(0.5))'],
  seealso: ['tan', 'acos', 'asin']
};

var atan2Docs = {
  name: 'atan2',
  category: 'Trigonometry',
  syntax: ['atan2(y, x)'],
  description: 'Computes the principal value of the arc tangent of y/x in radians.',
  examples: ['atan2(2, 2) / pi', 'angle = 60 deg in rad', 'x = cos(angle)', 'y = sin(angle)', 'atan2(y, x)'],
  seealso: ['sin', 'cos', 'tan']
};

var atanhDocs = {
  name: 'atanh',
  category: 'Trigonometry',
  syntax: ['atanh(x)'],
  description: 'Calculate the hyperbolic arctangent of a value, defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.',
  examples: ['atanh(0.5)'],
  seealso: ['acosh', 'asinh']
};

var cosDocs = {
  name: 'cos',
  category: 'Trigonometry',
  syntax: ['cos(x)'],
  description: 'Compute the cosine of x in radians.',
  examples: ['cos(2)', 'cos(pi / 4) ^ 2', 'cos(180 deg)', 'cos(60 deg)', 'sin(0.2)^2 + cos(0.2)^2'],
  seealso: ['acos', 'sin', 'tan']
};

var coshDocs = {
  name: 'cosh',
  category: 'Trigonometry',
  syntax: ['cosh(x)'],
  description: 'Compute the hyperbolic cosine of x in radians.',
  examples: ['cosh(0.5)'],
  seealso: ['sinh', 'tanh', 'coth']
};

var cotDocs = {
  name: 'cot',
  category: 'Trigonometry',
  syntax: ['cot(x)'],
  description: 'Compute the cotangent of x in radians. Defined as 1/tan(x)',
  examples: ['cot(2)', '1 / tan(2)'],
  seealso: ['sec', 'csc', 'tan']
};

var cothDocs = {
  name: 'coth',
  category: 'Trigonometry',
  syntax: ['coth(x)'],
  description: 'Compute the hyperbolic cotangent of x in radians.',
  examples: ['coth(2)', '1 / tanh(2)'],
  seealso: ['sech', 'csch', 'tanh']
};

var cscDocs = {
  name: 'csc',
  category: 'Trigonometry',
  syntax: ['csc(x)'],
  description: 'Compute the cosecant of x in radians. Defined as 1/sin(x)',
  examples: ['csc(2)', '1 / sin(2)'],
  seealso: ['sec', 'cot', 'sin']
};

var cschDocs = {
  name: 'csch',
  category: 'Trigonometry',
  syntax: ['csch(x)'],
  description: 'Compute the hyperbolic cosecant of x in radians. Defined as 1/sinh(x)',
  examples: ['csch(2)', '1 / sinh(2)'],
  seealso: ['sech', 'coth', 'sinh']
};

var secDocs = {
  name: 'sec',
  category: 'Trigonometry',
  syntax: ['sec(x)'],
  description: 'Compute the secant of x in radians. Defined as 1/cos(x)',
  examples: ['sec(2)', '1 / cos(2)'],
  seealso: ['cot', 'csc', 'cos']
};

var sechDocs = {
  name: 'sech',
  category: 'Trigonometry',
  syntax: ['sech(x)'],
  description: 'Compute the hyperbolic secant of x in radians. Defined as 1/cosh(x)',
  examples: ['sech(2)', '1 / cosh(2)'],
  seealso: ['coth', 'csch', 'cosh']
};

var sinDocs = {
  name: 'sin',
  category: 'Trigonometry',
  syntax: ['sin(x)'],
  description: 'Compute the sine of x in radians.',
  examples: ['sin(2)', 'sin(pi / 4) ^ 2', 'sin(90 deg)', 'sin(30 deg)', 'sin(0.2)^2 + cos(0.2)^2'],
  seealso: ['asin', 'cos', 'tan']
};

var sinhDocs = {
  name: 'sinh',
  category: 'Trigonometry',
  syntax: ['sinh(x)'],
  description: 'Compute the hyperbolic sine of x in radians.',
  examples: ['sinh(0.5)'],
  seealso: ['cosh', 'tanh']
};

var tanDocs = {
  name: 'tan',
  category: 'Trigonometry',
  syntax: ['tan(x)'],
  description: 'Compute the tangent of x in radians.',
  examples: ['tan(0.5)', 'sin(0.5) / cos(0.5)', 'tan(pi / 4)', 'tan(45 deg)'],
  seealso: ['atan', 'sin', 'cos']
};

var tanhDocs = {
  name: 'tanh',
  category: 'Trigonometry',
  syntax: ['tanh(x)'],
  description: 'Compute the hyperbolic tangent of x in radians.',
  examples: ['tanh(0.5)', 'sinh(0.5) / cosh(0.5)'],
  seealso: ['sinh', 'cosh']
};

var toDocs = {
  name: 'to',
  category: 'Units',
  syntax: ['x to unit', 'to(x, unit)'],
  description: 'Change the unit of a value.',
  examples: ['5 inch to cm', '3.2kg to g', '16 bytes in bits'],
  seealso: []
};

var binDocs = {
  name: 'bin',
  category: 'Utils',
  syntax: ['bin(value)'],
  description: 'Format a number as binary',
  examples: ['bin(2)'],
  seealso: ['oct', 'hex']
};

var cloneDocs = {
  name: 'clone',
  category: 'Utils',
  syntax: ['clone(x)'],
  description: 'Clone a variable. Creates a copy of primitive variables,and a deep copy of matrices',
  examples: ['clone(3.5)', 'clone(2 - 4i)', 'clone(45 deg)', 'clone([1, 2; 3, 4])', 'clone("hello world")'],
  seealso: []
};

var formatDocs = {
  name: 'format',
  category: 'Utils',
  syntax: ['format(value)', 'format(value, precision)'],
  description: 'Format a value of any type as string.',
  examples: ['format(2.3)', 'format(3 - 4i)', 'format([])', 'format(pi, 3)'],
  seealso: ['print']
};

var hasNumericValueDocs = {
  name: 'hasNumericValue',
  category: 'Utils',
  syntax: ['hasNumericValue(x)'],
  description: 'Test whether a value is an numeric value. ' + 'In case of a string, true is returned if the string contains a numeric value.',
  examples: ['hasNumericValue(2)', 'hasNumericValue("2")', 'isNumeric("2")', 'hasNumericValue(0)', 'hasNumericValue(bignumber(500))', 'hasNumericValue(fraction(0.125))', 'hasNumericValue(2 + 3i)', 'hasNumericValue([2.3, "foo", false])'],
  seealso: ['isInteger', 'isZero', 'isNegative', 'isPositive', 'isNaN', 'isNumeric']
};

var hexDocs = {
  name: 'hex',
  category: 'Utils',
  syntax: ['hex(value)'],
  description: 'Format a number as hexadecimal',
  examples: ['hex(240)'],
  seealso: ['bin', 'oct']
};

var isIntegerDocs = {
  name: 'isInteger',
  category: 'Utils',
  syntax: ['isInteger(x)'],
  description: 'Test whether a value is an integer number.',
  examples: ['isInteger(2)', 'isInteger(3.5)', 'isInteger([3, 0.5, -2])'],
  seealso: ['isNegative', 'isNumeric', 'isPositive', 'isZero']
};

var isNaNDocs = {
  name: 'isNaN',
  category: 'Utils',
  syntax: ['isNaN(x)'],
  description: 'Test whether a value is NaN (not a number)',
  examples: ['isNaN(2)', 'isNaN(0 / 0)', 'isNaN(NaN)', 'isNaN(Infinity)'],
  seealso: ['isNegative', 'isNumeric', 'isPositive', 'isZero']
};

var isNegativeDocs = {
  name: 'isNegative',
  category: 'Utils',
  syntax: ['isNegative(x)'],
  description: 'Test whether a value is negative: smaller than zero.',
  examples: ['isNegative(2)', 'isNegative(0)', 'isNegative(-4)', 'isNegative([3, 0.5, -2])'],
  seealso: ['isInteger', 'isNumeric', 'isPositive', 'isZero']
};

var isNumericDocs = {
  name: 'isNumeric',
  category: 'Utils',
  syntax: ['isNumeric(x)'],
  description: 'Test whether a value is a numeric value. ' + 'Returns true when the input is a number, BigNumber, Fraction, or boolean.',
  examples: ['isNumeric(2)', 'isNumeric("2")', 'hasNumericValue("2")', 'isNumeric(0)', 'isNumeric(bignumber(500))', 'isNumeric(fraction(0.125))', 'isNumeric(2 + 3i)', 'isNumeric([2.3, "foo", false])'],
  seealso: ['isInteger', 'isZero', 'isNegative', 'isPositive', 'isNaN', 'hasNumericValue']
};

var isPositiveDocs = {
  name: 'isPositive',
  category: 'Utils',
  syntax: ['isPositive(x)'],
  description: 'Test whether a value is positive: larger than zero.',
  examples: ['isPositive(2)', 'isPositive(0)', 'isPositive(-4)', 'isPositive([3, 0.5, -2])'],
  seealso: ['isInteger', 'isNumeric', 'isNegative', 'isZero']
};

var isPrimeDocs = {
  name: 'isPrime',
  category: 'Utils',
  syntax: ['isPrime(x)'],
  description: 'Test whether a value is prime: has no divisors other than itself and one.',
  examples: ['isPrime(3)', 'isPrime(-2)', 'isPrime([2, 17, 100])'],
  seealso: ['isInteger', 'isNumeric', 'isNegative', 'isZero']
};

var isZeroDocs = {
  name: 'isZero',
  category: 'Utils',
  syntax: ['isZero(x)'],
  description: 'Test whether a value is zero.',
  examples: ['isZero(2)', 'isZero(0)', 'isZero(-4)', 'isZero([3, 0, -2, 0])'],
  seealso: ['isInteger', 'isNumeric', 'isNegative', 'isPositive']
};

var numericDocs = {
  name: 'numeric',
  category: 'Utils',
  syntax: ['numeric(x)'],
  description: 'Convert a numeric input to a specific numeric type: number, BigNumber, bigint, or Fraction.',
  examples: ['numeric("4")', 'numeric("4", "number")', 'numeric("4", "bigint")', 'numeric("4", "BigNumber")', 'numeric("4", "Fraction")', 'numeric(4, "Fraction")', 'numeric(fraction(2, 5), "number")'],
  seealso: ['number', 'bigint', 'fraction', 'bignumber', 'string', 'format']
};

var octDocs = {
  name: 'oct',
  category: 'Utils',
  syntax: ['oct(value)'],
  description: 'Format a number as octal',
  examples: ['oct(56)'],
  seealso: ['bin', 'hex']
};

var printDocs = {
  name: 'print',
  category: 'Utils',
  syntax: ['print(template, values)', 'print(template, values, precision)'],
  description: 'Interpolate values into a string template.',
  examples: ['print("Lucy is $age years old", {age: 5})', 'print("The value of pi is $pi", {pi: pi}, 3)', 'print("Hello, $user.name!", {user: {name: "John"}})', 'print("Values: $1, $2, $3", [6, 9, 4])'],
  seealso: ['format']
};

var typeOfDocs = {
  name: 'typeOf',
  category: 'Utils',
  syntax: ['typeOf(x)'],
  description: 'Get the type of a variable.',
  examples: ['typeOf(3.5)', 'typeOf(2 - 4i)', 'typeOf(45 deg)', 'typeOf("hello world")'],
  seealso: ['getMatrixDataType']
};

var solveODEDocs = {
  name: 'solveODE',
  category: 'Numeric',
  syntax: ['solveODE(func, tspan, y0)', 'solveODE(func, tspan, y0, options)'],
  description: 'Numerical Integration of Ordinary Differential Equations.',
  examples: ['f(t,y) = y', 'tspan = [0, 4]', 'solveODE(f, tspan, 1)', 'solveODE(f, tspan, [1, 2])', 'solveODE(f, tspan, 1, { method:"RK23", maxStep:0.1 })'],
  seealso: ['derivative', 'simplifyCore']
};

var embeddedDocs = {
  // construction functions
  bignumber: bignumberDocs,
  bigint: bigintDocs,
  boolean: booleanDocs,
  complex: complexDocs,
  createUnit: createUnitDocs,
  fraction: fractionDocs,
  index: indexDocs,
  matrix: matrixDocs,
  number: numberDocs,
  sparse: sparseDocs,
  splitUnit: splitUnitDocs,
  string: stringDocs,
  unit: unitDocs,
  // constants
  e: eDocs,
  E: eDocs,
  false: falseDocs,
  i: iDocs,
  Infinity: InfinityDocs,
  LN2: LN2Docs,
  LN10: LN10Docs,
  LOG2E: LOG2EDocs,
  LOG10E: LOG10EDocs,
  NaN: NaNDocs,
  null: nullDocs,
  pi: piDocs,
  PI: piDocs,
  phi: phiDocs,
  SQRT1_2: SQRT12Docs,
  SQRT2: SQRT2Docs,
  tau: tauDocs,
  true: trueDocs,
  version: versionDocs,
  // physical constants
  // TODO: more detailed docs for physical constants
  speedOfLight: {
    description: 'Speed of light in vacuum',
    examples: ['speedOfLight']
  },
  gravitationConstant: {
    description: 'Newtonian constant of gravitation',
    examples: ['gravitationConstant']
  },
  planckConstant: {
    description: 'Planck constant',
    examples: ['planckConstant']
  },
  reducedPlanckConstant: {
    description: 'Reduced Planck constant',
    examples: ['reducedPlanckConstant']
  },
  magneticConstant: {
    description: 'Magnetic constant (vacuum permeability)',
    examples: ['magneticConstant']
  },
  electricConstant: {
    description: 'Electric constant (vacuum permeability)',
    examples: ['electricConstant']
  },
  vacuumImpedance: {
    description: 'Characteristic impedance of vacuum',
    examples: ['vacuumImpedance']
  },
  coulomb: {
    description: 'Coulomb\'s constant',
    examples: ['coulomb']
  },
  elementaryCharge: {
    description: 'Elementary charge',
    examples: ['elementaryCharge']
  },
  bohrMagneton: {
    description: 'Borh magneton',
    examples: ['bohrMagneton']
  },
  conductanceQuantum: {
    description: 'Conductance quantum',
    examples: ['conductanceQuantum']
  },
  inverseConductanceQuantum: {
    description: 'Inverse conductance quantum',
    examples: ['inverseConductanceQuantum']
  },
  // josephson: {description: 'Josephson constant', examples: ['josephson']},
  magneticFluxQuantum: {
    description: 'Magnetic flux quantum',
    examples: ['magneticFluxQuantum']
  },
  nuclearMagneton: {
    description: 'Nuclear magneton',
    examples: ['nuclearMagneton']
  },
  klitzing: {
    description: 'Von Klitzing constant',
    examples: ['klitzing']
  },
  bohrRadius: {
    description: 'Borh radius',
    examples: ['bohrRadius']
  },
  classicalElectronRadius: {
    description: 'Classical electron radius',
    examples: ['classicalElectronRadius']
  },
  electronMass: {
    description: 'Electron mass',
    examples: ['electronMass']
  },
  fermiCoupling: {
    description: 'Fermi coupling constant',
    examples: ['fermiCoupling']
  },
  fineStructure: {
    description: 'Fine-structure constant',
    examples: ['fineStructure']
  },
  hartreeEnergy: {
    description: 'Hartree energy',
    examples: ['hartreeEnergy']
  },
  protonMass: {
    description: 'Proton mass',
    examples: ['protonMass']
  },
  deuteronMass: {
    description: 'Deuteron Mass',
    examples: ['deuteronMass']
  },
  neutronMass: {
    description: 'Neutron mass',
    examples: ['neutronMass']
  },
  quantumOfCirculation: {
    description: 'Quantum of circulation',
    examples: ['quantumOfCirculation']
  },
  rydberg: {
    description: 'Rydberg constant',
    examples: ['rydberg']
  },
  thomsonCrossSection: {
    description: 'Thomson cross section',
    examples: ['thomsonCrossSection']
  },
  weakMixingAngle: {
    description: 'Weak mixing angle',
    examples: ['weakMixingAngle']
  },
  efimovFactor: {
    description: 'Efimov factor',
    examples: ['efimovFactor']
  },
  atomicMass: {
    description: 'Atomic mass constant',
    examples: ['atomicMass']
  },
  avogadro: {
    description: 'Avogadro\'s number',
    examples: ['avogadro']
  },
  boltzmann: {
    description: 'Boltzmann constant',
    examples: ['boltzmann']
  },
  faraday: {
    description: 'Faraday constant',
    examples: ['faraday']
  },
  firstRadiation: {
    description: 'First radiation constant',
    examples: ['firstRadiation']
  },
  loschmidt: {
    description: 'Loschmidt constant at T=273.15 K and p=101.325 kPa',
    examples: ['loschmidt']
  },
  gasConstant: {
    description: 'Gas constant',
    examples: ['gasConstant']
  },
  molarPlanckConstant: {
    description: 'Molar Planck constant',
    examples: ['molarPlanckConstant']
  },
  molarVolume: {
    description: 'Molar volume of an ideal gas at T=273.15 K and p=101.325 kPa',
    examples: ['molarVolume']
  },
  sackurTetrode: {
    description: 'Sackur-Tetrode constant at T=1 K and p=101.325 kPa',
    examples: ['sackurTetrode']
  },
  secondRadiation: {
    description: 'Second radiation constant',
    examples: ['secondRadiation']
  },
  stefanBoltzmann: {
    description: 'Stefan-Boltzmann constant',
    examples: ['stefanBoltzmann']
  },
  wienDisplacement: {
    description: 'Wien displacement law constant',
    examples: ['wienDisplacement']
  },
  // spectralRadiance: {description: 'First radiation constant for spectral radiance', examples: ['spectralRadiance']},

  molarMass: {
    description: 'Molar mass constant',
    examples: ['molarMass']
  },
  molarMassC12: {
    description: 'Molar mass constant of carbon-12',
    examples: ['molarMassC12']
  },
  gravity: {
    description: 'Standard acceleration of gravity (standard acceleration of free-fall on Earth)',
    examples: ['gravity']
  },
  planckLength: {
    description: 'Planck length',
    examples: ['planckLength']
  },
  planckMass: {
    description: 'Planck mass',
    examples: ['planckMass']
  },
  planckTime: {
    description: 'Planck time',
    examples: ['planckTime']
  },
  planckCharge: {
    description: 'Planck charge',
    examples: ['planckCharge']
  },
  planckTemperature: {
    description: 'Planck temperature',
    examples: ['planckTemperature']
  },
  // functions - algebra
  derivative: derivativeDocs,
  lsolve: lsolveDocs,
  lsolveAll: lsolveAllDocs,
  lup: lupDocs,
  lusolve: lusolveDocs,
  leafCount: leafCountDocs,
  polynomialRoot: polynomialRootDocs,
  resolve: resolveDocs,
  simplify: simplifyDocs,
  simplifyConstant: simplifyConstantDocs,
  simplifyCore: simplifyCoreDocs,
  symbolicEqual: symbolicEqualDocs,
  rationalize: rationalizeDocs,
  slu: sluDocs,
  usolve: usolveDocs,
  usolveAll: usolveAllDocs,
  qr: qrDocs,
  // functions - arithmetic
  abs: absDocs,
  add: addDocs,
  cbrt: cbrtDocs,
  ceil: ceilDocs,
  cube: cubeDocs,
  divide: divideDocs,
  dotDivide: dotDivideDocs,
  dotMultiply: dotMultiplyDocs,
  dotPow: dotPowDocs,
  exp: expDocs,
  expm: expmDocs,
  expm1: expm1Docs,
  fix: fixDocs,
  floor: floorDocs,
  gcd: gcdDocs,
  hypot: hypotDocs,
  lcm: lcmDocs,
  log: logDocs,
  log2: log2Docs,
  log1p: log1pDocs,
  log10: log10Docs,
  mod: modDocs,
  multiply: multiplyDocs,
  norm: normDocs,
  nthRoot: nthRootDocs,
  nthRoots: nthRootsDocs,
  pow: powDocs,
  round: roundDocs,
  sign: signDocs,
  sqrt: sqrtDocs,
  sqrtm: sqrtmDocs,
  square: squareDocs,
  subtract: subtractDocs,
  unaryMinus: unaryMinusDocs,
  unaryPlus: unaryPlusDocs,
  xgcd: xgcdDocs,
  invmod: invmodDocs,
  // functions - bitwise
  bitAnd: bitAndDocs,
  bitNot: bitNotDocs,
  bitOr: bitOrDocs,
  bitXor: bitXorDocs,
  leftShift: leftShiftDocs,
  rightArithShift: rightArithShiftDocs,
  rightLogShift: rightLogShiftDocs,
  // functions - combinatorics
  bellNumbers: bellNumbersDocs,
  catalan: catalanDocs,
  composition: compositionDocs,
  stirlingS2: stirlingS2Docs,
  // functions - core
  config: configDocs,
  import: importDocs,
  typed: typedDocs,
  // functions - complex
  arg: argDocs,
  conj: conjDocs,
  re: reDocs,
  im: imDocs,
  // functions - expression
  evaluate: evaluateDocs,
  help: helpDocs,
  // functions - geometry
  distance: distanceDocs,
  intersect: intersectDocs,
  // functions - logical
  and: andDocs,
  not: notDocs,
  or: orDocs,
  xor: xorDocs,
  // functions - matrix
  concat: concatDocs,
  count: countDocs,
  cross: crossDocs,
  column: columnDocs,
  ctranspose: ctransposeDocs,
  det: detDocs,
  diag: diagDocs,
  diff: diffDocs,
  dot: dotDocs,
  getMatrixDataType: getMatrixDataTypeDocs,
  identity: identityDocs,
  filter: filterDocs,
  flatten: flattenDocs,
  forEach: forEachDocs,
  inv: invDocs,
  pinv: pinvDocs,
  eigs: eigsDocs,
  kron: kronDocs,
  matrixFromFunction: matrixFromFunctionDocs,
  matrixFromRows: matrixFromRowsDocs,
  matrixFromColumns: matrixFromColumnsDocs,
  map: mapDocs,
  ones: onesDocs,
  partitionSelect: partitionSelectDocs,
  range: rangeDocs,
  resize: resizeDocs,
  reshape: reshapeDocs,
  rotate: rotateDocs,
  rotationMatrix: rotationMatrixDocs,
  row: rowDocs,
  size: sizeDocs,
  sort: sortDocs,
  squeeze: squeezeDocs,
  subset: subsetDocs,
  trace: traceDocs,
  transpose: transposeDocs,
  zeros: zerosDocs,
  fft: fftDocs,
  ifft: ifftDocs,
  sylvester: sylvesterDocs,
  schur: schurDocs,
  lyap: lyapDocs,
  // functions - numeric
  solveODE: solveODEDocs,
  // functions - probability
  combinations: combinationsDocs,
  combinationsWithRep: combinationsWithRepDocs,
  // distribution: distributionDocs,
  factorial: factorialDocs,
  gamma: gammaDocs,
  kldivergence: kldivergenceDocs,
  lgamma: lgammaDocs,
  multinomial: multinomialDocs,
  permutations: permutationsDocs,
  pickRandom: pickRandomDocs,
  random: randomDocs,
  randomInt: randomIntDocs,
  // functions - relational
  compare: compareDocs,
  compareNatural: compareNaturalDocs,
  compareText: compareTextDocs,
  deepEqual: deepEqualDocs,
  equal: equalDocs,
  equalText: equalTextDocs,
  larger: largerDocs,
  largerEq: largerEqDocs,
  smaller: smallerDocs,
  smallerEq: smallerEqDocs,
  unequal: unequalDocs,
  // functions - set
  setCartesian: setCartesianDocs,
  setDifference: setDifferenceDocs,
  setDistinct: setDistinctDocs,
  setIntersect: setIntersectDocs,
  setIsSubset: setIsSubsetDocs,
  setMultiplicity: setMultiplicityDocs,
  setPowerset: setPowersetDocs,
  setSize: setSizeDocs,
  setSymDifference: setSymDifferenceDocs,
  setUnion: setUnionDocs,
  // functions - signal
  zpk2tf: zpk2tfDocs,
  freqz: freqzDocs,
  // functions - special
  erf: erfDocs,
  zeta: zetaDocs,
  // functions - statistics
  cumsum: cumSumDocs,
  mad: madDocs,
  max: maxDocs,
  mean: meanDocs,
  median: medianDocs,
  min: minDocs,
  mode: modeDocs,
  prod: prodDocs,
  quantileSeq: quantileSeqDocs,
  std: stdDocs,
  sum: sumDocs,
  variance: varianceDocs,
  corr: corrDocs,
  // functions - trigonometry
  acos: acosDocs,
  acosh: acoshDocs,
  acot: acotDocs,
  acoth: acothDocs,
  acsc: acscDocs,
  acsch: acschDocs,
  asec: asecDocs,
  asech: asechDocs,
  asin: asinDocs,
  asinh: asinhDocs,
  atan: atanDocs,
  atanh: atanhDocs,
  atan2: atan2Docs,
  cos: cosDocs,
  cosh: coshDocs,
  cot: cotDocs,
  coth: cothDocs,
  csc: cscDocs,
  csch: cschDocs,
  sec: secDocs,
  sech: sechDocs,
  sin: sinDocs,
  sinh: sinhDocs,
  tan: tanDocs,
  tanh: tanhDocs,
  // functions - units
  to: toDocs,
  // functions - utils
  clone: cloneDocs,
  format: formatDocs,
  bin: binDocs,
  oct: octDocs,
  hex: hexDocs,
  isNaN: isNaNDocs,
  isInteger: isIntegerDocs,
  isNegative: isNegativeDocs,
  isNumeric: isNumericDocs,
  hasNumericValue: hasNumericValueDocs,
  isPositive: isPositiveDocs,
  isPrime: isPrimeDocs,
  isZero: isZeroDocs,
  print: printDocs,
  typeOf: typeOfDocs,
  numeric: numericDocs
};

var name$1a = 'help';
var dependencies$1a = ['typed', 'mathWithTransform', 'Help'];
var createHelp = /* #__PURE__ */factory(name$1a, dependencies$1a, _ref => {
  var {
    typed,
    mathWithTransform,
    Help
  } = _ref;
  /**
   * Retrieve help on a function or data type.
   * Help files are retrieved from the embedded documentation in math.docs.
   *
   * Syntax:
   *
   *    math.help(search)
   *
   * Examples:
   *
   *    console.log(math.help('sin').toString())
   *    console.log(math.help(math.add).toString())
   *    console.log(math.help(math.add).toJSON())
   *
   * @param {Function | string | Object} search   A function or function name
   *                                              for which to get help
   * @return {Help} A help object
   */
  return typed(name$1a, {
    any: function any(search) {
      var prop;
      var searchName = search;
      if (typeof search !== 'string') {
        for (prop in mathWithTransform) {
          // search in functions and constants
          if (hasOwnProperty(mathWithTransform, prop) && search === mathWithTransform[prop]) {
            searchName = prop;
            break;
          }
        }

        /* TODO: implement help for data types
         if (!text) {
         // search data type
         for (prop in math.type) {
         if (hasOwnProperty(math, prop)) {
         if (search === math.type[prop]) {
         text = prop
         break
         }
         }
         }
         }
         */
      }
      var doc = getSafeProperty(embeddedDocs, searchName);
      if (!doc) {
        var searchText = typeof searchName === 'function' ? searchName.name : searchName;
        throw new Error('No documentation found on "' + searchText + '"');
      }
      return new Help(doc);
    }
  });
});

var name$19 = 'chain';
var dependencies$19 = ['typed', 'Chain'];
var createChain = /* #__PURE__ */factory(name$19, dependencies$19, _ref => {
  var {
    typed,
    Chain
  } = _ref;
  /**
   * Wrap any value in a chain, allowing to perform chained operations on
   * the value.
   *
   * All methods available in the math.js library can be called upon the chain,
   * and then will be evaluated with the value itself as first argument.
   * The chain can be closed by executing `chain.done()`, which returns
   * the final value.
   *
   * The chain has a number of special functions:
   *
   * - `done()`     Finalize the chain and return the chain's value.
   * - `valueOf()`  The same as `done()`
   * - `toString()` Executes `math.format()` onto the chain's value, returning
   *                a string representation of the value.
   *
   * Syntax:
   *
   *    math.chain(value)
   *
   * Examples:
   *
   *     math.chain(3)
   *         .add(4)
   *         .subtract(2)
   *         .done()     // 5
   *
   *     math.chain( [[1, 2], [3, 4]] )
   *         .subset(math.index(0, 0), 8)
   *         .multiply(3)
   *         .done()     // [[24, 6], [9, 12]]
   *
   * @param {*} [value]   A value of any type on which to start a chained operation.
   * @return {math.Chain} The created chain
   */
  return typed(name$19, {
    '': function _() {
      return new Chain();
    },
    any: function any(value) {
      return new Chain(value);
    }
  });
});

var name$18 = 'det';
var dependencies$18 = ['typed', 'matrix', 'subtractScalar', 'multiply', 'divideScalar', 'isZero', 'unaryMinus'];
var createDet = /* #__PURE__ */factory(name$18, dependencies$18, _ref => {
  var {
    typed,
    matrix,
    subtractScalar,
    multiply,
    divideScalar,
    isZero,
    unaryMinus
  } = _ref;
  /**
   * Calculate the determinant of a matrix.
   *
   * Syntax:
   *
   *    math.det(x)
   *
   * Examples:
   *
   *    math.det([[1, 2], [3, 4]]) // returns -2
   *
   *    const A = [
   *      [-2, 2, 3],
   *      [-1, 1, 3],
   *      [2, 0, -1]
   *    ]
   *    math.det(A) // returns 6
   *
   * See also:
   *
   *    inv
   *
   * @param {Array | Matrix} x  A matrix
   * @return {number} The determinant of `x`
   */
  return typed(name$18, {
    any: function any(x) {
      return clone$2(x);
    },
    'Array | Matrix': function det(x) {
      var size;
      if (isMatrix(x)) {
        size = x.size();
      } else if (Array.isArray(x)) {
        x = matrix(x);
        size = x.size();
      } else {
        // a scalar
        size = [];
      }
      switch (size.length) {
        case 0:
          // scalar
          return clone$2(x);
        case 1:
          // vector
          if (size[0] === 1) {
            return clone$2(x.valueOf()[0]);
          }
          if (size[0] === 0) {
            return 1; // det of an empty matrix is per definition 1
          } else {
            throw new RangeError('Matrix must be square ' + '(size: ' + format(size) + ')');
          }
        case 2:
          {
            // two-dimensional array
            var rows = size[0];
            var cols = size[1];
            if (rows === cols) {
              return _det(x.clone().valueOf(), rows);
            }
            if (cols === 0) {
              return 1; // det of an empty matrix is per definition 1
            } else {
              throw new RangeError('Matrix must be square ' + '(size: ' + format(size) + ')');
            }
          }
        default:
          // multi dimensional array
          throw new RangeError('Matrix must be two dimensional ' + '(size: ' + format(size) + ')');
      }
    }
  });

  /**
   * Calculate the determinant of a matrix
   * @param {Array[]} matrix  A square, two dimensional matrix
   * @param {number} rows     Number of rows of the matrix (zero-based)
   * @param {number} cols     Number of columns of the matrix (zero-based)
   * @returns {number} det
   * @private
   */
  function _det(matrix, rows, cols) {
    if (rows === 1) {
      // this is a 1 x 1 matrix
      return clone$2(matrix[0][0]);
    } else if (rows === 2) {
      // this is a 2 x 2 matrix
      // the determinant of [a11,a12;a21,a22] is det = a11*a22-a21*a12
      return subtractScalar(multiply(matrix[0][0], matrix[1][1]), multiply(matrix[1][0], matrix[0][1]));
    } else {
      // Bareiss algorithm
      // this algorithm have same complexity as LUP decomposition (O(n^3))
      // but it preserve precision of floating point more relative to the LUP decomposition
      var negated = false;
      var rowIndices = new Array(rows).fill(0).map((_, i) => i); // matrix index of row i
      for (var k = 0; k < rows; k++) {
        var k_ = rowIndices[k];
        if (isZero(matrix[k_][k])) {
          var _k = void 0;
          for (_k = k + 1; _k < rows; _k++) {
            if (!isZero(matrix[rowIndices[_k]][k])) {
              k_ = rowIndices[_k];
              rowIndices[_k] = rowIndices[k];
              rowIndices[k] = k_;
              negated = !negated;
              break;
            }
          }
          if (_k === rows) return matrix[k_][k]; // some zero of the type
        }
        var piv = matrix[k_][k];
        var piv_ = k === 0 ? 1 : matrix[rowIndices[k - 1]][k - 1];
        for (var i = k + 1; i < rows; i++) {
          var i_ = rowIndices[i];
          for (var j = k + 1; j < rows; j++) {
            matrix[i_][j] = divideScalar(subtractScalar(multiply(matrix[i_][j], piv), multiply(matrix[i_][k], matrix[k_][j])), piv_);
          }
        }
      }
      var det = matrix[rowIndices[rows - 1]][rows - 1];
      return negated ? unaryMinus(det) : det;
    }
  }
});

var name$17 = 'inv';
var dependencies$17 = ['typed', 'matrix', 'divideScalar', 'addScalar', 'multiply', 'unaryMinus', 'det', 'identity', 'abs'];
var createInv = /* #__PURE__ */factory(name$17, dependencies$17, _ref => {
  var {
    typed,
    matrix,
    divideScalar,
    addScalar,
    multiply,
    unaryMinus,
    det,
    identity,
    abs
  } = _ref;
  /**
   * Calculate the inverse of a square matrix.
   *
   * Syntax:
   *
   *     math.inv(x)
   *
   * Examples:
   *
   *     math.inv([[1, 2], [3, 4]])  // returns [[-2, 1], [1.5, -0.5]]
   *     math.inv(4)                 // returns 0.25
   *     1 / 4                       // returns 0.25
   *
   * See also:
   *
   *     det, transpose
   *
   * @param {number | Complex | Array | Matrix} x     Matrix to be inversed
   * @return {number | Complex | Array | Matrix} The inverse of `x`.
   */
  return typed(name$17, {
    'Array | Matrix': function ArrayMatrix(x) {
      var size = isMatrix(x) ? x.size() : arraySize(x);
      switch (size.length) {
        case 1:
          // vector
          if (size[0] === 1) {
            if (isMatrix(x)) {
              return matrix([divideScalar(1, x.valueOf()[0])]);
            } else {
              return [divideScalar(1, x[0])];
            }
          } else {
            throw new RangeError('Matrix must be square ' + '(size: ' + format(size) + ')');
          }
        case 2:
          // two dimensional array
          {
            var rows = size[0];
            var cols = size[1];
            if (rows === cols) {
              if (isMatrix(x)) {
                return matrix(_inv(x.valueOf(), rows, cols), x.storage());
              } else {
                // return an Array
                return _inv(x, rows, cols);
              }
            } else {
              throw new RangeError('Matrix must be square ' + '(size: ' + format(size) + ')');
            }
          }
        default:
          // multi dimensional array
          throw new RangeError('Matrix must be two dimensional ' + '(size: ' + format(size) + ')');
      }
    },
    any: function any(x) {
      // scalar
      return divideScalar(1, x); // FIXME: create a BigNumber one when configured for bignumbers
    }
  });

  /**
   * Calculate the inverse of a square matrix
   * @param {Array[]} mat     A square matrix
   * @param {number} rows     Number of rows
   * @param {number} cols     Number of columns, must equal rows
   * @return {Array[]} inv    Inverse matrix
   * @private
   */
  function _inv(mat, rows, cols) {
    var r, s, f, value, temp;
    if (rows === 1) {
      // this is a 1 x 1 matrix
      value = mat[0][0];
      if (value === 0) {
        throw Error('Cannot calculate inverse, determinant is zero');
      }
      return [[divideScalar(1, value)]];
    } else if (rows === 2) {
      // this is a 2 x 2 matrix
      var d = det(mat);
      if (d === 0) {
        throw Error('Cannot calculate inverse, determinant is zero');
      }
      return [[divideScalar(mat[1][1], d), divideScalar(unaryMinus(mat[0][1]), d)], [divideScalar(unaryMinus(mat[1][0]), d), divideScalar(mat[0][0], d)]];
    } else {
      // this is a matrix of 3 x 3 or larger
      // calculate inverse using gauss-jordan elimination
      //      https://en.wikipedia.org/wiki/Gaussian_elimination
      //      http://mathworld.wolfram.com/MatrixInverse.html
      //      http://math.uww.edu/~mcfarlat/inverse.htm

      // make a copy of the matrix (only the arrays, not of the elements)
      var A = mat.concat();
      for (r = 0; r < rows; r++) {
        A[r] = A[r].concat();
      }

      // create an identity matrix which in the end will contain the
      // matrix inverse
      var B = identity(rows).valueOf();

      // loop over all columns, and perform row reductions
      for (var c = 0; c < cols; c++) {
        // Pivoting: Swap row c with row r, where row r contains the largest element A[r][c]
        var ABig = abs(A[c][c]);
        var rBig = c;
        r = c + 1;
        while (r < rows) {
          if (abs(A[r][c]) > ABig) {
            ABig = abs(A[r][c]);
            rBig = r;
          }
          r++;
        }
        if (ABig === 0) {
          throw Error('Cannot calculate inverse, determinant is zero');
        }
        r = rBig;
        if (r !== c) {
          temp = A[c];
          A[c] = A[r];
          A[r] = temp;
          temp = B[c];
          B[c] = B[r];
          B[r] = temp;
        }

        // eliminate non-zero values on the other rows at column c
        var Ac = A[c];
        var Bc = B[c];
        for (r = 0; r < rows; r++) {
          var Ar = A[r];
          var Br = B[r];
          if (r !== c) {
            // eliminate value at column c and row r
            if (Ar[c] !== 0) {
              f = divideScalar(unaryMinus(Ar[c]), Ac[c]);

              // add (f * row c) to row r to eliminate the value
              // at column c
              for (s = c; s < cols; s++) {
                Ar[s] = addScalar(Ar[s], multiply(f, Ac[s]));
              }
              for (s = 0; s < cols; s++) {
                Br[s] = addScalar(Br[s], multiply(f, Bc[s]));
              }
            }
          } else {
            // normalize value at Acc to 1,
            // divide each value on row r with the value at Acc
            f = Ac[c];
            for (s = c; s < cols; s++) {
              Ar[s] = divideScalar(Ar[s], f);
            }
            for (s = 0; s < cols; s++) {
              Br[s] = divideScalar(Br[s], f);
            }
          }
        }
      }
      return B;
    }
  }
});

var name$16 = 'pinv';
var dependencies$16 = ['typed', 'matrix', 'inv', 'deepEqual', 'equal', 'dotDivide', 'dot', 'ctranspose', 'divideScalar', 'multiply', 'add', 'Complex'];
var createPinv = /* #__PURE__ */factory(name$16, dependencies$16, _ref => {
  var {
    typed,
    matrix,
    inv,
    deepEqual,
    equal,
    dotDivide,
    dot,
    ctranspose,
    divideScalar,
    multiply,
    add,
    Complex
  } = _ref;
  /**
   * Calculate the Moore–Penrose inverse of a matrix.
   *
   * Syntax:
   *
   *     math.pinv(x)
   *
   * Examples:
   *
   *     math.pinv([[1, 2], [3, 4]])          // returns [[-2, 1], [1.5, -0.5]]
   *     math.pinv([[1, 0], [0, 1], [0, 1]])  // returns [[1, 0, 0], [0, 0.5, 0.5]]
   *     math.pinv(4)                         // returns 0.25
   *
   * See also:
   *
   *     inv
   *
   * @param {number | Complex | Array | Matrix} x     Matrix to be inversed
   * @return {number | Complex | Array | Matrix} The inverse of `x`.
   */
  return typed(name$16, {
    'Array | Matrix': function ArrayMatrix(x) {
      var size = isMatrix(x) ? x.size() : arraySize(x);
      switch (size.length) {
        case 1:
          // vector
          if (_isZeros(x)) return ctranspose(x); // null vector
          if (size[0] === 1) {
            return inv(x); // invertible matrix
          } else {
            return dotDivide(ctranspose(x), dot(x, x));
          }
        case 2:
          // two dimensional array
          {
            if (_isZeros(x)) return ctranspose(x); // zero matrixx
            var rows = size[0];
            var cols = size[1];
            if (rows === cols) {
              try {
                return inv(x); // invertible matrix
              } catch (err) {
                if (err instanceof Error && err.message.match(/Cannot calculate inverse, determinant is zero/)) ; else {
                  throw err;
                }
              }
            }
            if (isMatrix(x)) {
              return matrix(_pinv(x.valueOf(), rows, cols), x.storage());
            } else {
              // return an Array
              return _pinv(x, rows, cols);
            }
          }
        default:
          // multi dimensional array
          throw new RangeError('Matrix must be two dimensional ' + '(size: ' + format(size) + ')');
      }
    },
    any: function any(x) {
      // scalar
      if (equal(x, 0)) return clone$2(x); // zero
      return divideScalar(1, x);
    }
  });

  /**
   * Calculate the Moore–Penrose inverse of a matrix
   * @param {Array[]} mat     A matrix
   * @param {number} rows     Number of rows
   * @param {number} cols     Number of columns
   * @return {Array[]} pinv    Pseudoinverse matrix
   * @private
   */
  function _pinv(mat, rows, cols) {
    var {
      C,
      F
    } = _rankFact(mat, rows, cols); // TODO: Use SVD instead (may improve precision)
    var Cpinv = multiply(inv(multiply(ctranspose(C), C)), ctranspose(C));
    var Fpinv = multiply(ctranspose(F), inv(multiply(F, ctranspose(F))));
    return multiply(Fpinv, Cpinv);
  }

  /**
   * Calculate the reduced row echelon form of a matrix
   *
   * Modified from https://rosettacode.org/wiki/Reduced_row_echelon_form
   *
   * @param {Array[]} mat     A matrix
   * @param {number} rows     Number of rows
   * @param {number} cols     Number of columns
   * @return {Array[]}        Reduced row echelon form
   * @private
   */
  function _rref(mat, rows, cols) {
    var M = clone$2(mat);
    var lead = 0;
    for (var r = 0; r < rows; r++) {
      if (cols <= lead) {
        return M;
      }
      var i = r;
      while (_isZero(M[i][lead])) {
        i++;
        if (rows === i) {
          i = r;
          lead++;
          if (cols === lead) {
            return M;
          }
        }
      }
      [M[i], M[r]] = [M[r], M[i]];
      var val = M[r][lead];
      for (var j = 0; j < cols; j++) {
        M[r][j] = dotDivide(M[r][j], val);
      }
      for (var _i = 0; _i < rows; _i++) {
        if (_i === r) continue;
        val = M[_i][lead];
        for (var _j = 0; _j < cols; _j++) {
          M[_i][_j] = add(M[_i][_j], multiply(-1, multiply(val, M[r][_j])));
        }
      }
      lead++;
    }
    return M;
  }

  /**
   * Calculate the rank factorization of a matrix
   *
   * @param {Array[]} mat                  A matrix (M)
   * @param {number} rows                  Number of rows
   * @param {number} cols                  Number of columns
   * @return {{C: Array, F: Array}}        rank factorization where M = C F
   * @private
   */
  function _rankFact(mat, rows, cols) {
    var rref = _rref(mat, rows, cols);
    var C = mat.map((_, i) => _.filter((_, j) => j < rows && !_isZero(dot(rref[j], rref[j]))));
    var F = rref.filter((_, i) => !_isZero(dot(rref[i], rref[i])));
    return {
      C,
      F
    };
  }
  function _isZero(x) {
    return equal(add(x, Complex(1, 1)), add(0, Complex(1, 1)));
  }
  function _isZeros(arr) {
    return deepEqual(add(arr, Complex(1, 1)), add(multiply(arr, 0), Complex(1, 1)));
  }
});

function createComplexEigs(_ref) {
  var {
    addScalar,
    subtract,
    flatten,
    multiply,
    multiplyScalar,
    divideScalar,
    sqrt,
    abs,
    bignumber,
    diag,
    size,
    reshape,
    inv,
    qr,
    usolve,
    usolveAll,
    equal,
    complex,
    larger,
    smaller,
    matrixFromColumns,
    dot
  } = _ref;
  /**
   * @param {number[][]} arr the matrix to find eigenvalues of
   * @param {number} N size of the matrix
   * @param {number|BigNumber} prec precision, anything lower will be considered zero
   * @param {'number'|'BigNumber'|'Complex'} type
   * @param {boolean} findVectors should we find eigenvectors?
   *
   * @returns {{ values: number[], vectors: number[][] }}
   */
  function complexEigs(arr, N, prec, type) {
    var findVectors = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
    // TODO check if any row/col are zero except the diagonal

    // make sure corresponding rows and columns have similar magnitude
    // important because of numerical stability
    // MODIFIES arr by side effect!
    var R = balance(arr, N, prec, type, findVectors);

    // R is the row transformation matrix
    // arr = A' = R A R^-1, A is the original matrix
    // (if findVectors is false, R is undefined)
    // (And so to return to original matrix: A = R^-1 arr R)

    // TODO if magnitudes of elements vary over many orders,
    // move greatest elements to the top left corner

    // using similarity transformations, reduce the matrix
    // to Hessenberg form (upper triangular plus one subdiagonal row)
    // updates the transformation matrix R with new row operationsq
    // MODIFIES arr by side effect!
    reduceToHessenberg(arr, N, prec, type, findVectors, R);
    // still true that original A = R^-1 arr R)

    // find eigenvalues
    var {
      values,
      C
    } = iterateUntilTriangular(arr, N, prec, type, findVectors);

    // values is the list of eigenvalues, C is the column
    // transformation matrix that transforms arr, the hessenberg
    // matrix, to upper triangular
    // (So U = C^-1 arr C and the relationship between current arr
    // and original A is unchanged.)

    if (findVectors) {
      var eigenvectors = findEigenvectors(arr, N, C, R, values, prec, type);
      return {
        values,
        eigenvectors
      };
    }
    return {
      values
    };
  }

  /**
   * @param {number[][]} arr
   * @param {number} N
   * @param {number} prec
   * @param {'number'|'BigNumber'|'Complex'} type
   * @returns {number[][]}
   */
  function balance(arr, N, prec, type, findVectors) {
    var big = type === 'BigNumber';
    var cplx = type === 'Complex';
    var realzero = big ? bignumber(0) : 0;
    var one = big ? bignumber(1) : cplx ? complex(1) : 1;
    var realone = big ? bignumber(1) : 1;

    // base of the floating-point arithmetic
    var radix = big ? bignumber(10) : 2;
    var radixSq = multiplyScalar(radix, radix);

    // the diagonal transformation matrix R
    var Rdiag;
    if (findVectors) {
      Rdiag = Array(N).fill(one);
    }

    // this isn't the only time we loop thru the matrix...
    var last = false;
    while (!last) {
      // ...haha I'm joking! unless...
      last = true;
      for (var i = 0; i < N; i++) {
        // compute the taxicab norm of i-th column and row
        // TODO optimize for complex numbers
        var colNorm = realzero;
        var rowNorm = realzero;
        for (var j = 0; j < N; j++) {
          if (i === j) continue;
          colNorm = addScalar(colNorm, abs(arr[j][i]));
          rowNorm = addScalar(rowNorm, abs(arr[i][j]));
        }
        if (!equal(colNorm, 0) && !equal(rowNorm, 0)) {
          // find integer power closest to balancing the matrix
          // (we want to scale only by integer powers of radix,
          // so that we don't lose any precision due to round-off)

          var f = realone;
          var c = colNorm;
          var rowDivRadix = divideScalar(rowNorm, radix);
          var rowMulRadix = multiplyScalar(rowNorm, radix);
          while (smaller(c, rowDivRadix)) {
            c = multiplyScalar(c, radixSq);
            f = multiplyScalar(f, radix);
          }
          while (larger(c, rowMulRadix)) {
            c = divideScalar(c, radixSq);
            f = divideScalar(f, radix);
          }

          // check whether balancing is needed
          // condition = (c + rowNorm) / f < 0.95 * (colNorm + rowNorm)
          var condition = smaller(divideScalar(addScalar(c, rowNorm), f), multiplyScalar(addScalar(colNorm, rowNorm), 0.95));

          // apply balancing similarity transformation
          if (condition) {
            // we should loop once again to check whether
            // another rebalancing is needed
            last = false;
            var g = divideScalar(1, f);
            for (var _j = 0; _j < N; _j++) {
              if (i === _j) {
                continue;
              }
              arr[i][_j] = multiplyScalar(arr[i][_j], g);
              arr[_j][i] = multiplyScalar(arr[_j][i], f);
            }

            // keep track of transformations
            if (findVectors) {
              Rdiag[i] = multiplyScalar(Rdiag[i], g);
            }
          }
        }
      }
    }

    // return the diagonal row transformation matrix
    return findVectors ? diag(Rdiag) : null;
  }

  /**
   * @param {number[][]} arr
   * @param {number} N
   * @param {number} prec
   * @param {'number'|'BigNumber'|'Complex'} type
   * @param {boolean} findVectors
   * @param {number[][]} R the row transformation matrix that will be modified
   */
  function reduceToHessenberg(arr, N, prec, type, findVectors, R) {
    var big = type === 'BigNumber';
    var cplx = type === 'Complex';
    var zero = big ? bignumber(0) : cplx ? complex(0) : 0;
    if (big) {
      prec = bignumber(prec);
    }
    for (var i = 0; i < N - 2; i++) {
      // Find the largest subdiag element in the i-th col

      var maxIndex = 0;
      var max = zero;
      for (var j = i + 1; j < N; j++) {
        var el = arr[j][i];
        if (smaller(abs(max), abs(el))) {
          max = el;
          maxIndex = j;
        }
      }

      // This col is pivoted, no need to do anything
      if (smaller(abs(max), prec)) {
        continue;
      }
      if (maxIndex !== i + 1) {
        // Interchange maxIndex-th and (i+1)-th row
        var tmp1 = arr[maxIndex];
        arr[maxIndex] = arr[i + 1];
        arr[i + 1] = tmp1;

        // Interchange maxIndex-th and (i+1)-th column
        for (var _j2 = 0; _j2 < N; _j2++) {
          var tmp2 = arr[_j2][maxIndex];
          arr[_j2][maxIndex] = arr[_j2][i + 1];
          arr[_j2][i + 1] = tmp2;
        }

        // keep track of transformations
        if (findVectors) {
          var tmp3 = R[maxIndex];
          R[maxIndex] = R[i + 1];
          R[i + 1] = tmp3;
        }
      }

      // Reduce following rows and columns
      for (var _j3 = i + 2; _j3 < N; _j3++) {
        var n = divideScalar(arr[_j3][i], max);
        if (n === 0) {
          continue;
        }

        // from j-th row subtract n-times (i+1)th row
        for (var k = 0; k < N; k++) {
          arr[_j3][k] = subtract(arr[_j3][k], multiplyScalar(n, arr[i + 1][k]));
        }

        // to (i+1)th column add n-times j-th column
        for (var _k = 0; _k < N; _k++) {
          arr[_k][i + 1] = addScalar(arr[_k][i + 1], multiplyScalar(n, arr[_k][_j3]));
        }

        // keep track of transformations
        if (findVectors) {
          for (var _k2 = 0; _k2 < N; _k2++) {
            R[_j3][_k2] = subtract(R[_j3][_k2], multiplyScalar(n, R[i + 1][_k2]));
          }
        }
      }
    }
    return R;
  }

  /**
   * @returns {{values: values, C: Matrix}}
   * @see Press, Wiliams: Numerical recipes in Fortran 77
   * @see https://en.wikipedia.org/wiki/QR_algorithm
   */
  function iterateUntilTriangular(A, N, prec, type, findVectors) {
    var big = type === 'BigNumber';
    var cplx = type === 'Complex';
    var one = big ? bignumber(1) : cplx ? complex(1) : 1;
    if (big) {
      prec = bignumber(prec);
    }

    // The Francis Algorithm
    // The core idea of this algorithm is that doing successive
    // A' = QtAQ transformations will eventually converge to block-
    // upper-triangular with diagonal blocks either 1x1 or 2x2.
    // The Q here is the one from the QR decomposition, A = QR.
    // Since the eigenvalues of a block-upper-triangular matrix are
    // the eigenvalues of its diagonal blocks and we know how to find
    // eigenvalues of a 2x2 matrix, we know the eigenvalues of A.

    var arr = clone$2(A);

    // the list of converged eigenvalues
    var lambdas = [];

    // size of arr, which will get smaller as eigenvalues converge
    var n = N;

    // the diagonal of the block-diagonal matrix that turns
    // converged 2x2 matrices into upper triangular matrices
    var Sdiag = [];

    // N×N matrix describing the overall transformation done during the QR algorithm
    var Qtotal = findVectors ? diag(Array(N).fill(one)) : undefined;

    // nxn matrix describing the QR transformations done since last convergence
    var Qpartial = findVectors ? diag(Array(n).fill(one)) : undefined;

    // last eigenvalue converged before this many steps
    var lastConvergenceBefore = 0;
    while (lastConvergenceBefore <= 100) {
      lastConvergenceBefore += 1;

      // TODO if the convergence is slow, do something clever

      // Perform the factorization

      var k = arr[n - 1][n - 1]; // TODO this is apparently a somewhat
      // old-fashioned choice; ideally set close to an eigenvalue, or
      // perhaps better yet switch to the implicit QR version that is sometimes
      // specifically called the "Francis algorithm" that is alluded to
      // in the following TODO. (Or perhaps we switch to an independently
      // optimized third-party package for the linear algebra operations...)

      for (var i = 0; i < n; i++) {
        arr[i][i] = subtract(arr[i][i], k);
      }

      // TODO do an implicit QR transformation
      var {
        Q,
        R
      } = qr(arr);
      arr = multiply(R, Q);
      for (var _i = 0; _i < n; _i++) {
        arr[_i][_i] = addScalar(arr[_i][_i], k);
      }

      // keep track of transformations
      if (findVectors) {
        Qpartial = multiply(Qpartial, Q);
      }

      // The rightmost diagonal element converged to an eigenvalue
      if (n === 1 || smaller(abs(arr[n - 1][n - 2]), prec)) {
        lastConvergenceBefore = 0;
        lambdas.push(arr[n - 1][n - 1]);

        // keep track of transformations
        if (findVectors) {
          Sdiag.unshift([[1]]);
          inflateMatrix(Qpartial, N);
          Qtotal = multiply(Qtotal, Qpartial);
          if (n > 1) {
            Qpartial = diag(Array(n - 1).fill(one));
          }
        }

        // reduce the matrix size
        n -= 1;
        arr.pop();
        for (var _i2 = 0; _i2 < n; _i2++) {
          arr[_i2].pop();
        }

        // The rightmost diagonal 2x2 block converged
      } else if (n === 2 || smaller(abs(arr[n - 2][n - 3]), prec)) {
        lastConvergenceBefore = 0;
        var ll = eigenvalues2x2(arr[n - 2][n - 2], arr[n - 2][n - 1], arr[n - 1][n - 2], arr[n - 1][n - 1]);
        lambdas.push(...ll);

        // keep track of transformations
        if (findVectors) {
          Sdiag.unshift(jordanBase2x2(arr[n - 2][n - 2], arr[n - 2][n - 1], arr[n - 1][n - 2], arr[n - 1][n - 1], ll[0], ll[1], prec, type));
          inflateMatrix(Qpartial, N);
          Qtotal = multiply(Qtotal, Qpartial);
          if (n > 2) {
            Qpartial = diag(Array(n - 2).fill(one));
          }
        }

        // reduce the matrix size
        n -= 2;
        arr.pop();
        arr.pop();
        for (var _i3 = 0; _i3 < n; _i3++) {
          arr[_i3].pop();
          arr[_i3].pop();
        }
      }
      if (n === 0) {
        break;
      }
    }

    // standard sorting
    lambdas.sort((a, b) => +subtract(abs(a), abs(b)));

    // the algorithm didn't converge
    if (lastConvergenceBefore > 100) {
      var err = Error('The eigenvalues failed to converge. Only found these eigenvalues: ' + lambdas.join(', '));
      err.values = lambdas;
      err.vectors = [];
      throw err;
    }

    // combine the overall QR transformation Qtotal with the subsequent
    // transformation S that turns the diagonal 2x2 blocks to upper triangular
    var C = findVectors ? multiply(Qtotal, blockDiag(Sdiag, N)) : undefined;
    return {
      values: lambdas,
      C
    };
  }

  /**
   * @param {Matrix} A hessenberg-form matrix
   * @param {number} N size of A
   * @param {Matrix} C column transformation matrix that turns A into upper triangular
   * @param {Matrix} R similarity that turns original matrix into A
   * @param {number[]} values array of eigenvalues of A
   * @param {'number'|'BigNumber'|'Complex'} type
   * @returns {number[][]} eigenvalues
   */
  function findEigenvectors(A, N, C, R, values, prec, type) {
    var Cinv = inv(C);
    var U = multiply(Cinv, A, C);
    var big = type === 'BigNumber';
    var cplx = type === 'Complex';
    var zero = big ? bignumber(0) : cplx ? complex(0) : 0;
    var one = big ? bignumber(1) : cplx ? complex(1) : 1;

    // turn values into a kind of "multiset"
    // this way it is easier to find eigenvectors
    var uniqueValues = [];
    var multiplicities = [];
    for (var lambda of values) {
      var i = indexOf(uniqueValues, lambda, equal);
      if (i === -1) {
        uniqueValues.push(lambda);
        multiplicities.push(1);
      } else {
        multiplicities[i] += 1;
      }
    }

    // find eigenvectors by solving U − lambdaE = 0
    // TODO replace with an iterative eigenvector algorithm
    // (this one might fail for imprecise eigenvalues)

    var vectors = [];
    var len = uniqueValues.length;
    var b = Array(N).fill(zero);
    var E = diag(Array(N).fill(one));
    var _loop = function _loop() {
      var lambda = uniqueValues[_i4];
      var S = subtract(U, multiply(lambda, E)); // the characteristic matrix

      var solutions = usolveAll(S, b);
      solutions.shift(); // ignore the null vector

      // looks like we missed something, try inverse iteration
      // But if that fails, just presume that the original matrix truly
      // was defective.
      while (solutions.length < multiplicities[_i4]) {
        var approxVec = inverseIterate(S, N, solutions, prec, type);
        if (approxVec === null) {
          break;
        } // no more vectors were found
        solutions.push(approxVec);
      }

      // Transform back into original array coordinates
      var correction = multiply(inv(R), C);
      solutions = solutions.map(v => multiply(correction, v));
      vectors.push(...solutions.map(v => ({
        value: lambda,
        vector: flatten(v)
      })));
    };
    for (var _i4 = 0; _i4 < len; _i4++) {
      _loop();
    }
    return vectors;
  }

  /**
   * Compute the eigenvalues of an 2x2 matrix
   * @return {[number,number]}
   */
  function eigenvalues2x2(a, b, c, d) {
    // lambda_+- = 1/2 trA +- 1/2 sqrt( tr^2 A - 4 detA )
    var trA = addScalar(a, d);
    var detA = subtract(multiplyScalar(a, d), multiplyScalar(b, c));
    var x = multiplyScalar(trA, 0.5);
    var y = multiplyScalar(sqrt(subtract(multiplyScalar(trA, trA), multiplyScalar(4, detA))), 0.5);
    return [addScalar(x, y), subtract(x, y)];
  }

  /**
   * For an 2x2 matrix compute the transformation matrix S,
   * so that SAS^-1 is an upper triangular matrix
   * @return {[[number,number],[number,number]]}
   * @see https://math.berkeley.edu/~ogus/old/Math_54-05/webfoils/jordan.pdf
   * @see http://people.math.harvard.edu/~knill/teaching/math21b2004/exhibits/2dmatrices/index.html
   */
  function jordanBase2x2(a, b, c, d, l1, l2, prec, type) {
    var big = type === 'BigNumber';
    var cplx = type === 'Complex';
    var zero = big ? bignumber(0) : cplx ? complex(0) : 0;
    var one = big ? bignumber(1) : cplx ? complex(1) : 1;

    // matrix is already upper triangular
    // return an identity matrix
    if (smaller(abs(c), prec)) {
      return [[one, zero], [zero, one]];
    }

    // matrix is diagonalizable
    // return its eigenvectors as columns
    if (larger(abs(subtract(l1, l2)), prec)) {
      return [[subtract(l1, d), subtract(l2, d)], [c, c]];
    }

    // matrix is not diagonalizable
    // compute diagonal elements of N = A - lambdaI
    var na = subtract(a, l1);
    var nd = subtract(d, l1);

    // col(N,2) = 0  implies  S = ( col(N,1), e_1 )
    // col(N,2) != 0 implies  S = ( col(N,2), e_2 )

    if (smaller(abs(b), prec) && smaller(abs(nd), prec)) {
      return [[na, one], [c, zero]];
    } else {
      return [[b, zero], [nd, one]];
    }
  }

  /**
   * Enlarge the matrix from nxn to NxN, setting the new
   * elements to 1 on diagonal and 0 elsewhere
   */
  function inflateMatrix(arr, N) {
    // add columns
    for (var i = 0; i < arr.length; i++) {
      arr[i].push(...Array(N - arr[i].length).fill(0));
    }

    // add rows
    for (var _i5 = arr.length; _i5 < N; _i5++) {
      arr.push(Array(N).fill(0));
      arr[_i5][_i5] = 1;
    }
    return arr;
  }

  /**
   * Create a block-diagonal matrix with the given square matrices on the diagonal
   * @param {Matrix[] | number[][][]} arr array of matrices to be placed on the diagonal
   * @param {number} N the size of the resulting matrix
   */
  function blockDiag(arr, N) {
    var M = [];
    for (var i = 0; i < N; i++) {
      M[i] = Array(N).fill(0);
    }
    var I = 0;
    for (var sub of arr) {
      var n = sub.length;
      for (var _i6 = 0; _i6 < n; _i6++) {
        for (var j = 0; j < n; j++) {
          M[I + _i6][I + j] = sub[_i6][j];
        }
      }
      I += n;
    }
    return M;
  }

  /**
   * Finds the index of an element in an array using a custom equality function
   * @template T
   * @param {Array<T>} arr array in which to search
   * @param {T} el the element to find
   * @param {function(T, T): boolean} fn the equality function, first argument is an element of `arr`, the second is always `el`
   * @returns {number} the index of `el`, or -1 when it's not in `arr`
   */
  function indexOf(arr, el, fn) {
    for (var i = 0; i < arr.length; i++) {
      if (fn(arr[i], el)) {
        return i;
      }
    }
    return -1;
  }

  /**
   * Provided a near-singular upper-triangular matrix A and a list of vectors,
   * finds an eigenvector of A with the smallest eigenvalue, which is orthogonal
   * to each vector in the list
   * @template T
   * @param {T[][]} A near-singular square matrix
   * @param {number} N dimension
   * @param {T[][]} orthog list of vectors
   * @param {number} prec epsilon
   * @param {'number'|'BigNumber'|'Complex'} type
   * @return {T[] | null} eigenvector
   *
   * @see Numerical Recipes for Fortran 77 – 11.7 Eigenvalues or Eigenvectors by Inverse Iteration
   */
  function inverseIterate(A, N, orthog, prec, type) {
    var largeNum = type === 'BigNumber' ? bignumber(1000) : 1000;
    var b; // the vector

    // you better choose a random vector before I count to five
    var i = 0;
    for (; i < 5; ++i) {
      b = randomOrthogonalVector(N, orthog, type);
      try {
        b = usolve(A, b);
      } catch (_unused) {
        // That direction didn't work, likely because the original matrix
        // was defective. But still make the full number of tries...
        continue;
      }
      if (larger(norm(b), largeNum)) {
        break;
      }
    }
    if (i >= 5) {
      return null; // couldn't find any orthogonal vector in the image
    }

    // you better converge before I count to ten
    i = 0;
    while (true) {
      var c = usolve(A, b);
      if (smaller(norm(orthogonalComplement(b, [c])), prec)) {
        break;
      }
      if (++i >= 10) {
        return null;
      }
      b = normalize(c);
    }
    return b;
  }

  /**
   * Generates a random unit vector of dimension N, orthogonal to each vector in the list
   * @template T
   * @param {number} N dimension
   * @param {T[][]} orthog list of vectors
   * @param {'number'|'BigNumber'|'Complex'} type
   * @returns {T[]} random vector
   */
  function randomOrthogonalVector(N, orthog, type) {
    var big = type === 'BigNumber';
    var cplx = type === 'Complex';

    // generate random vector with the correct type
    var v = Array(N).fill(0).map(_ => 2 * Math.random() - 1);
    if (big) {
      v = v.map(n => bignumber(n));
    }
    if (cplx) {
      v = v.map(n => complex(n));
    }

    // project to orthogonal complement
    v = orthogonalComplement(v, orthog);

    // normalize
    return normalize(v, type);
  }

  /**
   * Project vector v to the orthogonal complement of an array of vectors
   */
  function orthogonalComplement(v, orthog) {
    var vectorShape = size(v);
    for (var w of orthog) {
      w = reshape(w, vectorShape); // make sure this is just a vector computation
      // v := v − (w, v)/|w|^2 w
      v = subtract(v, multiply(divideScalar(dot(w, v), dot(w, w)), w));
    }
    return v;
  }

  /**
   * Calculate the norm of a vector.
   * We can't use math.norm because factory can't handle circular dependency.
   * Seriously, I'm really fed up with factory.
   */
  function norm(v) {
    return abs(sqrt(dot(v, v)));
  }

  /**
   * Normalize a vector
   * @template T
   * @param {T[]} v
   * @param {'number'|'BigNumber'|'Complex'} type
   * @returns {T[]} normalized vec
   */
  function normalize(v, type) {
    var big = type === 'BigNumber';
    var cplx = type === 'Complex';
    var one = big ? bignumber(1) : cplx ? complex(1) : 1;
    return multiply(divideScalar(one, norm(v)), v);
  }
  return complexEigs;
}

function createRealSymmetric(_ref) {
  var {
    config,
    addScalar,
    subtract,
    abs,
    atan,
    cos,
    sin,
    multiplyScalar,
    inv,
    bignumber,
    multiply,
    add
  } = _ref;
  /**
   * @param {number[] | BigNumber[]} arr
   * @param {number} N
   * @param {number} prec
   * @param {'number' | 'BigNumber'} type
   */
  function main(arr, N) {
    var prec = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : config.relTol;
    var type = arguments.length > 3 ? arguments[3] : undefined;
    var computeVectors = arguments.length > 4 ? arguments[4] : undefined;
    if (type === 'number') {
      return diag(arr, prec, computeVectors);
    }
    if (type === 'BigNumber') {
      return diagBig(arr, prec, computeVectors);
    }
    throw TypeError('Unsupported data type: ' + type);
  }

  // diagonalization implementation for number (efficient)
  function diag(x, precision, computeVectors) {
    var N = x.length;
    var e0 = Math.abs(precision / N);
    var psi;
    var Sij;
    if (computeVectors) {
      Sij = new Array(N);
      // Sij is Identity Matrix
      for (var i = 0; i < N; i++) {
        Sij[i] = Array(N).fill(0);
        Sij[i][i] = 1.0;
      }
    }
    // initial error
    var Vab = getAij(x);
    while (Math.abs(Vab[1]) >= Math.abs(e0)) {
      var _i = Vab[0][0];
      var j = Vab[0][1];
      psi = getTheta(x[_i][_i], x[j][j], x[_i][j]);
      x = x1(x, psi, _i, j);
      if (computeVectors) Sij = Sij1(Sij, psi, _i, j);
      Vab = getAij(x);
    }
    var Ei = Array(N).fill(0); // eigenvalues
    for (var _i2 = 0; _i2 < N; _i2++) {
      Ei[_i2] = x[_i2][_i2];
    }
    return sorting(clone$2(Ei), Sij, computeVectors);
  }

  // diagonalization implementation for bigNumber
  function diagBig(x, precision, computeVectors) {
    var N = x.length;
    var e0 = abs(precision / N);
    var psi;
    var Sij;
    if (computeVectors) {
      Sij = new Array(N);
      // Sij is Identity Matrix
      for (var i = 0; i < N; i++) {
        Sij[i] = Array(N).fill(0);
        Sij[i][i] = 1.0;
      }
    }
    // initial error
    var Vab = getAijBig(x);
    while (abs(Vab[1]) >= abs(e0)) {
      var _i3 = Vab[0][0];
      var j = Vab[0][1];
      psi = getThetaBig(x[_i3][_i3], x[j][j], x[_i3][j]);
      x = x1Big(x, psi, _i3, j);
      if (computeVectors) Sij = Sij1Big(Sij, psi, _i3, j);
      Vab = getAijBig(x);
    }
    var Ei = Array(N).fill(0); // eigenvalues
    for (var _i4 = 0; _i4 < N; _i4++) {
      Ei[_i4] = x[_i4][_i4];
    }
    // return [clone(Ei), clone(Sij)]
    return sorting(clone$2(Ei), Sij, computeVectors);
  }

  // get angle
  function getTheta(aii, ajj, aij) {
    var denom = ajj - aii;
    if (Math.abs(denom) <= config.relTol) {
      return Math.PI / 4.0;
    } else {
      return 0.5 * Math.atan(2.0 * aij / (ajj - aii));
    }
  }

  // get angle
  function getThetaBig(aii, ajj, aij) {
    var denom = subtract(ajj, aii);
    if (abs(denom) <= config.relTol) {
      return bignumber(-1).acos().div(4);
    } else {
      return multiplyScalar(0.5, atan(multiply(2.0, aij, inv(denom))));
    }
  }

  // update eigvec
  function Sij1(Sij, theta, i, j) {
    var N = Sij.length;
    var c = Math.cos(theta);
    var s = Math.sin(theta);
    var Ski = Array(N).fill(0);
    var Skj = Array(N).fill(0);
    for (var k = 0; k < N; k++) {
      Ski[k] = c * Sij[k][i] - s * Sij[k][j];
      Skj[k] = s * Sij[k][i] + c * Sij[k][j];
    }
    for (var _k = 0; _k < N; _k++) {
      Sij[_k][i] = Ski[_k];
      Sij[_k][j] = Skj[_k];
    }
    return Sij;
  }
  // update eigvec for overlap
  function Sij1Big(Sij, theta, i, j) {
    var N = Sij.length;
    var c = cos(theta);
    var s = sin(theta);
    var Ski = Array(N).fill(bignumber(0));
    var Skj = Array(N).fill(bignumber(0));
    for (var k = 0; k < N; k++) {
      Ski[k] = subtract(multiplyScalar(c, Sij[k][i]), multiplyScalar(s, Sij[k][j]));
      Skj[k] = addScalar(multiplyScalar(s, Sij[k][i]), multiplyScalar(c, Sij[k][j]));
    }
    for (var _k2 = 0; _k2 < N; _k2++) {
      Sij[_k2][i] = Ski[_k2];
      Sij[_k2][j] = Skj[_k2];
    }
    return Sij;
  }

  // update matrix
  function x1Big(Hij, theta, i, j) {
    var N = Hij.length;
    var c = bignumber(cos(theta));
    var s = bignumber(sin(theta));
    var c2 = multiplyScalar(c, c);
    var s2 = multiplyScalar(s, s);
    var Aki = Array(N).fill(bignumber(0));
    var Akj = Array(N).fill(bignumber(0));
    // 2cs Hij
    var csHij = multiply(bignumber(2), c, s, Hij[i][j]);
    //  Aii
    var Aii = addScalar(subtract(multiplyScalar(c2, Hij[i][i]), csHij), multiplyScalar(s2, Hij[j][j]));
    var Ajj = add(multiplyScalar(s2, Hij[i][i]), csHij, multiplyScalar(c2, Hij[j][j]));
    // 0  to i
    for (var k = 0; k < N; k++) {
      Aki[k] = subtract(multiplyScalar(c, Hij[i][k]), multiplyScalar(s, Hij[j][k]));
      Akj[k] = addScalar(multiplyScalar(s, Hij[i][k]), multiplyScalar(c, Hij[j][k]));
    }
    // Modify Hij
    Hij[i][i] = Aii;
    Hij[j][j] = Ajj;
    Hij[i][j] = bignumber(0);
    Hij[j][i] = bignumber(0);
    // 0  to i
    for (var _k3 = 0; _k3 < N; _k3++) {
      if (_k3 !== i && _k3 !== j) {
        Hij[i][_k3] = Aki[_k3];
        Hij[_k3][i] = Aki[_k3];
        Hij[j][_k3] = Akj[_k3];
        Hij[_k3][j] = Akj[_k3];
      }
    }
    return Hij;
  }

  // update matrix
  function x1(Hij, theta, i, j) {
    var N = Hij.length;
    var c = Math.cos(theta);
    var s = Math.sin(theta);
    var c2 = c * c;
    var s2 = s * s;
    var Aki = Array(N).fill(0);
    var Akj = Array(N).fill(0);
    //  Aii
    var Aii = c2 * Hij[i][i] - 2 * c * s * Hij[i][j] + s2 * Hij[j][j];
    var Ajj = s2 * Hij[i][i] + 2 * c * s * Hij[i][j] + c2 * Hij[j][j];
    // 0  to i
    for (var k = 0; k < N; k++) {
      Aki[k] = c * Hij[i][k] - s * Hij[j][k];
      Akj[k] = s * Hij[i][k] + c * Hij[j][k];
    }
    // Modify Hij
    Hij[i][i] = Aii;
    Hij[j][j] = Ajj;
    Hij[i][j] = 0;
    Hij[j][i] = 0;
    // 0  to i
    for (var _k4 = 0; _k4 < N; _k4++) {
      if (_k4 !== i && _k4 !== j) {
        Hij[i][_k4] = Aki[_k4];
        Hij[_k4][i] = Aki[_k4];
        Hij[j][_k4] = Akj[_k4];
        Hij[_k4][j] = Akj[_k4];
      }
    }
    return Hij;
  }

  // get max off-diagonal value from Upper Diagonal
  function getAij(Mij) {
    var N = Mij.length;
    var maxMij = 0;
    var maxIJ = [0, 1];
    for (var i = 0; i < N; i++) {
      for (var j = i + 1; j < N; j++) {
        if (Math.abs(maxMij) < Math.abs(Mij[i][j])) {
          maxMij = Math.abs(Mij[i][j]);
          maxIJ = [i, j];
        }
      }
    }
    return [maxIJ, maxMij];
  }

  // get max off-diagonal value from Upper Diagonal
  function getAijBig(Mij) {
    var N = Mij.length;
    var maxMij = 0;
    var maxIJ = [0, 1];
    for (var i = 0; i < N; i++) {
      for (var j = i + 1; j < N; j++) {
        if (abs(maxMij) < abs(Mij[i][j])) {
          maxMij = abs(Mij[i][j]);
          maxIJ = [i, j];
        }
      }
    }
    return [maxIJ, maxMij];
  }

  // sort results
  function sorting(E, S, computeVectors) {
    var N = E.length;
    var values = Array(N);
    var vecs;
    if (computeVectors) {
      vecs = Array(N);
      for (var k = 0; k < N; k++) {
        vecs[k] = Array(N);
      }
    }
    for (var i = 0; i < N; i++) {
      var minID = 0;
      var minE = E[0];
      for (var j = 0; j < E.length; j++) {
        if (abs(E[j]) < abs(minE)) {
          minID = j;
          minE = E[minID];
        }
      }
      values[i] = E.splice(minID, 1)[0];
      if (computeVectors) {
        for (var _k5 = 0; _k5 < N; _k5++) {
          vecs[i][_k5] = S[_k5][minID];
          S[_k5].splice(minID, 1);
        }
      }
    }
    if (!computeVectors) return {
      values
    };
    var eigenvectors = vecs.map((vector, i) => ({
      value: values[i],
      vector
    }));
    return {
      values,
      eigenvectors
    };
  }
  return main;
}

var name$15 = 'eigs';

// The absolute state of math.js's dependency system:
var dependencies$15 = ['config', 'typed', 'matrix', 'addScalar', 'equal', 'subtract', 'abs', 'atan', 'cos', 'sin', 'multiplyScalar', 'divideScalar', 'inv', 'bignumber', 'multiply', 'add', 'larger', 'column', 'flatten', 'number', 'complex', 'sqrt', 'diag', 'size', 'reshape', 'qr', 'usolve', 'usolveAll', 'im', 're', 'smaller', 'matrixFromColumns', 'dot'];
var createEigs = /* #__PURE__ */factory(name$15, dependencies$15, _ref => {
  var {
    config,
    typed,
    matrix,
    addScalar,
    subtract,
    equal,
    abs,
    atan,
    cos,
    sin,
    multiplyScalar,
    divideScalar,
    inv,
    bignumber,
    multiply,
    add,
    larger,
    column,
    flatten,
    number,
    complex,
    sqrt,
    diag,
    size,
    reshape,
    qr,
    usolve,
    usolveAll,
    im,
    re,
    smaller,
    matrixFromColumns,
    dot
  } = _ref;
  var doRealSymmetric = createRealSymmetric({
    config,
    addScalar,
    subtract,
    column,
    flatten,
    equal,
    abs,
    atan,
    cos,
    sin,
    multiplyScalar,
    inv,
    bignumber,
    complex,
    multiply,
    add
  });
  var doComplexEigs = createComplexEigs({
    config,
    addScalar,
    subtract,
    multiply,
    multiplyScalar,
    flatten,
    divideScalar,
    sqrt,
    abs,
    bignumber,
    diag,
    size,
    reshape,
    qr,
    inv,
    usolve,
    usolveAll,
    equal,
    complex,
    larger,
    smaller,
    matrixFromColumns,
    dot
  });

  /**
   * Compute eigenvalues and optionally eigenvectors of a square matrix.
   * The eigenvalues are sorted by their absolute value, ascending, and
   * returned as a vector in the `values` property of the returned project.
   * An eigenvalue with algebraic multiplicity k will be listed k times, so
   * that the returned `values` vector always has length equal to the size
   * of the input matrix.
   *
   * The `eigenvectors` property of the return value provides the eigenvectors.
   * It is an array of plain objects: the `value` property of each gives the
   * associated eigenvalue, and the `vector` property gives the eigenvector
   * itself. Note that the same `value` property will occur as many times in
   * the list provided by `eigenvectors` as the geometric multiplicity of
   * that value.
   *
   * If the algorithm fails to converge, it will throw an error –
   * in that case, however, you may still find useful information
   * in `err.values` and `err.vectors`.
   *
   * Note that the 'precision' option does not directly specify the _accuracy_
   * of the returned eigenvalues. Rather, it determines how small an entry
   * of the iterative approximations to an upper triangular matrix must be
   * in order to be considered zero. The actual accuracy of the returned
   * eigenvalues may be greater or less than the precision, depending on the
   * conditioning of the matrix and how far apart or close the actual
   * eigenvalues are. Note that currently, relatively simple, "traditional"
   * methods of eigenvalue computation are being used; this is not a modern,
   * high-precision eigenvalue computation. That said, it should typically
   * produce fairly reasonable results.
   *
   * Syntax:
   *
   *     math.eigs(x, [prec])
   *     math.eigs(x, {options})
   *
   * Examples:
   *
   *     const { eigs, multiply, column, transpose, matrixFromColumns } = math
   *     const H = [[5, 2.3], [2.3, 1]]
   *     const ans = eigs(H) // returns {values: [E1,E2...sorted], eigenvectors: [{value: E1, vector: v2}, {value: e, vector: v2}, ...]
   *     const E = ans.values
   *     const V = ans.eigenvectors
   *     multiply(H, V[0].vector)) // returns multiply(E[0], V[0].vector))
   *     const U = matrixFromColumns(...V.map(obj => obj.vector))
   *     const UTxHxU = multiply(transpose(U), H, U) // diagonalizes H if possible
   *     E[0] == UTxHxU[0][0]  // returns true always
   *
   *     // Compute only approximate eigenvalues:
   *     const {values} = eigs(H, {eigenvectors: false, precision: 1e-6})
   *
   * See also:
   *
   *     inv
   *
   * @param {Array | Matrix} x  Matrix to be diagonalized
   *
   * @param {number | BigNumber | OptsObject} [opts] Object with keys `precision`, defaulting to config.relTol, and `eigenvectors`, defaulting to true and specifying whether to compute eigenvectors. If just a number, specifies precision.
   * @return {{values: Array|Matrix, eigenvectors?: Array<EVobj>}} Object containing an array of eigenvalues and an array of {value: number|BigNumber, vector: Array|Matrix} objects. The eigenvectors property is undefined if eigenvectors were not requested.
   *
   */
  return typed('eigs', {
    // The conversion to matrix in the first two implementations,
    // just to convert back to an array right away in
    // computeValuesAndVectors, is unfortunate, and should perhaps be
    // streamlined. It is done because the Matrix object carries some
    // type information about its entries, and so constructing the matrix
    // is a roundabout way of doing type detection.
    Array: function Array(x) {
      return doEigs(matrix(x));
    },
    'Array, number|BigNumber': function ArrayNumberBigNumber(x, prec) {
      return doEigs(matrix(x), {
        precision: prec
      });
    },
    'Array, Object'(x, opts) {
      return doEigs(matrix(x), opts);
    },
    Matrix: function Matrix(mat) {
      return doEigs(mat, {
        matricize: true
      });
    },
    'Matrix, number|BigNumber': function MatrixNumberBigNumber(mat, prec) {
      return doEigs(mat, {
        precision: prec,
        matricize: true
      });
    },
    'Matrix, Object': function MatrixObject(mat, opts) {
      var useOpts = {
        matricize: true
      };
      _extends$1(useOpts, opts);
      return doEigs(mat, useOpts);
    }
  });
  function doEigs(mat) {
    var _opts$precision;
    var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var computeVectors = 'eigenvectors' in opts ? opts.eigenvectors : true;
    var prec = (_opts$precision = opts.precision) !== null && _opts$precision !== void 0 ? _opts$precision : config.relTol;
    var result = computeValuesAndVectors(mat, prec, computeVectors);
    if (opts.matricize) {
      result.values = matrix(result.values);
      if (computeVectors) {
        result.eigenvectors = result.eigenvectors.map(_ref2 => {
          var {
            value,
            vector
          } = _ref2;
          return {
            value,
            vector: matrix(vector)
          };
        });
      }
    }
    if (computeVectors) {
      Object.defineProperty(result, 'vectors', {
        enumerable: false,
        // to make sure that the eigenvectors can still be
        // converted to string.
        get: () => {
          throw new Error('eigs(M).vectors replaced with eigs(M).eigenvectors');
        }
      });
    }
    return result;
  }
  function computeValuesAndVectors(mat, prec, computeVectors) {
    var arr = mat.toArray(); // NOTE: arr is guaranteed to be unaliased
    // and so safe to modify in place
    var asize = mat.size();
    if (asize.length !== 2 || asize[0] !== asize[1]) {
      throw new RangeError("Matrix must be square (size: ".concat(format(asize), ")"));
    }
    var N = asize[0];
    if (isReal(arr, N, prec)) {
      coerceReal(arr, N); // modifies arr by side effect

      if (isSymmetric(arr, N, prec)) {
        var _type = coerceTypes(mat, arr, N); // modifies arr by side effect
        return doRealSymmetric(arr, N, prec, _type, computeVectors);
      }
    }
    var type = coerceTypes(mat, arr, N); // modifies arr by side effect
    return doComplexEigs(arr, N, prec, type, computeVectors);
  }

  /** @return {boolean} */
  function isSymmetric(arr, N, prec) {
    for (var i = 0; i < N; i++) {
      for (var j = i; j < N; j++) {
        // TODO proper comparison of bignum and frac
        if (larger(bignumber(abs(subtract(arr[i][j], arr[j][i]))), prec)) {
          return false;
        }
      }
    }
    return true;
  }

  /** @return {boolean} */
  function isReal(arr, N, prec) {
    for (var i = 0; i < N; i++) {
      for (var j = 0; j < N; j++) {
        // TODO proper comparison of bignum and frac
        if (larger(bignumber(abs(im(arr[i][j]))), prec)) {
          return false;
        }
      }
    }
    return true;
  }
  function coerceReal(arr, N) {
    for (var i = 0; i < N; i++) {
      for (var j = 0; j < N; j++) {
        arr[i][j] = re(arr[i][j]);
      }
    }
  }

  /** @return {'number' | 'BigNumber' | 'Complex'} */
  function coerceTypes(mat, arr, N) {
    /** @type {string} */
    var type = mat.datatype();
    if (type === 'number' || type === 'BigNumber' || type === 'Complex') {
      return type;
    }
    var hasNumber = false;
    var hasBig = false;
    var hasComplex = false;
    for (var i = 0; i < N; i++) {
      for (var j = 0; j < N; j++) {
        var el = arr[i][j];
        if (isNumber(el) || isFraction(el)) {
          hasNumber = true;
        } else if (isBigNumber(el)) {
          hasBig = true;
        } else if (isComplex(el)) {
          hasComplex = true;
        } else {
          throw TypeError('Unsupported type in Matrix: ' + typeOf(el));
        }
      }
    }
    if (hasBig && hasComplex) {
      console.warn('Complex BigNumbers not supported, this operation will lose precission.');
    }
    if (hasComplex) {
      for (var _i = 0; _i < N; _i++) {
        for (var _j = 0; _j < N; _j++) {
          arr[_i][_j] = complex(arr[_i][_j]);
        }
      }
      return 'Complex';
    }
    if (hasBig) {
      for (var _i2 = 0; _i2 < N; _i2++) {
        for (var _j2 = 0; _j2 < N; _j2++) {
          arr[_i2][_j2] = bignumber(arr[_i2][_j2]);
        }
      }
      return 'BigNumber';
    }
    if (hasNumber) {
      for (var _i3 = 0; _i3 < N; _i3++) {
        for (var _j3 = 0; _j3 < N; _j3++) {
          arr[_i3][_j3] = number(arr[_i3][_j3]);
        }
      }
      return 'number';
    } else {
      throw TypeError('Matrix contains unsupported types only.');
    }
  }
});

var name$14 = 'expm';
var dependencies$14 = ['typed', 'abs', 'add', 'identity', 'inv', 'multiply'];
var createExpm = /* #__PURE__ */factory(name$14, dependencies$14, _ref => {
  var {
    typed,
    abs,
    add,
    identity,
    inv,
    multiply
  } = _ref;
  /**
   * Compute the matrix exponential, expm(A) = e^A. The matrix must be square.
   * Not to be confused with exp(a), which performs element-wise
   * exponentiation.
   *
   * The exponential is calculated using the Padé approximant with scaling and
   * squaring; see "Nineteen Dubious Ways to Compute the Exponential of a
   * Matrix," by Moler and Van Loan.
   *
   * Syntax:
   *
   *     math.expm(x)
   *
   * Examples:
   *
   *     const A = [[0,2],[0,0]]
   *     math.expm(A)        // returns [[1,2],[0,1]]
   *
   * See also:
   *
   *     exp
   *
   * @param {Matrix} x  A square Matrix
   * @return {Matrix}   The exponential of x
   */
  return typed(name$14, {
    Matrix: function Matrix(A) {
      // Check matrix size
      var size = A.size();
      if (size.length !== 2 || size[0] !== size[1]) {
        throw new RangeError('Matrix must be square ' + '(size: ' + format(size) + ')');
      }
      var n = size[0];

      // Desired accuracy of the approximant (The actual accuracy
      // will be affected by round-off error)
      var eps = 1e-15;

      // The Padé approximant is not so accurate when the values of A
      // are "large", so scale A by powers of two. Then compute the
      // exponential, and square the result repeatedly according to
      // the identity e^A = (e^(A/m))^m

      // Compute infinity-norm of A, ||A||, to see how "big" it is
      var infNorm = infinityNorm(A);

      // Find the optimal scaling factor and number of terms in the
      // Padé approximant to reach the desired accuracy
      var params = findParams(infNorm, eps);
      var q = params.q;
      var j = params.j;

      // The Pade approximation to e^A is:
      // Rqq(A) = Dqq(A) ^ -1 * Nqq(A)
      // where
      // Nqq(A) = sum(i=0, q, (2q-i)!p! / [ (2q)!i!(q-i)! ] A^i
      // Dqq(A) = sum(i=0, q, (2q-i)!q! / [ (2q)!i!(q-i)! ] (-A)^i

      // Scale A by 1 / 2^j
      var Apos = multiply(A, Math.pow(2, -j));

      // The i=0 term is just the identity matrix
      var N = identity(n);
      var D = identity(n);

      // Initialization (i=0)
      var factor = 1;

      // Initialization (i=1)
      var AposToI = Apos; // Cloning not necessary
      var alternate = -1;
      for (var i = 1; i <= q; i++) {
        if (i > 1) {
          AposToI = multiply(AposToI, Apos);
          alternate = -alternate;
        }
        factor = factor * (q - i + 1) / ((2 * q - i + 1) * i);
        N = add(N, multiply(factor, AposToI));
        D = add(D, multiply(factor * alternate, AposToI));
      }
      var R = multiply(inv(D), N);

      // Square j times
      for (var _i = 0; _i < j; _i++) {
        R = multiply(R, R);
      }
      return isSparseMatrix(A) ? A.createSparseMatrix(R) : R;
    }
  });
  function infinityNorm(A) {
    var n = A.size()[0];
    var infNorm = 0;
    for (var i = 0; i < n; i++) {
      var rowSum = 0;
      for (var j = 0; j < n; j++) {
        rowSum += abs(A.get([i, j]));
      }
      infNorm = Math.max(rowSum, infNorm);
    }
    return infNorm;
  }

  /**
   * Find the best parameters for the Pade approximant given
   * the matrix norm and desired accuracy. Returns the first acceptable
   * combination in order of increasing computational load.
   */
  function findParams(infNorm, eps) {
    var maxSearchSize = 30;
    for (var k = 0; k < maxSearchSize; k++) {
      for (var q = 0; q <= k; q++) {
        var j = k - q;
        if (errorEstimate(infNorm, q, j) < eps) {
          return {
            q,
            j
          };
        }
      }
    }
    throw new Error('Could not find acceptable parameters to compute the matrix exponential (try increasing maxSearchSize in expm.js)');
  }

  /**
   * Returns the estimated error of the Pade approximant for the given
   * parameters.
   */
  function errorEstimate(infNorm, q, j) {
    var qfac = 1;
    for (var i = 2; i <= q; i++) {
      qfac *= i;
    }
    var twoqfac = qfac;
    for (var _i2 = q + 1; _i2 <= 2 * q; _i2++) {
      twoqfac *= _i2;
    }
    var twoqp1fac = twoqfac * (2 * q + 1);
    return 8.0 * Math.pow(infNorm / Math.pow(2, j), 2 * q) * qfac * qfac / (twoqfac * twoqp1fac);
  }
});

var name$13 = 'sqrtm';
var dependencies$13 = ['typed', 'abs', 'add', 'multiply', 'map', 'sqrt', 'subtract', 'inv', 'size', 'max', 'identity'];
var createSqrtm = /* #__PURE__ */factory(name$13, dependencies$13, _ref => {
  var {
    typed,
    abs,
    add,
    multiply,
    map,
    sqrt,
    subtract,
    inv,
    size,
    max,
    identity
  } = _ref;
  var _maxIterations = 1e3;
  var _tolerance = 1e-6;

  /**
   * Calculate the principal square root matrix using the Denman–Beavers iterative method
   *
   * https://en.wikipedia.org/wiki/Square_root_of_a_matrix#By_Denman–Beavers_iteration
   *
   * @param  {Array | Matrix} A   The square matrix `A`
   * @return {Array | Matrix}     The principal square root of matrix `A`
   * @private
   */
  function _denmanBeavers(A) {
    var error;
    var iterations = 0;
    var Y = A;
    var Z = identity(size(A));
    do {
      var Yk = Y;
      Y = multiply(0.5, add(Yk, inv(Z)));
      Z = multiply(0.5, add(Z, inv(Yk)));
      error = max(abs(subtract(Y, Yk)));
      if (error > _tolerance && ++iterations > _maxIterations) {
        throw new Error('computing square root of matrix: iterative method could not converge');
      }
    } while (error > _tolerance);
    return Y;
  }

  /**
   * Calculate the principal square root of a square matrix.
   * The principal square root matrix `X` of another matrix `A` is such that `X * X = A`.
   *
   * https://en.wikipedia.org/wiki/Square_root_of_a_matrix
   *
   * Syntax:
   *
   *     math.sqrtm(A)
   *
   * Examples:
   *
   *     math.sqrtm([[33, 24], [48, 57]]) // returns [[5, 2], [4, 7]]
   *
   * See also:
   *
   *     sqrt, pow
   *
   * @param  {Array | Matrix} A   The square matrix `A`
   * @return {Array | Matrix}     The principal square root of matrix `A`
   */
  return typed(name$13, {
    'Array | Matrix': function ArrayMatrix(A) {
      var size = isMatrix(A) ? A.size() : arraySize(A);
      switch (size.length) {
        case 1:
          // Single element Array | Matrix
          if (size[0] === 1) {
            return map(A, sqrt);
          } else {
            throw new RangeError('Matrix must be square ' + '(size: ' + format(size) + ')');
          }
        case 2:
          {
            // Two-dimensional Array | Matrix
            var rows = size[0];
            var cols = size[1];
            if (rows === cols) {
              return _denmanBeavers(A);
            } else {
              throw new RangeError('Matrix must be square ' + '(size: ' + format(size) + ')');
            }
          }
        default:
          // Multi dimensional array
          throw new RangeError('Matrix must be at most two dimensional ' + '(size: ' + format(size) + ')');
      }
    }
  });
});

var name$12 = 'sylvester';
var dependencies$12 = ['typed', 'schur', 'matrixFromColumns', 'matrix', 'multiply', 'range', 'concat', 'transpose', 'index', 'subset', 'add', 'subtract', 'identity', 'lusolve', 'abs'];
var createSylvester = /* #__PURE__ */factory(name$12, dependencies$12, _ref => {
  var {
    typed,
    schur,
    matrixFromColumns,
    matrix,
    multiply,
    range,
    concat,
    transpose,
    index,
    subset,
    add,
    subtract,
    identity,
    lusolve,
    abs
  } = _ref;
  /**
   *
   * Solves the real-valued Sylvester equation AX+XB=C for X, where A, B and C are
   * matrices of appropriate dimensions, being A and B squared. Notice that other
   * equivalent definitions for the Sylvester equation exist and this function
   * assumes the one presented in the original publication of the the Bartels-
   * Stewart algorithm, which is implemented by this function.
   * https://en.wikipedia.org/wiki/Sylvester_equation
   *
   * Syntax:
   *
   *     math.sylvester(A, B, C)
   *
   * Examples:
   *
   *     const A = [[-1, -2], [1, 1]]
   *     const B = [[2, -1], [1, -2]]
   *     const C = [[-3, 2], [3, 0]]
   *     math.sylvester(A, B, C)      // returns DenseMatrix [[-0.25, 0.25], [1.5, -1.25]]
   *
   * See also:
   *
   *     schur, lyap
   *
   * @param {Matrix | Array} A  Matrix A
   * @param {Matrix | Array} B  Matrix B
   * @param {Matrix | Array} C  Matrix C
   * @return {Matrix | Array}   Matrix X, solving the Sylvester equation
   */
  return typed(name$12, {
    'Matrix, Matrix, Matrix': _sylvester,
    'Array, Matrix, Matrix': function ArrayMatrixMatrix(A, B, C) {
      return _sylvester(matrix(A), B, C);
    },
    'Array, Array, Matrix': function ArrayArrayMatrix(A, B, C) {
      return _sylvester(matrix(A), matrix(B), C);
    },
    'Array, Matrix, Array': function ArrayMatrixArray(A, B, C) {
      return _sylvester(matrix(A), B, matrix(C));
    },
    'Matrix, Array, Matrix': function MatrixArrayMatrix(A, B, C) {
      return _sylvester(A, matrix(B), C);
    },
    'Matrix, Array, Array': function MatrixArrayArray(A, B, C) {
      return _sylvester(A, matrix(B), matrix(C));
    },
    'Matrix, Matrix, Array': function MatrixMatrixArray(A, B, C) {
      return _sylvester(A, B, matrix(C));
    },
    'Array, Array, Array': function ArrayArrayArray(A, B, C) {
      return _sylvester(matrix(A), matrix(B), matrix(C)).toArray();
    }
  });
  function _sylvester(A, B, C) {
    var n = B.size()[0];
    var m = A.size()[0];
    var sA = schur(A);
    var F = sA.T;
    var U = sA.U;
    var sB = schur(multiply(-1, B));
    var G = sB.T;
    var V = sB.U;
    var D = multiply(multiply(transpose(U), C), V);
    var all = range(0, m);
    var y = [];
    var hc = (a, b) => concat(a, b, 1);
    var vc = (a, b) => concat(a, b, 0);
    for (var k = 0; k < n; k++) {
      if (k < n - 1 && abs(subset(G, index(k + 1, k))) > 1e-5) {
        var RHS = vc(subset(D, index(all, k)), subset(D, index(all, k + 1)));
        for (var j = 0; j < k; j++) {
          RHS = add(RHS, vc(multiply(y[j], subset(G, index(j, k))), multiply(y[j], subset(G, index(j, k + 1)))));
        }
        var gkk = multiply(identity(m), multiply(-1, subset(G, index(k, k))));
        var gmk = multiply(identity(m), multiply(-1, subset(G, index(k + 1, k))));
        var gkm = multiply(identity(m), multiply(-1, subset(G, index(k, k + 1))));
        var gmm = multiply(identity(m), multiply(-1, subset(G, index(k + 1, k + 1))));
        var LHS = vc(hc(add(F, gkk), gmk), hc(gkm, add(F, gmm)));
        var yAux = lusolve(LHS, RHS);
        y[k] = yAux.subset(index(range(0, m), 0));
        y[k + 1] = yAux.subset(index(range(m, 2 * m), 0));
        k++;
      } else {
        var _RHS = subset(D, index(all, k));
        for (var _j = 0; _j < k; _j++) {
          _RHS = add(_RHS, multiply(y[_j], subset(G, index(_j, k))));
        }
        var _gkk = subset(G, index(k, k));
        var _LHS = subtract(F, multiply(_gkk, identity(m)));
        y[k] = lusolve(_LHS, _RHS);
      }
    }
    var Y = matrix(matrixFromColumns(...y));
    var X = multiply(U, multiply(Y, transpose(V)));
    return X;
  }
});

var name$11 = 'schur';
var dependencies$11 = ['typed', 'matrix', 'identity', 'multiply', 'qr', 'norm', 'subtract'];
var createSchur = /* #__PURE__ */factory(name$11, dependencies$11, _ref => {
  var {
    typed,
    matrix,
    identity,
    multiply,
    qr,
    norm,
    subtract
  } = _ref;
  /**
   *
   * Performs a real Schur decomposition of the real matrix A = UTU' where U is orthogonal
   * and T is upper quasi-triangular.
   * https://en.wikipedia.org/wiki/Schur_decomposition
   *
   * Syntax:
   *
   *     math.schur(A)
   *
   * Examples:
   *
   *     const A = [[1, 0], [-4, 3]]
   *     math.schur(A) // returns {T: [[3, 4], [0, 1]], R: [[0, 1], [-1, 0]]}
   *
   * See also:
   *
   *     sylvester, lyap, qr
   *
   * @param {Array | Matrix} A  Matrix A
   * @return {{U: Array | Matrix, T: Array | Matrix}} Object containing both matrix U and T of the Schur Decomposition A=UTU'
   */
  return typed(name$11, {
    Array: function Array(X) {
      var r = _schur(matrix(X));
      return {
        U: r.U.valueOf(),
        T: r.T.valueOf()
      };
    },
    Matrix: function Matrix(X) {
      return _schur(X);
    }
  });
  function _schur(X) {
    var n = X.size()[0];
    var A = X;
    var U = identity(n);
    var k = 0;
    var A0;
    do {
      A0 = A;
      var QR = qr(A);
      var Q = QR.Q;
      var R = QR.R;
      A = multiply(R, Q);
      U = multiply(U, Q);
      if (k++ > 100) {
        break;
      }
    } while (norm(subtract(A, A0)) > 1e-4);
    return {
      U,
      T: A
    };
  }
});

var name$10 = 'lyap';
var dependencies$10 = ['typed', 'matrix', 'sylvester', 'multiply', 'transpose'];
var createLyap = /* #__PURE__ */factory(name$10, dependencies$10, _ref => {
  var {
    typed,
    matrix,
    sylvester,
    multiply,
    transpose
  } = _ref;
  /**
   *
   * Solves the Continuous-time Lyapunov equation AP+PA'+Q=0 for P, where
   * Q is an input matrix. When Q is symmetric, P is also symmetric. Notice
   * that different equivalent definitions exist for the Continuous-time
   * Lyapunov equation.
   * https://en.wikipedia.org/wiki/Lyapunov_equation
   *
   * Syntax:
   *
   *     math.lyap(A, Q)
   *
   * Examples:
   *
   *     const A = [[-2, 0], [1, -4]]
   *     const Q = [[3, 1], [1, 3]]
   *     const P = math.lyap(A, Q)
   *
   * See also:
   *
   *     sylvester, schur
   *
   * @param {Matrix | Array} A  Matrix A
   * @param {Matrix | Array} Q  Matrix Q
   * @return {Matrix | Array} Matrix P solution to the Continuous-time Lyapunov equation AP+PA'=Q
   */
  return typed(name$10, {
    'Matrix, Matrix': function MatrixMatrix(A, Q) {
      return sylvester(A, transpose(A), multiply(-1, Q));
    },
    'Array, Matrix': function ArrayMatrix(A, Q) {
      return sylvester(matrix(A), transpose(matrix(A)), multiply(-1, Q));
    },
    'Matrix, Array': function MatrixArray(A, Q) {
      return sylvester(A, transpose(matrix(A)), matrix(multiply(-1, Q)));
    },
    'Array, Array': function ArrayArray(A, Q) {
      return sylvester(matrix(A), transpose(matrix(A)), matrix(multiply(-1, Q))).toArray();
    }
  });
});

var name$$ = 'divide';
var dependencies$$ = ['typed', 'matrix', 'multiply', 'equalScalar', 'divideScalar', 'inv'];
var createDivide = /* #__PURE__ */factory(name$$, dependencies$$, _ref => {
  var {
    typed,
    matrix,
    multiply,
    equalScalar,
    divideScalar,
    inv
  } = _ref;
  var matAlgo11xS0s = createMatAlgo11xS0s({
    typed,
    equalScalar
  });
  var matAlgo14xDs = createMatAlgo14xDs({
    typed
  });

  /**
   * Divide two values, `x / y`.
   * To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`.
   *
   * Syntax:
   *
   *    math.divide(x, y)
   *
   * Examples:
   *
   *    math.divide(2, 3)            // returns number 0.6666666666666666
   *
   *    const a = math.complex(5, 14)
   *    const b = math.complex(4, 1)
   *    math.divide(a, b)            // returns Complex 2 + 3i
   *
   *    const c = [[7, -6], [13, -4]]
   *    const d = [[1, 2], [4, 3]]
   *    math.divide(c, d)            // returns Array [[-9, 4], [-11, 6]]
   *
   *    const e = math.unit('18 km')
   *    math.divide(e, 4.5)          // returns Unit 4 km
   *
   * See also:
   *
   *    multiply
   *
   * @param  {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix} x   Numerator
   * @param  {number | BigNumber | bigint | Fraction | Complex | Array | Matrix} y          Denominator
   * @return {number | BigNumber | bigint | Fraction | Complex | Unit | Array | Matrix}                      Quotient, `x / y`
   */
  return typed('divide', extend({
    // we extend the signatures of divideScalar with signatures dealing with matrices

    'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(x, y) {
      // TODO: implement matrix right division using pseudo inverse
      // https://www.mathworks.nl/help/matlab/ref/mrdivide.html
      // https://www.gnu.org/software/octave/doc/interpreter/Arithmetic-Ops.html
      // https://stackoverflow.com/questions/12263932/how-does-gnu-octave-matrix-division-work-getting-unexpected-behaviour
      return multiply(x, inv(y));
    },
    'DenseMatrix, any': function DenseMatrixAny(x, y) {
      return matAlgo14xDs(x, y, divideScalar, false);
    },
    'SparseMatrix, any': function SparseMatrixAny(x, y) {
      return matAlgo11xS0s(x, y, divideScalar, false);
    },
    'Array, any': function ArrayAny(x, y) {
      // use matrix implementation
      return matAlgo14xDs(matrix(x), y, divideScalar, false).valueOf();
    },
    'any, Array | Matrix': function anyArrayMatrix(x, y) {
      return multiply(x, inv(y));
    }
  }, divideScalar.signatures));
});

var name$_ = 'distance';
var dependencies$_ = ['typed', 'addScalar', 'subtractScalar', 'divideScalar', 'multiplyScalar', 'deepEqual', 'sqrt', 'abs'];
var createDistance = /* #__PURE__ */factory(name$_, dependencies$_, _ref => {
  var {
    typed,
    addScalar,
    subtractScalar,
    multiplyScalar,
    divideScalar,
    deepEqual,
    sqrt,
    abs
  } = _ref;
  /**
    * Calculates:
    *    The eucledian distance between two points in N-dimensional spaces.
    *    Distance between point and a line in 2 and 3 dimensional spaces.
    *    Pairwise distance between a set of 2D or 3D points
    * NOTE:
    *    When substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c
    *    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)
    *
    * Syntax:
    *
    *    math.distance([x1,y1], [x2,y2])
    *    math.distance({pointOneX, pointOneY}, {pointTwoX, pointTwoY})
    *    math.distance([x1,y1,z1], [x2,y2,z2])
    *    math.distance({pointOneX, pointOneY, pointOneZ}, {pointTwoX, pointTwoY, pointTwoZ})
    *    math.distance([x1,y1,z1,a1], [x2,y2,z2,a2])
    *    math.distance([[x1,y1], [x2,y2], [x3,y3]])
    *    math.distance([[x1,y1,z1], [x2,y2,z2], [x3,y3,z3]])
    *    math.distance([pointX,pointY], [a,b,c])
    *    math.distance([pointX,pointY], [lineOnePtX,lineOnePtY], [lineTwoPtX,lineTwoPtY])
    *    math.distance({pointX, pointY}, {lineOnePtX, lineOnePtY}, {lineTwoPtX, lineTwoPtY})
    *    math.distance([pointX,pointY,pointZ], [x0, y0, z0, a, b, c])
    *    math.distance({pointX, pointY, pointZ}, {x0, y0, z0, a, b, c})
    *
    * Examples:
    *    math.distance([0,0], [4,4])                     // Returns 5.656854249492381
    *    math.distance(
    *     {pointOneX: 0, pointOneY: 0},
    *     {pointTwoX: 10, pointTwoY: 10})                // Returns 14.142135623730951
    *    math.distance([1, 0, 1], [4, -2, 2])            // Returns 3.7416573867739413
    *    math.distance(
    *     {pointOneX: 4, pointOneY: 5, pointOneZ: 8},
    *     {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9})    // Returns 3
    *    math.distance([1, 0, 1, 0], [0, -1, 0, -1])     // Returns 2
    *    math.distance([[1, 2], [1, 2], [1, 3]])         // Returns [0, 1, 1]
    *    math.distance([[1,2,4], [1,2,6], [8,1,3]])      // Returns [2, 7.14142842854285, 7.681145747868608]
    *    math.distance([10, 10], [8, 1, 3])              // Returns 11.535230316796387
    *    math.distance([0, 0], [3, 0], [0, 4])        // Returns 2.4
    *    math.distance(
    *     {pointX: 0, pointY: 0},
    *     {lineOnePtX: 3, lineOnePtY: 0},
    *     {lineTwoPtX: 0, lineTwoPtY: 4})                // Returns 2.4
    *    math.distance([2, 3, 1], [1, 1, 2, 5, 0, 1])    // Returns 2.3204774044612857
    *    math.distance(
    *     {pointX: 2, pointY: 3, pointZ: 1},
    *     {x0: 1, y0: 1, z0: 2, a: 5, b: 0, c: 1})       // Returns 2.3204774044612857
    *
    * @param {Array | Matrix | Object} x    Co-ordinates of first point
    * @param {Array | Matrix | Object} y    Co-ordinates of second point
    * @return {Number | BigNumber} Returns the distance from two/three points
  */
  return typed(name$_, {
    'Array, Array, Array': function ArrayArrayArray(x, y, z) {
      // Point to Line 2D (x=Point, y=LinePoint1, z=LinePoint2)
      if (x.length === 2 && y.length === 2 && z.length === 2) {
        if (!_2d(x)) {
          throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument');
        }
        if (!_2d(y)) {
          throw new TypeError('Array with 2 numbers or BigNumbers expected for second argument');
        }
        if (!_2d(z)) {
          throw new TypeError('Array with 2 numbers or BigNumbers expected for third argument');
        }
        if (deepEqual(y, z)) {
          throw new TypeError('LinePoint1 should not be same with LinePoint2');
        }
        var xCoeff = subtractScalar(z[1], y[1]);
        var yCoeff = subtractScalar(y[0], z[0]);
        var constant = subtractScalar(multiplyScalar(z[0], y[1]), multiplyScalar(y[0], z[1]));
        return _distancePointLine2D(x[0], x[1], xCoeff, yCoeff, constant);
      } else {
        throw new TypeError('Invalid Arguments: Try again');
      }
    },
    'Object, Object, Object': function ObjectObjectObject(x, y, z) {
      if (Object.keys(x).length === 2 && Object.keys(y).length === 2 && Object.keys(z).length === 2) {
        if (!_2d(x)) {
          throw new TypeError('Values of pointX and pointY should be numbers or BigNumbers');
        }
        if (!_2d(y)) {
          throw new TypeError('Values of lineOnePtX and lineOnePtY should be numbers or BigNumbers');
        }
        if (!_2d(z)) {
          throw new TypeError('Values of lineTwoPtX and lineTwoPtY should be numbers or BigNumbers');
        }
        if (deepEqual(_objectToArray(y), _objectToArray(z))) {
          throw new TypeError('LinePoint1 should not be same with LinePoint2');
        }
        if ('pointX' in x && 'pointY' in x && 'lineOnePtX' in y && 'lineOnePtY' in y && 'lineTwoPtX' in z && 'lineTwoPtY' in z) {
          var xCoeff = subtractScalar(z.lineTwoPtY, y.lineOnePtY);
          var yCoeff = subtractScalar(y.lineOnePtX, z.lineTwoPtX);
          var constant = subtractScalar(multiplyScalar(z.lineTwoPtX, y.lineOnePtY), multiplyScalar(y.lineOnePtX, z.lineTwoPtY));
          return _distancePointLine2D(x.pointX, x.pointY, xCoeff, yCoeff, constant);
        } else {
          throw new TypeError('Key names do not match');
        }
      } else {
        throw new TypeError('Invalid Arguments: Try again');
      }
    },
    'Array, Array': function ArrayArray(x, y) {
      // Point to Line 2D (x=[pointX, pointY], y=[x-coeff, y-coeff, const])
      if (x.length === 2 && y.length === 3) {
        if (!_2d(x)) {
          throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument');
        }
        if (!_3d(y)) {
          throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument');
        }
        return _distancePointLine2D(x[0], x[1], y[0], y[1], y[2]);
      } else if (x.length === 3 && y.length === 6) {
        // Point to Line 3D
        if (!_3d(x)) {
          throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument');
        }
        if (!_parametricLine(y)) {
          throw new TypeError('Array with 6 numbers or BigNumbers expected for second argument');
        }
        return _distancePointLine3D(x[0], x[1], x[2], y[0], y[1], y[2], y[3], y[4], y[5]);
      } else if (x.length === y.length && x.length > 0) {
        // Point to Point N-dimensions
        if (!_containsOnlyNumbers(x)) {
          throw new TypeError('All values of an array should be numbers or BigNumbers');
        }
        if (!_containsOnlyNumbers(y)) {
          throw new TypeError('All values of an array should be numbers or BigNumbers');
        }
        return _euclideanDistance(x, y);
      } else {
        throw new TypeError('Invalid Arguments: Try again');
      }
    },
    'Object, Object': function ObjectObject(x, y) {
      if (Object.keys(x).length === 2 && Object.keys(y).length === 3) {
        if (!_2d(x)) {
          throw new TypeError('Values of pointX and pointY should be numbers or BigNumbers');
        }
        if (!_3d(y)) {
          throw new TypeError('Values of xCoeffLine, yCoeffLine and constant should be numbers or BigNumbers');
        }
        if ('pointX' in x && 'pointY' in x && 'xCoeffLine' in y && 'yCoeffLine' in y && 'constant' in y) {
          return _distancePointLine2D(x.pointX, x.pointY, y.xCoeffLine, y.yCoeffLine, y.constant);
        } else {
          throw new TypeError('Key names do not match');
        }
      } else if (Object.keys(x).length === 3 && Object.keys(y).length === 6) {
        // Point to Line 3D
        if (!_3d(x)) {
          throw new TypeError('Values of pointX, pointY and pointZ should be numbers or BigNumbers');
        }
        if (!_parametricLine(y)) {
          throw new TypeError('Values of x0, y0, z0, a, b and c should be numbers or BigNumbers');
        }
        if ('pointX' in x && 'pointY' in x && 'x0' in y && 'y0' in y && 'z0' in y && 'a' in y && 'b' in y && 'c' in y) {
          return _distancePointLine3D(x.pointX, x.pointY, x.pointZ, y.x0, y.y0, y.z0, y.a, y.b, y.c);
        } else {
          throw new TypeError('Key names do not match');
        }
      } else if (Object.keys(x).length === 2 && Object.keys(y).length === 2) {
        // Point to Point 2D
        if (!_2d(x)) {
          throw new TypeError('Values of pointOneX and pointOneY should be numbers or BigNumbers');
        }
        if (!_2d(y)) {
          throw new TypeError('Values of pointTwoX and pointTwoY should be numbers or BigNumbers');
        }
        if ('pointOneX' in x && 'pointOneY' in x && 'pointTwoX' in y && 'pointTwoY' in y) {
          return _euclideanDistance([x.pointOneX, x.pointOneY], [y.pointTwoX, y.pointTwoY]);
        } else {
          throw new TypeError('Key names do not match');
        }
      } else if (Object.keys(x).length === 3 && Object.keys(y).length === 3) {
        // Point to Point 3D
        if (!_3d(x)) {
          throw new TypeError('Values of pointOneX, pointOneY and pointOneZ should be numbers or BigNumbers');
        }
        if (!_3d(y)) {
          throw new TypeError('Values of pointTwoX, pointTwoY and pointTwoZ should be numbers or BigNumbers');
        }
        if ('pointOneX' in x && 'pointOneY' in x && 'pointOneZ' in x && 'pointTwoX' in y && 'pointTwoY' in y && 'pointTwoZ' in y) {
          return _euclideanDistance([x.pointOneX, x.pointOneY, x.pointOneZ], [y.pointTwoX, y.pointTwoY, y.pointTwoZ]);
        } else {
          throw new TypeError('Key names do not match');
        }
      } else {
        throw new TypeError('Invalid Arguments: Try again');
      }
    },
    Array: function Array(arr) {
      if (!_pairwise(arr)) {
        throw new TypeError('Incorrect array format entered for pairwise distance calculation');
      }
      return _distancePairwise(arr);
    }
  });
  function _isNumber(a) {
    // distance supports numbers and bignumbers
    return typeof a === 'number' || isBigNumber(a);
  }
  function _2d(a) {
    // checks if the number of arguments are correct in count and are valid (should be numbers)
    if (a.constructor !== Array) {
      a = _objectToArray(a);
    }
    return _isNumber(a[0]) && _isNumber(a[1]);
  }
  function _3d(a) {
    // checks if the number of arguments are correct in count and are valid (should be numbers)
    if (a.constructor !== Array) {
      a = _objectToArray(a);
    }
    return _isNumber(a[0]) && _isNumber(a[1]) && _isNumber(a[2]);
  }
  function _containsOnlyNumbers(a) {
    // checks if the number of arguments are correct in count and are valid (should be numbers)
    if (!Array.isArray(a)) {
      a = _objectToArray(a);
    }
    return a.every(_isNumber);
  }
  function _parametricLine(a) {
    if (a.constructor !== Array) {
      a = _objectToArray(a);
    }
    return _isNumber(a[0]) && _isNumber(a[1]) && _isNumber(a[2]) && _isNumber(a[3]) && _isNumber(a[4]) && _isNumber(a[5]);
  }
  function _objectToArray(o) {
    var keys = Object.keys(o);
    var a = [];
    for (var i = 0; i < keys.length; i++) {
      a.push(o[keys[i]]);
    }
    return a;
  }
  function _pairwise(a) {
    // checks for valid arguments passed to _distancePairwise(Array)
    if (a[0].length === 2 && _isNumber(a[0][0]) && _isNumber(a[0][1])) {
      if (a.some(aI => aI.length !== 2 || !_isNumber(aI[0]) || !_isNumber(aI[1]))) {
        return false;
      }
    } else if (a[0].length === 3 && _isNumber(a[0][0]) && _isNumber(a[0][1]) && _isNumber(a[0][2])) {
      if (a.some(aI => aI.length !== 3 || !_isNumber(aI[0]) || !_isNumber(aI[1]) || !_isNumber(aI[2]))) {
        return false;
      }
    } else {
      return false;
    }
    return true;
  }
  function _distancePointLine2D(x, y, a, b, c) {
    var num = abs(addScalar(addScalar(multiplyScalar(a, x), multiplyScalar(b, y)), c));
    var den = sqrt(addScalar(multiplyScalar(a, a), multiplyScalar(b, b)));
    return divideScalar(num, den);
  }
  function _distancePointLine3D(x, y, z, x0, y0, z0, a, b, c) {
    var num = [subtractScalar(multiplyScalar(subtractScalar(y0, y), c), multiplyScalar(subtractScalar(z0, z), b)), subtractScalar(multiplyScalar(subtractScalar(z0, z), a), multiplyScalar(subtractScalar(x0, x), c)), subtractScalar(multiplyScalar(subtractScalar(x0, x), b), multiplyScalar(subtractScalar(y0, y), a))];
    num = sqrt(addScalar(addScalar(multiplyScalar(num[0], num[0]), multiplyScalar(num[1], num[1])), multiplyScalar(num[2], num[2])));
    var den = sqrt(addScalar(addScalar(multiplyScalar(a, a), multiplyScalar(b, b)), multiplyScalar(c, c)));
    return divideScalar(num, den);
  }
  function _euclideanDistance(x, y) {
    var vectorSize = x.length;
    var result = 0;
    var diff = 0;
    for (var i = 0; i < vectorSize; i++) {
      diff = subtractScalar(x[i], y[i]);
      result = addScalar(multiplyScalar(diff, diff), result);
    }
    return sqrt(result);
  }
  function _distancePairwise(a) {
    var result = [];
    var pointA = [];
    var pointB = [];
    for (var i = 0; i < a.length - 1; i++) {
      for (var j = i + 1; j < a.length; j++) {
        if (a[0].length === 2) {
          pointA = [a[i][0], a[i][1]];
          pointB = [a[j][0], a[j][1]];
        } else if (a[0].length === 3) {
          pointA = [a[i][0], a[i][1], a[i][2]];
          pointB = [a[j][0], a[j][1], a[j][2]];
        }
        result.push(_euclideanDistance(pointA, pointB));
      }
    }
    return result;
  }
});

var name$Z = 'intersect';
var dependencies$Z = ['typed', 'config', 'abs', 'add', 'addScalar', 'matrix', 'multiply', 'multiplyScalar', 'divideScalar', 'subtract', 'smaller', 'equalScalar', 'flatten', 'isZero', 'isNumeric'];
var createIntersect = /* #__PURE__ */factory(name$Z, dependencies$Z, _ref => {
  var {
    typed,
    config,
    abs,
    add,
    addScalar,
    matrix,
    multiply,
    multiplyScalar,
    divideScalar,
    subtract,
    smaller,
    equalScalar,
    flatten,
    isZero,
    isNumeric
  } = _ref;
  /**
   * Calculates the point of intersection of two lines in two or three dimensions
   * and of a line and a plane in three dimensions. The inputs are in the form of
   * arrays or 1 dimensional matrices. The line intersection functions return null
   * if the lines do not meet.
   *
   * Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`.
   *
   * Syntax:
   *
   *    math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2)
   *    math.intersect(endPoint1, endPoint2, planeCoefficients)
   *
   * Examples:
   *
   *    math.intersect([0, 0], [10, 10], [10, 0], [0, 10])              // Returns [5, 5]
   *    math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0])  // Returns [5, 5, 0]
   *    math.intersect([1, 0, 1],  [4, -2, 2], [1, 1, 1, 6])            // Returns [7, -4, 3]
   *
   * @param  {Array | Matrix} w   Co-ordinates of first end-point of first line
   * @param  {Array | Matrix} x   Co-ordinates of second end-point of first line
   * @param  {Array | Matrix} y   Co-ordinates of first end-point of second line
   *                              OR Co-efficients of the plane's equation
   * @param  {Array | Matrix} z   Co-ordinates of second end-point of second line
   *                              OR undefined if the calculation is for line and plane
   * @return {Array}              Returns the point of intersection of lines/lines-planes
   */
  return typed('intersect', {
    'Array, Array, Array': _AAA,
    'Array, Array, Array, Array': _AAAA,
    'Matrix, Matrix, Matrix': function MatrixMatrixMatrix(x, y, plane) {
      var arr = _AAA(x.valueOf(), y.valueOf(), plane.valueOf());
      return arr === null ? null : matrix(arr);
    },
    'Matrix, Matrix, Matrix, Matrix': function MatrixMatrixMatrixMatrix(w, x, y, z) {
      // TODO: output matrix type should match input matrix type
      var arr = _AAAA(w.valueOf(), x.valueOf(), y.valueOf(), z.valueOf());
      return arr === null ? null : matrix(arr);
    }
  });
  function _AAA(x, y, plane) {
    x = _coerceArr(x);
    y = _coerceArr(y);
    plane = _coerceArr(plane);
    if (!_3d(x)) {
      throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument');
    }
    if (!_3d(y)) {
      throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument');
    }
    if (!_4d(plane)) {
      throw new TypeError('Array with 4 numbers expected as third argument');
    }
    return _intersectLinePlane(x[0], x[1], x[2], y[0], y[1], y[2], plane[0], plane[1], plane[2], plane[3]);
  }
  function _AAAA(w, x, y, z) {
    w = _coerceArr(w);
    x = _coerceArr(x);
    y = _coerceArr(y);
    z = _coerceArr(z);
    if (w.length === 2) {
      if (!_2d(w)) {
        throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument');
      }
      if (!_2d(x)) {
        throw new TypeError('Array with 2 numbers or BigNumbers expected for second argument');
      }
      if (!_2d(y)) {
        throw new TypeError('Array with 2 numbers or BigNumbers expected for third argument');
      }
      if (!_2d(z)) {
        throw new TypeError('Array with 2 numbers or BigNumbers expected for fourth argument');
      }
      return _intersect2d(w, x, y, z);
    } else if (w.length === 3) {
      if (!_3d(w)) {
        throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument');
      }
      if (!_3d(x)) {
        throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument');
      }
      if (!_3d(y)) {
        throw new TypeError('Array with 3 numbers or BigNumbers expected for third argument');
      }
      if (!_3d(z)) {
        throw new TypeError('Array with 3 numbers or BigNumbers expected for fourth argument');
      }
      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]);
    } else {
      throw new TypeError('Arrays with two or thee dimensional points expected');
    }
  }

  /** Coerce row and column 2-dim arrays to 1-dim array */
  function _coerceArr(arr) {
    // row matrix
    if (arr.length === 1) return arr[0];

    // column matrix
    if (arr.length > 1 && Array.isArray(arr[0])) {
      if (arr.every(el => Array.isArray(el) && el.length === 1)) return flatten(arr);
    }
    return arr;
  }
  function _2d(x) {
    return x.length === 2 && isNumeric(x[0]) && isNumeric(x[1]);
  }
  function _3d(x) {
    return x.length === 3 && isNumeric(x[0]) && isNumeric(x[1]) && isNumeric(x[2]);
  }
  function _4d(x) {
    return x.length === 4 && isNumeric(x[0]) && isNumeric(x[1]) && isNumeric(x[2]) && isNumeric(x[3]);
  }
  function _intersect2d(p1a, p1b, p2a, p2b) {
    var o1 = p1a;
    var o2 = p2a;
    var d1 = subtract(o1, p1b);
    var d2 = subtract(o2, p2b);
    var det = subtract(multiplyScalar(d1[0], d2[1]), multiplyScalar(d2[0], d1[1]));
    if (isZero(det)) return null;
    if (smaller(abs(det), config.relTol)) {
      return null;
    }
    var d20o11 = multiplyScalar(d2[0], o1[1]);
    var d21o10 = multiplyScalar(d2[1], o1[0]);
    var d20o21 = multiplyScalar(d2[0], o2[1]);
    var d21o20 = multiplyScalar(d2[1], o2[0]);
    var t = divideScalar(addScalar(subtract(subtract(d20o11, d21o10), d20o21), d21o20), det);
    return add(multiply(d1, t), o1);
  }
  function _intersect3dHelper(a, b, c, d, e, f, g, h, i, j, k, l) {
    // (a - b)*(c - d) + (e - f)*(g - h) + (i - j)*(k - l)
    var add1 = multiplyScalar(subtract(a, b), subtract(c, d));
    var add2 = multiplyScalar(subtract(e, f), subtract(g, h));
    var add3 = multiplyScalar(subtract(i, j), subtract(k, l));
    return addScalar(addScalar(add1, add2), add3);
  }
  function _intersect3d(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) {
    var d1343 = _intersect3dHelper(x1, x3, x4, x3, y1, y3, y4, y3, z1, z3, z4, z3);
    var d4321 = _intersect3dHelper(x4, x3, x2, x1, y4, y3, y2, y1, z4, z3, z2, z1);
    var d1321 = _intersect3dHelper(x1, x3, x2, x1, y1, y3, y2, y1, z1, z3, z2, z1);
    var d4343 = _intersect3dHelper(x4, x3, x4, x3, y4, y3, y4, y3, z4, z3, z4, z3);
    var d2121 = _intersect3dHelper(x2, x1, x2, x1, y2, y1, y2, y1, z2, z1, z2, z1);
    var numerator = subtract(multiplyScalar(d1343, d4321), multiplyScalar(d1321, d4343));
    var denominator = subtract(multiplyScalar(d2121, d4343), multiplyScalar(d4321, d4321));
    if (isZero(denominator)) return null;
    var ta = divideScalar(numerator, denominator);
    var tb = divideScalar(addScalar(d1343, multiplyScalar(ta, d4321)), d4343);
    var pax = addScalar(x1, multiplyScalar(ta, subtract(x2, x1)));
    var pay = addScalar(y1, multiplyScalar(ta, subtract(y2, y1)));
    var paz = addScalar(z1, multiplyScalar(ta, subtract(z2, z1)));
    var pbx = addScalar(x3, multiplyScalar(tb, subtract(x4, x3)));
    var pby = addScalar(y3, multiplyScalar(tb, subtract(y4, y3)));
    var pbz = addScalar(z3, multiplyScalar(tb, subtract(z4, z3)));
    if (equalScalar(pax, pbx) && equalScalar(pay, pby) && equalScalar(paz, pbz)) {
      return [pax, pay, paz];
    } else {
      return null;
    }
  }
  function _intersectLinePlane(x1, y1, z1, x2, y2, z2, x, y, z, c) {
    var x1x = multiplyScalar(x1, x);
    var x2x = multiplyScalar(x2, x);
    var y1y = multiplyScalar(y1, y);
    var y2y = multiplyScalar(y2, y);
    var z1z = multiplyScalar(z1, z);
    var z2z = multiplyScalar(z2, z);
    var numerator = subtract(subtract(subtract(c, x1x), y1y), z1z);
    var denominator = subtract(subtract(subtract(addScalar(addScalar(x2x, y2y), z2z), x1x), y1y), z1z);
    var t = divideScalar(numerator, denominator);
    var px = addScalar(x1, multiplyScalar(t, subtract(x2, x1)));
    var py = addScalar(y1, multiplyScalar(t, subtract(y2, y1)));
    var pz = addScalar(z1, multiplyScalar(t, subtract(z2, z1)));
    return [px, py, pz];
    // TODO: Add cases when line is parallel to the plane:
    //       (a) no intersection,
    //       (b) line contained in plane
  }
});

var name$Y = 'sum';
var dependencies$Y = ['typed', 'config', 'add', 'numeric'];
var createSum = /* #__PURE__ */factory(name$Y, dependencies$Y, _ref => {
  var {
    typed,
    config,
    add,
    numeric
  } = _ref;
  /**
   * Compute the sum of a matrix or a list with values.
   * In case of a multidimensional array or matrix, the sum of all
   * elements will be calculated.
   *
   * Syntax:
   *
   *     math.sum(a, b, c, ...)
   *     math.sum(A)
   *     math.sum(A, dimension)
   *
   * Examples:
   *
   *     math.sum(2, 1, 4, 3)               // returns 10
   *     math.sum([2, 1, 4, 3])             // returns 10
   *     math.sum([[2, 5], [4, 3], [1, 7]]) // returns 22
   *
   * See also:
   *
   *    mean, median, min, max, prod, std, variance, cumsum
   *
   * @param {... *} args  A single matrix or multiple scalar values
   * @return {*} The sum of all values
   */
  return typed(name$Y, {
    // sum([a, b, c, d, ...])
    'Array | Matrix': _sum,
    // sum([a, b, c, d, ...], dim)
    'Array | Matrix, number | BigNumber': _nsumDim,
    // sum(a, b, c, d, ...)
    '...': function _(args) {
      if (containsCollections(args)) {
        throw new TypeError('Scalar values expected in function sum');
      }
      return _sum(args);
    }
  });

  /**
   * Recursively calculate the sum of an n-dimensional array
   * @param {Array | Matrix} array
   * @return {number} sum
   * @private
   */
  function _sum(array) {
    var sum;
    deepForEach(array, function (value) {
      try {
        sum = sum === undefined ? value : add(sum, value);
      } catch (err) {
        throw improveErrorMessage(err, 'sum', value);
      }
    });

    // make sure returning numeric value: parse a string into a numeric value
    if (sum === undefined) {
      sum = numeric(0, config.number);
    }
    if (typeof sum === 'string') {
      sum = numeric(sum, safeNumberType(sum, config));
    }
    return sum;
  }
  function _nsumDim(array, dim) {
    try {
      var sum = reduce(array, dim, add);
      return sum;
    } catch (err) {
      throw improveErrorMessage(err, 'sum');
    }
  }
});

var name$X = 'cumsum';
var dependencies$X = ['typed', 'add', 'unaryPlus'];
var createCumSum = /* #__PURE__ */factory(name$X, dependencies$X, _ref => {
  var {
    typed,
    add,
    unaryPlus
  } = _ref;
  /**
   * Compute the cumulative sum of a matrix or a list with values.
   * In case of a (multi dimensional) array or matrix, the cumulative sums
   * along a specified dimension (defaulting to the first) will be calculated.
   *
   * Syntax:
   *
   *     math.cumsum(a, b, c, ...)
   *     math.cumsum(A)
   *
   * Examples:
   *
   *     math.cumsum(2, 1, 4, 3)               // returns [2, 3, 7, 10]
   *     math.cumsum([2, 1, 4, 3])             // returns [2, 3, 7, 10]
   *     math.cumsum([[1, 2], [3, 4]])         // returns [[1, 2], [4, 6]]
   *     math.cumsum([[1, 2], [3, 4]], 0)      // returns [[1, 2], [4, 6]]
   *     math.cumsum([[1, 2], [3, 4]], 1)      // returns [[1, 3], [3, 7]]
   *     math.cumsum([[2, 5], [4, 3], [1, 7]]) // returns [[2, 5], [6, 8], [7, 15]]
   *
   * See also:
   *
   *    mean, median, min, max, prod, std, variance, sum
   *
   * @param {... *} args  A single matrix or or multiple scalar values
   * @return {*} The cumulative sum of all values
   */
  return typed(name$X, {
    // sum([a, b, c, d, ...])
    Array: _cumsum,
    Matrix: function Matrix(matrix) {
      return matrix.create(_cumsum(matrix.valueOf()));
    },
    // sum([a, b, c, d, ...], dim)
    'Array, number | BigNumber': _ncumSumDim,
    'Matrix, number | BigNumber': function MatrixNumberBigNumber(matrix, dim) {
      return matrix.create(_ncumSumDim(matrix.valueOf(), dim));
    },
    // cumsum(a, b, c, d, ...)
    '...': function _(args) {
      if (containsCollections(args)) {
        throw new TypeError('All values expected to be scalar in function cumsum');
      }
      return _cumsum(args);
    }
  });

  /**
     * Recursively calculate the cumulative sum of an n-dimensional array
     * @param {Array} array
     * @return {number} cumsum
     * @private
     */
  function _cumsum(array) {
    try {
      return _cumsummap(array);
    } catch (err) {
      throw improveErrorMessage(err, name$X);
    }
  }
  function _cumsummap(array) {
    if (array.length === 0) {
      return [];
    }
    var sums = [unaryPlus(array[0])]; // unaryPlus converts to number if need be
    for (var i = 1; i < array.length; ++i) {
      // Must use add below and not addScalar for the case of summing a
      // 2+-dimensional array along the 0th dimension (the row vectors,
      // or higher-d analogues, are literally added to each other).
      sums.push(add(sums[i - 1], array[i]));
    }
    return sums;
  }
  function _ncumSumDim(array, dim) {
    var size = arraySize(array);
    if (dim < 0 || dim >= size.length) {
      // TODO: would be more clear when throwing a DimensionError here
      throw new IndexError(dim, size.length);
    }
    try {
      return _cumsumDimensional(array, dim);
    } catch (err) {
      throw improveErrorMessage(err, name$X);
    }
  }

  /* Possible TODO: Refactor _reduce in collection.js to be able to work here as well */
  function _cumsumDimensional(mat, dim) {
    var i, ret, tran;
    if (dim <= 0) {
      var initialValue = mat[0][0];
      if (!Array.isArray(initialValue)) {
        return _cumsummap(mat);
      } else {
        tran = _switch$1(mat);
        ret = [];
        for (i = 0; i < tran.length; i++) {
          ret[i] = _cumsumDimensional(tran[i], dim - 1);
        }
        return ret;
      }
    } else {
      ret = [];
      for (i = 0; i < mat.length; i++) {
        ret[i] = _cumsumDimensional(mat[i], dim - 1);
      }
      return ret;
    }
  }
});

var name$W = 'mean';
var dependencies$W = ['typed', 'add', 'divide'];
var createMean = /* #__PURE__ */factory(name$W, dependencies$W, _ref => {
  var {
    typed,
    add,
    divide
  } = _ref;
  /**
   * Compute the mean value of matrix or a list with values.
   * In case of a multidimensional array, the mean of the flattened array
   * will be calculated. When `dim` is provided, the maximum over the selected
   * dimension will be calculated. Parameter `dim` is zero-based.
   *
   * Syntax:
   *
   *     math.mean(a, b, c, ...)
   *     math.mean(A)
   *     math.mean(A, dimension)
   *
   * Examples:
   *
   *     math.mean(2, 1, 4, 3)                     // returns 2.5
   *     math.mean([1, 2.7, 3.2, 4])               // returns 2.725
   *
   *     math.mean([[2, 5], [6, 3], [1, 7]], 0)    // returns [3, 5]
   *     math.mean([[2, 5], [6, 3], [1, 7]], 1)    // returns [3.5, 4.5, 4]
   *
   * See also:
   *
   *     median, min, max, sum, prod, std, variance
   *
   * @param {... *} args  A single matrix or or multiple scalar values
   * @return {*} The mean of all values
   */
  return typed(name$W, {
    // mean([a, b, c, d, ...])
    'Array | Matrix': _mean,
    // mean([a, b, c, d, ...], dim)
    'Array | Matrix, number | BigNumber': _nmeanDim,
    // mean(a, b, c, d, ...)
    '...': function _(args) {
      if (containsCollections(args)) {
        throw new TypeError('Scalar values expected in function mean');
      }
      return _mean(args);
    }
  });

  /**
   * Calculate the mean value in an n-dimensional array, returning a
   * n-1 dimensional array
   * @param {Array} array
   * @param {number} dim
   * @return {number} mean
   * @private
   */
  function _nmeanDim(array, dim) {
    try {
      var sum = reduce(array, dim, add);
      var s = Array.isArray(array) ? arraySize(array) : array.size();
      return divide(sum, s[dim]);
    } catch (err) {
      throw improveErrorMessage(err, 'mean');
    }
  }

  /**
   * Recursively calculate the mean value in an n-dimensional array
   * @param {Array} array
   * @return {number} mean
   * @private
   */
  function _mean(array) {
    var sum;
    var num = 0;
    deepForEach(array, function (value) {
      try {
        sum = sum === undefined ? value : add(sum, value);
        num++;
      } catch (err) {
        throw improveErrorMessage(err, 'mean', value);
      }
    });
    if (num === 0) {
      throw new Error('Cannot calculate the mean of an empty array');
    }
    return divide(sum, num);
  }
});

var name$V = 'median';
var dependencies$V = ['typed', 'add', 'divide', 'compare', 'partitionSelect'];
var createMedian = /* #__PURE__ */factory(name$V, dependencies$V, _ref => {
  var {
    typed,
    add,
    divide,
    compare,
    partitionSelect
  } = _ref;
  /**
   * Recursively calculate the median of an n-dimensional array
   * @param {Array} array
   * @return {Number} median
   * @private
   */
  function _median(array) {
    try {
      array = flatten(array.valueOf());
      var num = array.length;
      if (num === 0) {
        throw new Error('Cannot calculate median of an empty array');
      }
      if (num % 2 === 0) {
        // even: return the average of the two middle values
        var mid = num / 2 - 1;
        var right = partitionSelect(array, mid + 1);

        // array now partitioned at mid + 1, take max of left part
        var left = array[mid];
        for (var i = 0; i < mid; ++i) {
          if (compare(array[i], left) > 0) {
            left = array[i];
          }
        }
        return middle2(left, right);
      } else {
        // odd: return the middle value
        var m = partitionSelect(array, (num - 1) / 2);
        return middle(m);
      }
    } catch (err) {
      throw improveErrorMessage(err, 'median');
    }
  }

  // helper function to type check the middle value of the array
  var middle = typed({
    'number | BigNumber | Complex | Unit': function numberBigNumberComplexUnit(value) {
      return value;
    }
  });

  // helper function to type check the two middle value of the array
  var middle2 = typed({
    'number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit': function numberBigNumberComplexUnitNumberBigNumberComplexUnit(left, right) {
      return divide(add(left, right), 2);
    }
  });

  /**
   * Compute the median of a matrix or a list with 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.
   * Supported types of values are: Number, BigNumber, Unit
   *
   * In case of a (multi dimensional) array or matrix, the median of all
   * elements will be calculated.
   *
   * Syntax:
   *
   *     math.median(a, b, c, ...)
   *     math.median(A)
   *
   * Examples:
   *
   *     math.median(5, 2, 7)        // returns 5
   *     math.median([3, -1, 5, 7])  // returns 4
   *
   * See also:
   *
   *     mean, min, max, sum, prod, std, variance, quantileSeq
   *
   * @param {... *} args  A single matrix or or multiple scalar values
   * @return {*} The median
   */
  return typed(name$V, {
    // median([a, b, c, d, ...])
    'Array | Matrix': _median,
    // median([a, b, c, d, ...], dim)
    'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) {
      // TODO: implement median(A, dim)
      throw new Error('median(A, dim) is not yet supported');
      // return reduce(arguments[0], arguments[1], ...)
    },
    // median(a, b, c, d, ...)
    '...': function _(args) {
      if (containsCollections(args)) {
        throw new TypeError('Scalar values expected in function median');
      }
      return _median(args);
    }
  });
});

var name$U = 'mad';
var dependencies$U = ['typed', 'abs', 'map', 'median', 'subtract'];
var createMad = /* #__PURE__ */factory(name$U, dependencies$U, _ref => {
  var {
    typed,
    abs,
    map,
    median,
    subtract
  } = _ref;
  /**
   * 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.
   *
   * Syntax:
   *
   *     math.mad(a, b, c, ...)
   *     math.mad(A)
   *
   * Examples:
   *
   *     math.mad(10, 20, 30)             // returns 10
   *     math.mad([1, 2, 3])              // returns 1
   *     math.mad([[1, 2, 3], [4, 5, 6]]) // returns 1.5
   *
   * See also:
   *
   *     median, mean, std, abs
   *
   * @param {Array | Matrix} array
   *                        A single matrix or multiple scalar values.
   * @return {*} The median absolute deviation.
   */
  return typed(name$U, {
    // mad([a, b, c, d, ...])
    'Array | Matrix': _mad,
    // mad(a, b, c, d, ...)
    '...': function _(args) {
      return _mad(args);
    }
  });
  function _mad(array) {
    array = flatten(array.valueOf());
    if (array.length === 0) {
      throw new Error('Cannot calculate median absolute deviation (mad) of an empty array');
    }
    try {
      var med = median(array);
      return median(map(array, function (value) {
        return abs(subtract(value, med));
      }));
    } catch (err) {
      if (err instanceof TypeError && err.message.includes('median')) {
        throw new TypeError(err.message.replace('median', 'mad'));
      } else {
        throw improveErrorMessage(err, 'mad');
      }
    }
  }
});

var DEFAULT_NORMALIZATION = 'unbiased';
var name$T = 'variance';
var dependencies$T = ['typed', 'add', 'subtract', 'multiply', 'divide', 'apply', 'isNaN'];
var createVariance = /* #__PURE__ */factory(name$T, dependencies$T, _ref => {
  var {
    typed,
    add,
    subtract,
    multiply,
    divide,
    apply,
    isNaN
  } = _ref;
  /**
   * Compute the variance of a matrix or a  list with values.
   * In case of a multidimensional array or matrix, the variance over all
   * elements will be calculated.
   *
   * Additionally, it is possible to compute the variance along the rows
   * or columns of a matrix by specifying the dimension as the second argument.
   *
   * Optionally, the type of normalization can be specified as the final
   * parameter. The parameter `normalization` can be one of the following values:
   *
   * - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
   * - 'uncorrected'        The sum of squared errors is divided by n
   * - 'biased'             The sum of squared errors is divided by (n + 1)
   *
   *
   * Note that older browser may not like the variable name `var`. In that
   * case, the function can be called as `math['var'](...)` instead of
   * `math.var(...)`.
   *
   * Syntax:
   *
   *     math.variance(a, b, c, ...)
   *     math.variance(A)
   *     math.variance(A, normalization)
   *     math.variance(A, dimension)
   *     math.variance(A, dimension, normalization)
   *
   * Examples:
   *
   *     math.variance(2, 4, 6)                     // returns 4
   *     math.variance([2, 4, 6, 8])                // returns 6.666666666666667
   *     math.variance([2, 4, 6, 8], 'uncorrected') // returns 5
   *     math.variance([2, 4, 6, 8], 'biased')      // returns 4
   *
   *     math.variance([[1, 2, 3], [4, 5, 6]])      // returns 3.5
   *     math.variance([[1, 2, 3], [4, 6, 8]], 0)   // returns [4.5, 8, 12.5]
   *     math.variance([[1, 2, 3], [4, 6, 8]], 1)   // returns [1, 4]
   *     math.variance([[1, 2, 3], [4, 6, 8]], 1, 'biased') // returns [0.5, 2]
   *
   * See also:
   *
   *    mean, median, max, min, prod, std, sum
   *
   * @param {Array | Matrix} array
   *                        A single matrix or or multiple scalar values
   * @param {string} [normalization='unbiased']
   *                        Determines how to normalize the variance.
   *                        Choose 'unbiased' (default), 'uncorrected', or 'biased'.
   * @param dimension {number | BigNumber}
   *                        Determines the axis to compute the variance for a matrix
   * @return {*} The variance
   */
  return typed(name$T, {
    // variance([a, b, c, d, ...])
    'Array | Matrix': function ArrayMatrix(array) {
      return _var(array, DEFAULT_NORMALIZATION);
    },
    // variance([a, b, c, d, ...], normalization)
    'Array | Matrix, string': _var,
    // variance([a, b, c, c, ...], dim)
    'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) {
      return _varDim(array, dim, DEFAULT_NORMALIZATION);
    },
    // variance([a, b, c, c, ...], dim, normalization)
    'Array | Matrix, number | BigNumber, string': _varDim,
    // variance(a, b, c, d, ...)
    '...': function _(args) {
      return _var(args, DEFAULT_NORMALIZATION);
    }
  });

  /**
   * Recursively calculate the variance of an n-dimensional array
   * @param {Array} array
   * @param {string} normalization
   *                        Determines how to normalize the variance:
   *                        - 'unbiased'    The sum of squared errors is divided by (n - 1)
   *                        - 'uncorrected' The sum of squared errors is divided by n
   *                        - 'biased'      The sum of squared errors is divided by (n + 1)
   * @return {number | BigNumber} variance
   * @private
   */
  function _var(array, normalization) {
    var sum;
    var num = 0;
    if (array.length === 0) {
      throw new SyntaxError('Function variance requires one or more parameters (0 provided)');
    }

    // calculate the mean and number of elements
    deepForEach(array, function (value) {
      try {
        sum = sum === undefined ? value : add(sum, value);
        num++;
      } catch (err) {
        throw improveErrorMessage(err, 'variance', value);
      }
    });
    if (num === 0) throw new Error('Cannot calculate variance of an empty array');
    var mean = divide(sum, num);

    // calculate the variance
    sum = undefined;
    deepForEach(array, function (value) {
      var diff = subtract(value, mean);
      sum = sum === undefined ? multiply(diff, diff) : add(sum, multiply(diff, diff));
    });
    if (isNaN(sum)) {
      return sum;
    }
    switch (normalization) {
      case 'uncorrected':
        return divide(sum, num);
      case 'biased':
        return divide(sum, num + 1);
      case 'unbiased':
        {
          var zero = isBigNumber(sum) ? sum.mul(0) : 0;
          return num === 1 ? zero : divide(sum, num - 1);
        }
      default:
        throw new Error('Unknown normalization "' + normalization + '". ' + 'Choose "unbiased" (default), "uncorrected", or "biased".');
    }
  }
  function _varDim(array, dim, normalization) {
    try {
      if (array.length === 0) {
        throw new SyntaxError('Function variance requires one or more parameters (0 provided)');
      }
      return apply(array, dim, x => _var(x, normalization));
    } catch (err) {
      throw improveErrorMessage(err, 'variance');
    }
  }
});

var name$S = 'quantileSeq';
var dependencies$S = ['typed', '?bignumber', 'add', 'subtract', 'divide', 'multiply', 'partitionSelect', 'compare', 'isInteger', 'smaller', 'smallerEq', 'larger'];
var createQuantileSeq = /* #__PURE__ */factory(name$S, dependencies$S, _ref => {
  var {
    typed,
    bignumber,
    add,
    subtract,
    divide,
    multiply,
    partitionSelect,
    compare,
    isInteger,
    smaller,
    smallerEq,
    larger
  } = _ref;
  var apply = createApply({
    typed,
    isInteger
  });

  /**
   * 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 probability are: Number, BigNumber
   *
   * In case of a multidimensional array or matrix, the prob order quantile
   * of all elements will be calculated.
   *
   * Syntax:
   *
   *     math.quantileSeq(A, prob[, sorted])
   *     math.quantileSeq(A, [prob1, prob2, ...][, sorted])
   *     math.quantileSeq(A, N[, sorted])
   *
   * Examples:
   *
   *     math.quantileSeq([3, -1, 5, 7], 0.5)         // returns 4
   *     math.quantileSeq([3, -1, 5, 7], [1/3, 2/3])  // returns [3, 5]
   *     math.quantileSeq([3, -1, 5, 7], 2)           // returns [3, 5]
   *     math.quantileSeq([-1, 3, 5, 7], 0.5, true)   // returns 4
   *
   * See also:
   *
   *     median, mean, min, max, sum, prod, std, variance
   *
   * @param {Array, Matrix} data                A single matrix or Array
   * @param {Number, BigNumber, Array} probOrN  prob is the order of the quantile, while N is
   *                                            the amount of evenly distributed steps of
   *                                            probabilities; only one of these options can
   *                                            be provided
   * @param {Boolean} sorted=false              is data sorted in ascending order
   * @return {Number, BigNumber, Unit, Array}   Quantile(s)
   */
  return typed(name$S, {
    'Array | Matrix, number | BigNumber': (data, p) => _quantileSeqProbNumber(data, p, false),
    'Array | Matrix, number | BigNumber, number': (data, prob, dim) => _quantileSeqDim(data, prob, false, dim, _quantileSeqProbNumber),
    'Array | Matrix, number | BigNumber, boolean': _quantileSeqProbNumber,
    'Array | Matrix, number | BigNumber, boolean, number': (data, prob, sorted, dim) => _quantileSeqDim(data, prob, sorted, dim, _quantileSeqProbNumber),
    'Array | Matrix, Array | Matrix': (data, p) => _quantileSeqProbCollection(data, p, false),
    'Array | Matrix, Array | Matrix, number': (data, prob, dim) => _quantileSeqDim(data, prob, false, dim, _quantileSeqProbCollection),
    'Array | Matrix, Array | Matrix, boolean': _quantileSeqProbCollection,
    'Array | Matrix, Array | Matrix, boolean, number': (data, prob, sorted, dim) => _quantileSeqDim(data, prob, sorted, dim, _quantileSeqProbCollection)
  });
  function _quantileSeqDim(data, prob, sorted, dim, fn) {
    return apply(data, dim, x => fn(x, prob, sorted));
  }
  function _quantileSeqProbNumber(data, probOrN, sorted) {
    var probArr;
    var dataArr = data.valueOf();
    if (smaller(probOrN, 0)) {
      throw new Error('N/prob must be non-negative');
    }
    if (smallerEq(probOrN, 1)) {
      // quantileSeq([a, b, c, d, ...], prob[,sorted])
      return isNumber(probOrN) ? _quantileSeq(dataArr, probOrN, sorted) : bignumber(_quantileSeq(dataArr, probOrN, sorted));
    }
    if (larger(probOrN, 1)) {
      // quantileSeq([a, b, c, d, ...], N[,sorted])
      if (!isInteger(probOrN)) {
        throw new Error('N must be a positive integer');
      }

      // largest possible Array length is 2^32-1
      // 2^32 < 10^15, thus safe conversion guaranteed
      if (larger(probOrN, 4294967295)) {
        throw new Error('N must be less than or equal to 2^32-1, as that is the maximum length of an Array');
      }
      var nPlusOne = add(probOrN, 1);
      probArr = [];
      for (var i = 0; smaller(i, probOrN); i++) {
        var prob = divide(i + 1, nPlusOne);
        probArr.push(_quantileSeq(dataArr, prob, sorted));
      }
      return isNumber(probOrN) ? probArr : bignumber(probArr);
    }
  }

  /**
   * Calculate the prob order quantile of an n-dimensional array.
   *
   * @param {Array, Matrix} array
   * @param {Array, Matrix} prob
   * @param {Boolean} sorted
   * @return {Number, BigNumber, Unit} prob order quantile
   * @private
   */

  function _quantileSeqProbCollection(data, probOrN, sorted) {
    var dataArr = data.valueOf();
    // quantileSeq([a, b, c, d, ...], [prob1, prob2, ...][,sorted])
    var probOrNArr = probOrN.valueOf();
    var probArr = [];
    for (var i = 0; i < probOrNArr.length; ++i) {
      probArr.push(_quantileSeq(dataArr, probOrNArr[i], sorted));
    }
    return probArr;
  }

  /**
   * Calculate the prob order quantile of an n-dimensional array.
   *
   * @param {Array} array
   * @param {Number, BigNumber} prob
   * @param {Boolean} sorted
   * @return {Number, BigNumber, Unit} prob order quantile
   * @private
   */
  function _quantileSeq(array, prob, sorted) {
    var flat = flatten(array);
    var len = flat.length;
    if (len === 0) {
      throw new Error('Cannot calculate quantile of an empty sequence');
    }
    var index = isNumber(prob) ? prob * (len - 1) : prob.times(len - 1);
    var integerPart = isNumber(prob) ? Math.floor(index) : index.floor().toNumber();
    var fracPart = isNumber(prob) ? index % 1 : index.minus(integerPart);
    if (isInteger(index)) {
      return sorted ? flat[index] : partitionSelect(flat, isNumber(prob) ? index : index.valueOf());
    }
    var left;
    var right;
    if (sorted) {
      left = flat[integerPart];
      right = flat[integerPart + 1];
    } else {
      right = partitionSelect(flat, integerPart + 1);

      // max of partition is kth largest
      left = flat[integerPart];
      for (var i = 0; i < integerPart; ++i) {
        if (compare(flat[i], left) > 0) {
          left = flat[i];
        }
      }
    }
    // Q(prob) = (1-f)*A[floor(index)] + f*A[floor(index)+1]
    return add(multiply(left, subtract(1, fracPart)), multiply(right, fracPart));
  }
});

var name$R = 'std';
var dependencies$R = ['typed', 'map', 'sqrt', 'variance'];
var createStd = /* #__PURE__ */factory(name$R, dependencies$R, _ref => {
  var {
    typed,
    map,
    sqrt,
    variance
  } = _ref;
  /**
   * Compute the standard deviation of a matrix or a  list with values.
   * The standard deviations is defined as the square root of the variance:
   * `std(A) = sqrt(variance(A))`.
   * In case of a (multi dimensional) array or matrix, the standard deviation
   * over all elements will be calculated by default, unless an axis is specified
   * in which case the standard deviation will be computed along that axis.
   *
   * Additionally, it is possible to compute the standard deviation along the rows
   * or columns of a matrix by specifying the dimension as the second argument.
   *
   * Optionally, the type of normalization can be specified as the final
   * parameter. The parameter `normalization` can be one of the following values:
   *
   * - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
   * - 'uncorrected'        The sum of squared errors is divided by n
   * - 'biased'             The sum of squared errors is divided by (n + 1)
   *
   *
   * Syntax:
   *
   *     math.std(a, b, c, ...)
   *     math.std(A)
   *     math.std(A, normalization)
   *     math.std(A, dimension)
   *     math.std(A, dimension, normalization)
   *
   * Examples:
   *
   *     math.std(2, 4, 6)                     // returns 2
   *     math.std([2, 4, 6, 8])                // returns 2.581988897471611
   *     math.std([2, 4, 6, 8], 'uncorrected') // returns 2.23606797749979
   *     math.std([2, 4, 6, 8], 'biased')      // returns 2
   *
   *     math.std([[1, 2, 3], [4, 5, 6]])      // returns 1.8708286933869707
   *     math.std([[1, 2, 3], [4, 6, 8]], 0)    // returns [2.1213203435596424, 2.8284271247461903, 3.5355339059327378]
   *     math.std([[1, 2, 3], [4, 6, 8]], 1)    // returns [1, 2]
   *     math.std([[1, 2, 3], [4, 6, 8]], 1, 'biased') // returns [0.7071067811865476, 1.4142135623730951]
   *
   * See also:
   *
   *    mean, median, max, min, prod, sum, variance
   *
   * @param {Array | Matrix} array
   *                        A single matrix or or multiple scalar values
   * @param {string} [normalization='unbiased']
   *                        Determines how to normalize the variance.
   *                        Choose 'unbiased' (default), 'uncorrected', or 'biased'.
   * @param dimension {number | BigNumber}
   *                        Determines the axis to compute the standard deviation for a matrix
   * @return {*} The standard deviation
   */
  return typed(name$R, {
    // std([a, b, c, d, ...])
    'Array | Matrix': _std,
    // std([a, b, c, d, ...], normalization)
    'Array | Matrix, string': _std,
    // std([a, b, c, c, ...], dim)
    'Array | Matrix, number | BigNumber': _std,
    // std([a, b, c, c, ...], dim, normalization)
    'Array | Matrix, number | BigNumber, string': _std,
    // std(a, b, c, d, ...)
    '...': function _(args) {
      return _std(args);
    }
  });
  function _std(array, normalization) {
    if (array.length === 0) {
      throw new SyntaxError('Function std requires one or more parameters (0 provided)');
    }
    try {
      var v = variance.apply(null, arguments);
      if (isCollection(v)) {
        return map(v, sqrt);
      } else {
        return sqrt(v);
      }
    } catch (err) {
      if (err instanceof TypeError && err.message.includes(' variance')) {
        throw new TypeError(err.message.replace(' variance', ' std'));
      } else {
        throw err;
      }
    }
  }
});

var name$Q = 'corr';
var dependencies$Q = ['typed', 'matrix', 'mean', 'sqrt', 'sum', 'add', 'subtract', 'multiply', 'pow', 'divide'];
var createCorr = /* #__PURE__ */factory(name$Q, dependencies$Q, _ref => {
  var {
    typed,
    matrix,
    sqrt,
    sum,
    add,
    subtract,
    multiply,
    pow,
    divide
  } = _ref;
  /**
   * Compute the correlation coefficient of a two list with values, For matrices, the matrix correlation coefficient is calculated.
   *
   * Syntax:
   *
   *     math.corr(A, B)
   *
   * Examples:
   *
   *     math.corr([1, 2, 3, 4, 5], [4, 5, 6, 7, 8])     // returns 1
   *     math.corr([1, 2.2, 3, 4.8, 5], [4, 5.3, 6.6, 7, 8])     //returns 0.9569941688503644
   *     math.corr([[1, 2.2, 3, 4.8, 5], [4, 5.3, 6.6, 7, 8]],[[1, 2.2, 3, 4.8, 5], [4, 5.3, 6.6, 7, 8]])   // returns [1,1]
   *
   * See also:
   *
   *     median, mean, min, max, sum, prod, std, variance
   *
   * @param {Array | Matrix} A The first array or matrix to compute correlation coefficient
   * @param {Array | Matrix} B The second array or matrix to compute correlation coefficient
   * @return {*} The correlation coefficient
   */
  return typed(name$Q, {
    'Array, Array': function ArrayArray(A, B) {
      return _corr(A, B);
    },
    'Matrix, Matrix': function MatrixMatrix(A, B) {
      var res = _corr(A.toArray(), B.toArray());
      return Array.isArray(res) ? matrix(res) : res;
    }
  });
  /**
   * Calculate the correlation coefficient between two arrays or matrices.
   * @param {Array | Matrix} A
   * @param {Array | Matrix} B
   * @return {*} correlation coefficient
   * @private
   */
  function _corr(A, B) {
    var correlations = [];
    if (Array.isArray(A[0]) && Array.isArray(B[0])) {
      if (A.length !== B.length) {
        throw new SyntaxError('Dimension mismatch. Array A and B must have the same length.');
      }
      for (var i = 0; i < A.length; i++) {
        if (A[i].length !== B[i].length) {
          throw new SyntaxError('Dimension mismatch. Array A and B must have the same number of elements.');
        }
        correlations.push(correlation(A[i], B[i]));
      }
      return correlations;
    } else {
      if (A.length !== B.length) {
        throw new SyntaxError('Dimension mismatch. Array A and B must have the same number of elements.');
      }
      return correlation(A, B);
    }
  }
  function correlation(A, B) {
    var n = A.length;
    var sumX = sum(A);
    var sumY = sum(B);
    var sumXY = A.reduce((acc, x, index) => add(acc, multiply(x, B[index])), 0);
    var sumXSquare = sum(A.map(x => pow(x, 2)));
    var sumYSquare = sum(B.map(y => pow(y, 2)));
    var numerator = subtract(multiply(n, sumXY), multiply(sumX, sumY));
    var denominator = sqrt(multiply(subtract(multiply(n, sumXSquare), pow(sumX, 2)), subtract(multiply(n, sumYSquare), pow(sumY, 2))));
    return divide(numerator, denominator);
  }
});

var name$P = 'combinations';
var dependencies$P = ['typed'];
var createCombinations = /* #__PURE__ */factory(name$P, dependencies$P, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Compute the number of ways of picking `k` unordered outcomes from `n`
   * possibilities.
   *
   * Combinations only takes integer arguments.
   * The following condition must be enforced: k <= n.
   *
   * Syntax:
   *
   *     math.combinations(n, k)
   *
   * Examples:
   *
   *    math.combinations(7, 5) // returns 21
   *
   * See also:
   *
   *    combinationsWithRep, permutations, factorial
   *
   * @param {number | BigNumber} n    Total number of objects in the set
   * @param {number | BigNumber} k    Number of objects in the subset
   * @return {number | BigNumber}     Number of possible combinations.
   */
  return typed(name$P, {
    'number, number': combinationsNumber,
    'BigNumber, BigNumber': function BigNumberBigNumber(n, k) {
      var BigNumber = n.constructor;
      var result, i;
      var nMinusk = n.minus(k);
      var one = new BigNumber(1);
      if (!isPositiveInteger$2(n) || !isPositiveInteger$2(k)) {
        throw new TypeError('Positive integer value expected in function combinations');
      }
      if (k.gt(n)) {
        throw new TypeError('k must be less than n in function combinations');
      }
      result = one;
      if (k.lt(nMinusk)) {
        for (i = one; i.lte(nMinusk); i = i.plus(one)) {
          result = result.times(k.plus(i)).dividedBy(i);
        }
      } else {
        for (i = one; i.lte(k); i = i.plus(one)) {
          result = result.times(nMinusk.plus(i)).dividedBy(i);
        }
      }
      return result;
    }

    // TODO: implement support for collection in combinations
  });
});

/**
 * Test whether BigNumber n is a positive integer
 * @param {BigNumber} n
 * @returns {boolean} isPositiveInteger
 */
function isPositiveInteger$2(n) {
  return n.isInteger() && n.gte(0);
}

var name$O = 'combinationsWithRep';
var dependencies$O = ['typed'];
var createCombinationsWithRep = /* #__PURE__ */factory(name$O, dependencies$O, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Compute the number of ways of picking `k` unordered outcomes from `n`
   * possibilities, allowing individual outcomes to be repeated more than once.
   *
   * CombinationsWithRep only takes integer arguments.
   * The following condition must be enforced: k <= n + k -1.
   *
   * Syntax:
   *
   *     math.combinationsWithRep(n, k)
   *
   * Examples:
   *
   *    math.combinationsWithRep(7, 5) // returns 462
   *
   * See also:
   *
   *    combinations, permutations, factorial
   *
   * @param {number | BigNumber} n    Total number of objects in the set
   * @param {number | BigNumber} k    Number of objects in the subset
   * @return {number | BigNumber}     Number of possible combinations with replacement.
   */
  return typed(name$O, {
    'number, number': function numberNumber(n, k) {
      if (!isInteger(n) || n < 0) {
        throw new TypeError('Positive integer value expected in function combinationsWithRep');
      }
      if (!isInteger(k) || k < 0) {
        throw new TypeError('Positive integer value expected in function combinationsWithRep');
      }
      if (n < 1) {
        throw new TypeError('k must be less than or equal to n + k - 1');
      }
      if (k < n - 1) {
        var _prodrange = product(n, n + k - 1);
        return _prodrange / product(1, k);
      }
      var prodrange = product(k + 1, n + k - 1);
      return prodrange / product(1, n - 1);
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(n, k) {
      var BigNumber = n.constructor;
      var result, i;
      var one = new BigNumber(1);
      var nMinusOne = n.minus(one);
      if (!isPositiveInteger$1(n) || !isPositiveInteger$1(k)) {
        throw new TypeError('Positive integer value expected in function combinationsWithRep');
      }
      if (n.lt(one)) {
        throw new TypeError('k must be less than or equal to n + k - 1 in function combinationsWithRep');
      }
      result = one;
      if (k.lt(nMinusOne)) {
        for (i = one; i.lte(nMinusOne); i = i.plus(one)) {
          result = result.times(k.plus(i)).dividedBy(i);
        }
      } else {
        for (i = one; i.lte(k); i = i.plus(one)) {
          result = result.times(nMinusOne.plus(i)).dividedBy(i);
        }
      }
      return result;
    }
  });
});

/**
 * Test whether BigNumber n is a positive integer
 * @param {BigNumber} n
 * @returns {boolean} isPositiveInteger
 */
function isPositiveInteger$1(n) {
  return n.isInteger() && n.gte(0);
}

var name$N = 'gamma';
var dependencies$N = ['typed', 'config', 'multiplyScalar', 'pow', 'BigNumber', 'Complex'];
var createGamma = /* #__PURE__ */factory(name$N, dependencies$N, _ref => {
  var {
    typed,
    config,
    multiplyScalar,
    pow,
    BigNumber: _BigNumber,
    Complex
  } = _ref;
  /**
   * Compute the gamma function of a value using Lanczos approximation for
   * small values, and an extended Stirling approximation for large values.
   *
   * To avoid confusion with the matrix Gamma function, this function does
   * not apply to matrices.
   *
   * Syntax:
   *
   *    math.gamma(n)
   *
   * Examples:
   *
   *    math.gamma(5)       // returns 24
   *    math.gamma(-0.5)    // returns -3.5449077018110335
   *    math.gamma(math.i)  // returns -0.15494982830180973 - 0.49801566811835596i
   *
   * See also:
   *
   *    combinations, factorial, permutations
   *
   * @param {number | BigNumber | Complex} n   A real or complex number
   * @return {number | BigNumber | Complex}    The gamma of `n`
   */

  function gammaComplex(n) {
    if (n.im === 0) {
      return gammaNumber(n.re);
    }

    // Lanczos approximation doesn't work well with real part lower than 0.5
    // So reflection formula is required
    if (n.re < 0.5) {
      // Euler's reflection formula
      // gamma(1-z) * gamma(z) = PI / sin(PI * z)
      // real part of Z should not be integer [sin(PI) == 0 -> 1/0 - undefined]
      // thanks to imperfect sin implementation sin(PI * n) != 0
      // we can safely use it anyway
      var _t = new Complex(1 - n.re, -n.im);
      var r = new Complex(Math.PI * n.re, Math.PI * n.im);
      return new Complex(Math.PI).div(r.sin()).div(gammaComplex(_t));
    }

    // Lanczos approximation
    // z -= 1
    n = new Complex(n.re - 1, n.im);

    // x = gammaPval[0]
    var x = new Complex(gammaP[0], 0);
    // for (i, gammaPval) in enumerate(gammaP):
    for (var i = 1; i < gammaP.length; ++i) {
      // x += gammaPval / (z + i)
      var gammaPval = new Complex(gammaP[i], 0);
      x = x.add(gammaPval.div(n.add(i)));
    }
    // t = z + gammaG + 0.5
    var t = new Complex(n.re + gammaG + 0.5, n.im);

    // y = sqrt(2 * pi) * t ** (z + 0.5) * exp(-t) * x
    var twoPiSqrt = Math.sqrt(2 * Math.PI);
    var tpow = t.pow(n.add(0.5));
    var expt = t.neg().exp();

    // y = [x] * [sqrt(2 * pi)] * [t ** (z + 0.5)] * [exp(-t)]
    return x.mul(twoPiSqrt).mul(tpow).mul(expt);
  }
  return typed(name$N, {
    number: gammaNumber,
    Complex: gammaComplex,
    BigNumber: function BigNumber(n) {
      if (n.isInteger()) {
        return n.isNegative() || n.isZero() ? new _BigNumber(Infinity) : bigFactorial(n.minus(1));
      }
      if (!n.isFinite()) {
        return new _BigNumber(n.isNegative() ? NaN : Infinity);
      }
      throw new Error('Integer BigNumber expected');
    }
  });

  /**
   * Calculate factorial for a BigNumber
   * @param {BigNumber} n
   * @returns {BigNumber} Returns the factorial of n
   */
  function bigFactorial(n) {
    if (n < 8) {
      return new _BigNumber([1, 1, 2, 6, 24, 120, 720, 5040][n]);
    }
    var precision = config.precision + (Math.log(n.toNumber()) | 0);
    var Big = _BigNumber.clone({
      precision
    });
    if (n % 2 === 1) {
      return n.times(bigFactorial(new _BigNumber(n - 1)));
    }
    var p = n;
    var prod = new Big(n);
    var sum = n.toNumber();
    while (p > 2) {
      p -= 2;
      sum += p;
      prod = prod.times(sum);
    }
    return new _BigNumber(prod.toPrecision(_BigNumber.precision));
  }
});

/* eslint-disable no-loss-of-precision */
var name$M = 'lgamma';
var dependencies$M = ['Complex', 'typed'];
var createLgamma = /* #__PURE__ */factory(name$M, dependencies$M, _ref => {
  var {
    Complex,
    typed
  } = _ref;
  // Stirling series is non-convergent, we need to use the recurrence `lgamma(z) = lgamma(z+1) - log z` to get
  // sufficient accuracy.
  //
  // These two values are copied from Scipy implementation:
  // https://github.com/scipy/scipy/blob/v1.8.0/scipy/special/_loggamma.pxd#L37
  var SMALL_RE = 7;
  var SMALL_IM = 7;

  /**
   * The coefficients are B[2*n]/(2*n*(2*n - 1)) where B[2*n] is the (2*n)th Bernoulli number. See (1.1) in [1].
   *
   * If you cannot access the paper, can also get these values from the formula in [2].
   *
   *    1 /     12 = 0.00833333333333333333333333333333
   *    1 /    360 = 0.00277777777777777777777777777778
   * ...
   * 3617 / 133400 = 0.02955065359477124183006535947712
   */
  var coeffs = [-2.955065359477124183e-2, 6.4102564102564102564e-3, -1.9175269175269175269e-3, 8.4175084175084175084e-4, -5.952380952380952381e-4, 7.9365079365079365079e-4, -2.7777777777777777778e-3, 8.3333333333333333333e-2];

  /**
   * Logarithm of the gamma function for real, positive numbers and complex numbers,
   * using Lanczos approximation for numbers and Stirling series for complex numbers.
   *
   * Syntax:
   *
   *    math.lgamma(n)
   *
   * Examples:
   *
   *    math.lgamma(5)       // returns 3.178053830347945
   *    math.lgamma(0)       // returns Infinity
   *    math.lgamma(-0.5)    // returns NaN
   *    math.lgamma(math.i)  // returns -0.6509231993018536 - 1.8724366472624294i
   *
   * See also:
   *
   *    gamma
   *
   * @param {number | Complex} n   A real or complex number
   * @return {number | Complex}    The log gamma of `n`
   */
  return typed(name$M, {
    number: lgammaNumber,
    Complex: lgammaComplex,
    BigNumber: function BigNumber() {
      throw new Error("mathjs doesn't yet provide an implementation of the algorithm lgamma for BigNumber");
    }
  });
  function lgammaComplex(n) {
    var TWOPI = 6.2831853071795864769252842; // 2*pi
    var LOGPI = 1.1447298858494001741434262; // log(pi)

    var REFLECTION = 0.1;
    if (n.isNaN()) {
      return new Complex(NaN, NaN);
    } else if (n.im === 0) {
      return new Complex(lgammaNumber(n.re), 0);
    } else if (n.re >= SMALL_RE || Math.abs(n.im) >= SMALL_IM) {
      return lgammaStirling(n);
    } else if (n.re <= REFLECTION) {
      // Reflection formula. see Proposition 3.1 in [1]
      var tmp = copysign(TWOPI, n.im) * Math.floor(0.5 * n.re + 0.25);
      var a = n.mul(Math.PI).sin().log();
      var b = lgammaComplex(new Complex(1 - n.re, -n.im));
      return new Complex(LOGPI, tmp).sub(a).sub(b);
    } else if (n.im >= 0) {
      return lgammaRecurrence(n);
    } else {
      return lgammaRecurrence(n.conjugate()).conjugate();
    }
  }
  function lgammaStirling(z) {
    // formula ref in [2]
    // computation ref:
    // https://github.com/scipy/scipy/blob/v1.8.0/scipy/special/_loggamma.pxd#L101

    // left part

    // x (log(x) - 1) + 1/2 (log(2PI) - log(x))
    // => (x - 0.5) * log(x) - x + log(2PI) / 2
    var leftPart = z.sub(0.5).mul(z.log()).sub(z).add(lnSqrt2PI);

    // right part

    var rz = new Complex(1, 0).div(z);
    var rzz = rz.div(z);
    var a = coeffs[0];
    var b = coeffs[1];
    var r = 2 * rzz.re;
    var s = rzz.re * rzz.re + rzz.im * rzz.im;
    for (var i = 2; i < 8; i++) {
      var tmp = b;
      b = -s * a + coeffs[i];
      a = r * a + tmp;
    }
    var rightPart = rz.mul(rzz.mul(a).add(b));

    // plus left and right

    return leftPart.add(rightPart);
  }
  function lgammaRecurrence(z) {
    // computation ref:
    // https://github.com/scipy/scipy/blob/v1.8.0/scipy/special/_loggamma.pxd#L78

    var signflips = 0;
    var sb = 0;
    var shiftprod = z;
    z = z.add(1);
    while (z.re <= SMALL_RE) {
      shiftprod = shiftprod.mul(z);
      var nsb = shiftprod.im < 0 ? 1 : 0;
      if (nsb !== 0 && sb === 0) signflips++;
      sb = nsb;
      z = z.add(1);
    }
    return lgammaStirling(z).sub(shiftprod.log()).sub(new Complex(0, signflips * 2 * Math.PI * 1));
  }
});

var name$L = 'factorial';
var dependencies$L = ['typed', 'gamma'];
var createFactorial = /* #__PURE__ */factory(name$L, dependencies$L, _ref => {
  var {
    typed,
    gamma
  } = _ref;
  /**
   * Compute the factorial of a value
   *
   * Factorial only supports an integer value as argument.
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.factorial(n)
   *
   * Examples:
   *
   *    math.factorial(5)    // returns 120
   *    math.factorial(3)    // returns 6
   *
   * See also:
   *
   *    combinations, combinationsWithRep, gamma, permutations
   *
   * @param {number | BigNumber | Array | Matrix} n   An integer number
   * @return {number | BigNumber | Array | Matrix}    The factorial of `n`
   */
  return typed(name$L, {
    number: function number(n) {
      if (n < 0) {
        throw new Error('Value must be non-negative');
      }
      return gamma(n + 1);
    },
    BigNumber: function BigNumber(n) {
      if (n.isNegative()) {
        throw new Error('Value must be non-negative');
      }
      return gamma(n.plus(1));
    },
    'Array | Matrix': typed.referToSelf(self => n => deepMap(n, self))
  });
});

var name$K = 'kldivergence';
var dependencies$K = ['typed', 'matrix', 'divide', 'sum', 'multiply', 'map', 'dotDivide', 'log', 'isNumeric'];
var createKldivergence = /* #__PURE__ */factory(name$K, dependencies$K, _ref => {
  var {
    typed,
    matrix,
    divide,
    sum,
    multiply,
    map,
    dotDivide,
    log,
    isNumeric
  } = _ref;
  /**
     * Calculate the Kullback-Leibler (KL) divergence  between two distributions
     *
     * Syntax:
     *
     *     math.kldivergence(x, y)
     *
     * Examples:
     *
     *     math.kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5])   //returns 0.24376698773121153
     *
     *
     * @param  {Array | Matrix} q    First vector
     * @param  {Array | Matrix} p    Second vector
     * @return {number}              Returns distance between q and p
     */
  return typed(name$K, {
    'Array, Array': function ArrayArray(q, p) {
      return _kldiv(matrix(q), matrix(p));
    },
    'Matrix, Array': function MatrixArray(q, p) {
      return _kldiv(q, matrix(p));
    },
    'Array, Matrix': function ArrayMatrix(q, p) {
      return _kldiv(matrix(q), p);
    },
    'Matrix, Matrix': function MatrixMatrix(q, p) {
      return _kldiv(q, p);
    }
  });
  function _kldiv(q, p) {
    var plength = p.size().length;
    var qlength = q.size().length;
    if (plength > 1) {
      throw new Error('first object must be one dimensional');
    }
    if (qlength > 1) {
      throw new Error('second object must be one dimensional');
    }
    if (plength !== qlength) {
      throw new Error('Length of two vectors must be equal');
    }

    // Before calculation, apply normalization
    var sumq = sum(q);
    if (sumq === 0) {
      throw new Error('Sum of elements in first object must be non zero');
    }
    var sump = sum(p);
    if (sump === 0) {
      throw new Error('Sum of elements in second object must be non zero');
    }
    var qnorm = divide(q, sum(q));
    var pnorm = divide(p, sum(p));
    var result = sum(multiply(qnorm, map(dotDivide(qnorm, pnorm), x => log(x))));
    if (isNumeric(result)) {
      return result;
    } else {
      return Number.NaN;
    }
  }
});

var name$J = 'multinomial';
var dependencies$J = ['typed', 'add', 'divide', 'multiply', 'factorial', 'isInteger', 'isPositive'];
var createMultinomial = /* #__PURE__ */factory(name$J, dependencies$J, _ref => {
  var {
    typed,
    add,
    divide,
    multiply,
    factorial,
    isInteger,
    isPositive
  } = _ref;
  /**
   * 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
   *
   * Syntax:
   *
   *     math.multinomial(a) // a is an array type
   *
   * Examples:
   *
   *    math.multinomial([1,2,1]) // returns 12
   *
   * See also:
   *
   *    combinations, factorial
   *
   * @param {number[] | BigNumber[]} a    Integer numbers of objects in the subset
   * @return {Number | BigNumber}         Multinomial coefficient.
   */
  return typed(name$J, {
    'Array | Matrix': function ArrayMatrix(a) {
      var sum = 0;
      var denom = 1;
      deepForEach(a, function (ai) {
        if (!isInteger(ai) || !isPositive(ai)) {
          throw new TypeError('Positive integer value expected in function multinomial');
        }
        sum = add(sum, ai);
        denom = multiply(denom, factorial(ai));
      });
      return divide(factorial(sum), denom);
    }
  });
});

var name$I = 'permutations';
var dependencies$I = ['typed', 'factorial'];
var createPermutations = /* #__PURE__ */factory(name$I, dependencies$I, _ref => {
  var {
    typed,
    factorial
  } = _ref;
  /**
   * Compute the number of ways of obtaining an ordered subset of `k` elements
   * from a set of `n` elements.
   *
   * Permutations only takes integer arguments.
   * The following condition must be enforced: k <= n.
   *
   * Syntax:
   *
   *     math.permutations(n)
   *     math.permutations(n, k)
   *
   * Examples:
   *
   *    math.permutations(5)     // 120
   *    math.permutations(5, 3)  // 60
   *
   * See also:
   *
   *    combinations, combinationsWithRep, factorial
   *
   * @param {number | BigNumber} n   The number of objects in total
   * @param {number | BigNumber} [k] The number of objects in the subset
   * @return {number | BigNumber}    The number of permutations
   */
  return typed(name$I, {
    'number | BigNumber': factorial,
    'number, number': function numberNumber(n, k) {
      if (!isInteger(n) || n < 0) {
        throw new TypeError('Positive integer value expected in function permutations');
      }
      if (!isInteger(k) || k < 0) {
        throw new TypeError('Positive integer value expected in function permutations');
      }
      if (k > n) {
        throw new TypeError('second argument k must be less than or equal to first argument n');
      }
      // Permute n objects, k at a time
      return product(n - k + 1, n);
    },
    'BigNumber, BigNumber': function BigNumberBigNumber(n, k) {
      var result, i;
      if (!isPositiveInteger(n) || !isPositiveInteger(k)) {
        throw new TypeError('Positive integer value expected in function permutations');
      }
      if (k.gt(n)) {
        throw new TypeError('second argument k must be less than or equal to first argument n');
      }
      var one = n.mul(0).add(1);
      result = one;
      for (i = n.minus(k).plus(1); i.lte(n); i = i.plus(1)) {
        result = result.times(i);
      }
      return result;
    }

    // TODO: implement support for collection in permutations
  });
});

/**
 * Test whether BigNumber n is a positive integer
 * @param {BigNumber} n
 * @returns {boolean} isPositiveInteger
 */
function isPositiveInteger(n) {
  return n.isInteger() && n.gte(0);
}

var alea$1 = {exports: {}};

(function (module) {
// A port of an algorithm by Johannes Baagøe <baagoe@baagoe.com>, 2010
// http://baagoe.com/en/RandomMusings/javascript/
// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror
// Original work is under MIT license -

// Copyright (C) 2010 by Johannes Baagøe <baagoe@baagoe.org>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.



(function(global, module, define) {

function Alea(seed) {
  var me = this, mash = Mash();

  me.next = function() {
    var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32
    me.s0 = me.s1;
    me.s1 = me.s2;
    return me.s2 = t - (me.c = t | 0);
  };

  // Apply the seeding algorithm from Baagoe.
  me.c = 1;
  me.s0 = mash(' ');
  me.s1 = mash(' ');
  me.s2 = mash(' ');
  me.s0 -= mash(seed);
  if (me.s0 < 0) { me.s0 += 1; }
  me.s1 -= mash(seed);
  if (me.s1 < 0) { me.s1 += 1; }
  me.s2 -= mash(seed);
  if (me.s2 < 0) { me.s2 += 1; }
  mash = null;
}

function copy(f, t) {
  t.c = f.c;
  t.s0 = f.s0;
  t.s1 = f.s1;
  t.s2 = f.s2;
  return t;
}

function impl(seed, opts) {
  var xg = new Alea(seed),
      state = opts && opts.state,
      prng = xg.next;
  prng.int32 = function() { return (xg.next() * 0x100000000) | 0; };
  prng.double = function() {
    return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
  };
  prng.quick = prng;
  if (state) {
    if (typeof(state) == 'object') copy(state, xg);
    prng.state = function() { return copy(xg, {}); };
  }
  return prng;
}

function Mash() {
  var n = 0xefc8249d;

  var mash = function(data) {
    data = String(data);
    for (var i = 0; i < data.length; i++) {
      n += data.charCodeAt(i);
      var h = 0.02519603282416938 * n;
      n = h >>> 0;
      h -= n;
      h *= n;
      n = h >>> 0;
      h -= n;
      n += h * 0x100000000; // 2^32
    }
    return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
  };

  return mash;
}


if (module && module.exports) {
  module.exports = impl;
} else if (define && define.amd) {
  define(function() { return impl; });
} else {
  this.alea = impl;
}

})(
  commonjsGlobal,
  module,    // present in node.js
  (typeof undefined) == 'function'    // present with an AMD loader
);
}(alea$1));

var xor128$1 = {exports: {}};

(function (module) {
// A Javascript implementaion of the "xor128" prng algorithm by
// George Marsaglia.  See http://www.jstatsoft.org/v08/i14/paper

(function(global, module, define) {

function XorGen(seed) {
  var me = this, strseed = '';

  me.x = 0;
  me.y = 0;
  me.z = 0;
  me.w = 0;

  // Set up generator function.
  me.next = function() {
    var t = me.x ^ (me.x << 11);
    me.x = me.y;
    me.y = me.z;
    me.z = me.w;
    return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8);
  };

  if (seed === (seed | 0)) {
    // Integer seed.
    me.x = seed;
  } else {
    // String seed.
    strseed += seed;
  }

  // Mix in string seed, then discard an initial batch of 64 values.
  for (var k = 0; k < strseed.length + 64; k++) {
    me.x ^= strseed.charCodeAt(k) | 0;
    me.next();
  }
}

function copy(f, t) {
  t.x = f.x;
  t.y = f.y;
  t.z = f.z;
  t.w = f.w;
  return t;
}

function impl(seed, opts) {
  var xg = new XorGen(seed),
      state = opts && opts.state,
      prng = function() { return (xg.next() >>> 0) / 0x100000000; };
  prng.double = function() {
    do {
      var top = xg.next() >>> 11,
          bot = (xg.next() >>> 0) / 0x100000000,
          result = (top + bot) / (1 << 21);
    } while (result === 0);
    return result;
  };
  prng.int32 = xg.next;
  prng.quick = prng;
  if (state) {
    if (typeof(state) == 'object') copy(state, xg);
    prng.state = function() { return copy(xg, {}); };
  }
  return prng;
}

if (module && module.exports) {
  module.exports = impl;
} else if (define && define.amd) {
  define(function() { return impl; });
} else {
  this.xor128 = impl;
}

})(
  commonjsGlobal,
  module,    // present in node.js
  (typeof undefined) == 'function'    // present with an AMD loader
);
}(xor128$1));

var xorwow$1 = {exports: {}};

(function (module) {
// A Javascript implementaion of the "xorwow" prng algorithm by
// George Marsaglia.  See http://www.jstatsoft.org/v08/i14/paper

(function(global, module, define) {

function XorGen(seed) {
  var me = this, strseed = '';

  // Set up generator function.
  me.next = function() {
    var t = (me.x ^ (me.x >>> 2));
    me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v;
    return (me.d = (me.d + 362437 | 0)) +
       (me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0;
  };

  me.x = 0;
  me.y = 0;
  me.z = 0;
  me.w = 0;
  me.v = 0;

  if (seed === (seed | 0)) {
    // Integer seed.
    me.x = seed;
  } else {
    // String seed.
    strseed += seed;
  }

  // Mix in string seed, then discard an initial batch of 64 values.
  for (var k = 0; k < strseed.length + 64; k++) {
    me.x ^= strseed.charCodeAt(k) | 0;
    if (k == strseed.length) {
      me.d = me.x << 10 ^ me.x >>> 4;
    }
    me.next();
  }
}

function copy(f, t) {
  t.x = f.x;
  t.y = f.y;
  t.z = f.z;
  t.w = f.w;
  t.v = f.v;
  t.d = f.d;
  return t;
}

function impl(seed, opts) {
  var xg = new XorGen(seed),
      state = opts && opts.state,
      prng = function() { return (xg.next() >>> 0) / 0x100000000; };
  prng.double = function() {
    do {
      var top = xg.next() >>> 11,
          bot = (xg.next() >>> 0) / 0x100000000,
          result = (top + bot) / (1 << 21);
    } while (result === 0);
    return result;
  };
  prng.int32 = xg.next;
  prng.quick = prng;
  if (state) {
    if (typeof(state) == 'object') copy(state, xg);
    prng.state = function() { return copy(xg, {}); };
  }
  return prng;
}

if (module && module.exports) {
  module.exports = impl;
} else if (define && define.amd) {
  define(function() { return impl; });
} else {
  this.xorwow = impl;
}

})(
  commonjsGlobal,
  module,    // present in node.js
  (typeof undefined) == 'function'    // present with an AMD loader
);
}(xorwow$1));

var xorshift7$1 = {exports: {}};

(function (module) {
// A Javascript implementaion of the "xorshift7" algorithm by
// François Panneton and Pierre L'ecuyer:
// "On the Xorgshift Random Number Generators"
// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf

(function(global, module, define) {

function XorGen(seed) {
  var me = this;

  // Set up generator function.
  me.next = function() {
    // Update xor generator.
    var X = me.x, i = me.i, t, v;
    t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24);
    t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10);
    t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3);
    t = X[(i + 4) & 7]; v ^= t ^ (t << 7);
    t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);
    X[i] = v;
    me.i = (i + 1) & 7;
    return v;
  };

  function init(me, seed) {
    var j, X = [];

    if (seed === (seed | 0)) {
      // Seed state array using a 32-bit integer.
      X[0] = seed;
    } else {
      // Seed state using a string.
      seed = '' + seed;
      for (j = 0; j < seed.length; ++j) {
        X[j & 7] = (X[j & 7] << 15) ^
            (seed.charCodeAt(j) + X[(j + 1) & 7] << 13);
      }
    }
    // Enforce an array length of 8, not all zeroes.
    while (X.length < 8) X.push(0);
    for (j = 0; j < 8 && X[j] === 0; ++j);
    if (j == 8) X[7] = -1; else X[j];

    me.x = X;
    me.i = 0;

    // Discard an initial 256 values.
    for (j = 256; j > 0; --j) {
      me.next();
    }
  }

  init(me, seed);
}

function copy(f, t) {
  t.x = f.x.slice();
  t.i = f.i;
  return t;
}

function impl(seed, opts) {
  if (seed == null) seed = +(new Date);
  var xg = new XorGen(seed),
      state = opts && opts.state,
      prng = function() { return (xg.next() >>> 0) / 0x100000000; };
  prng.double = function() {
    do {
      var top = xg.next() >>> 11,
          bot = (xg.next() >>> 0) / 0x100000000,
          result = (top + bot) / (1 << 21);
    } while (result === 0);
    return result;
  };
  prng.int32 = xg.next;
  prng.quick = prng;
  if (state) {
    if (state.x) copy(state, xg);
    prng.state = function() { return copy(xg, {}); };
  }
  return prng;
}

if (module && module.exports) {
  module.exports = impl;
} else if (define && define.amd) {
  define(function() { return impl; });
} else {
  this.xorshift7 = impl;
}

})(
  commonjsGlobal,
  module,    // present in node.js
  (typeof undefined) == 'function'    // present with an AMD loader
);
}(xorshift7$1));

var xor4096$1 = {exports: {}};

(function (module) {
// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.
//
// This fast non-cryptographic random number generator is designed for
// use in Monte-Carlo algorithms. It combines a long-period xorshift
// generator with a Weyl generator, and it passes all common batteries
// of stasticial tests for randomness while consuming only a few nanoseconds
// for each prng generated.  For background on the generator, see Brent's
// paper: "Some long-period random number generators using shifts and xors."
// http://arxiv.org/pdf/1004.3115v1.pdf
//
// Usage:
//
// var xor4096 = require('xor4096');
// random = xor4096(1);                        // Seed with int32 or string.
// assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits.
// assert.equal(random.int32(), 1806534897);   // signed int32, 32 bits.
//
// For nonzero numeric keys, this impelementation provides a sequence
// identical to that by Brent's xorgens 3 implementaion in C.  This
// implementation also provides for initalizing the generator with
// string seeds, or for saving and restoring the state of the generator.
//
// On Chrome, this prng benchmarks about 2.1 times slower than
// Javascript's built-in Math.random().

(function(global, module, define) {

function XorGen(seed) {
  var me = this;

  // Set up generator function.
  me.next = function() {
    var w = me.w,
        X = me.X, i = me.i, t, v;
    // Update Weyl generator.
    me.w = w = (w + 0x61c88647) | 0;
    // Update xor generator.
    v = X[(i + 34) & 127];
    t = X[i = ((i + 1) & 127)];
    v ^= v << 13;
    t ^= t << 17;
    v ^= v >>> 15;
    t ^= t >>> 12;
    // Update Xor generator array state.
    v = X[i] = v ^ t;
    me.i = i;
    // Result is the combination.
    return (v + (w ^ (w >>> 16))) | 0;
  };

  function init(me, seed) {
    var t, v, i, j, w, X = [], limit = 128;
    if (seed === (seed | 0)) {
      // Numeric seeds initialize v, which is used to generates X.
      v = seed;
      seed = null;
    } else {
      // String seeds are mixed into v and X one character at a time.
      seed = seed + '\0';
      v = 0;
      limit = Math.max(limit, seed.length);
    }
    // Initialize circular array and weyl value.
    for (i = 0, j = -32; j < limit; ++j) {
      // Put the unicode characters into the array, and shuffle them.
      if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);
      // After 32 shuffles, take v as the starting w value.
      if (j === 0) w = v;
      v ^= v << 10;
      v ^= v >>> 15;
      v ^= v << 4;
      v ^= v >>> 13;
      if (j >= 0) {
        w = (w + 0x61c88647) | 0;     // Weyl.
        t = (X[j & 127] ^= (v + w));  // Combine xor and weyl to init array.
        i = (0 == t) ? i + 1 : 0;     // Count zeroes.
      }
    }
    // We have detected all zeroes; make the key nonzero.
    if (i >= 128) {
      X[(seed && seed.length || 0) & 127] = -1;
    }
    // Run the generator 512 times to further mix the state before using it.
    // Factoring this as a function slows the main generator, so it is just
    // unrolled here.  The weyl generator is not advanced while warming up.
    i = 127;
    for (j = 4 * 128; j > 0; --j) {
      v = X[(i + 34) & 127];
      t = X[i = ((i + 1) & 127)];
      v ^= v << 13;
      t ^= t << 17;
      v ^= v >>> 15;
      t ^= t >>> 12;
      X[i] = v ^ t;
    }
    // Storing state as object members is faster than using closure variables.
    me.w = w;
    me.X = X;
    me.i = i;
  }

  init(me, seed);
}

function copy(f, t) {
  t.i = f.i;
  t.w = f.w;
  t.X = f.X.slice();
  return t;
}
function impl(seed, opts) {
  if (seed == null) seed = +(new Date);
  var xg = new XorGen(seed),
      state = opts && opts.state,
      prng = function() { return (xg.next() >>> 0) / 0x100000000; };
  prng.double = function() {
    do {
      var top = xg.next() >>> 11,
          bot = (xg.next() >>> 0) / 0x100000000,
          result = (top + bot) / (1 << 21);
    } while (result === 0);
    return result;
  };
  prng.int32 = xg.next;
  prng.quick = prng;
  if (state) {
    if (state.X) copy(state, xg);
    prng.state = function() { return copy(xg, {}); };
  }
  return prng;
}

if (module && module.exports) {
  module.exports = impl;
} else if (define && define.amd) {
  define(function() { return impl; });
} else {
  this.xor4096 = impl;
}

})(
  commonjsGlobal,                                     // window object or global
  module,    // present in node.js
  (typeof undefined) == 'function'    // present with an AMD loader
);
}(xor4096$1));

var tychei$1 = {exports: {}};

(function (module) {
// A Javascript implementaion of the "Tyche-i" prng algorithm by
// Samuel Neves and Filipe Araujo.
// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf

(function(global, module, define) {

function XorGen(seed) {
  var me = this, strseed = '';

  // Set up generator function.
  me.next = function() {
    var b = me.b, c = me.c, d = me.d, a = me.a;
    b = (b << 25) ^ (b >>> 7) ^ c;
    c = (c - d) | 0;
    d = (d << 24) ^ (d >>> 8) ^ a;
    a = (a - b) | 0;
    me.b = b = (b << 20) ^ (b >>> 12) ^ c;
    me.c = c = (c - d) | 0;
    me.d = (d << 16) ^ (c >>> 16) ^ a;
    return me.a = (a - b) | 0;
  };

  /* The following is non-inverted tyche, which has better internal
   * bit diffusion, but which is about 25% slower than tyche-i in JS.
  me.next = function() {
    var a = me.a, b = me.b, c = me.c, d = me.d;
    a = (me.a + me.b | 0) >>> 0;
    d = me.d ^ a; d = d << 16 ^ d >>> 16;
    c = me.c + d | 0;
    b = me.b ^ c; b = b << 12 ^ d >>> 20;
    me.a = a = a + b | 0;
    d = d ^ a; me.d = d = d << 8 ^ d >>> 24;
    me.c = c = c + d | 0;
    b = b ^ c;
    return me.b = (b << 7 ^ b >>> 25);
  }
  */

  me.a = 0;
  me.b = 0;
  me.c = 2654435769 | 0;
  me.d = 1367130551;

  if (seed === Math.floor(seed)) {
    // Integer seed.
    me.a = (seed / 0x100000000) | 0;
    me.b = seed | 0;
  } else {
    // String seed.
    strseed += seed;
  }

  // Mix in string seed, then discard an initial batch of 64 values.
  for (var k = 0; k < strseed.length + 20; k++) {
    me.b ^= strseed.charCodeAt(k) | 0;
    me.next();
  }
}

function copy(f, t) {
  t.a = f.a;
  t.b = f.b;
  t.c = f.c;
  t.d = f.d;
  return t;
}
function impl(seed, opts) {
  var xg = new XorGen(seed),
      state = opts && opts.state,
      prng = function() { return (xg.next() >>> 0) / 0x100000000; };
  prng.double = function() {
    do {
      var top = xg.next() >>> 11,
          bot = (xg.next() >>> 0) / 0x100000000,
          result = (top + bot) / (1 << 21);
    } while (result === 0);
    return result;
  };
  prng.int32 = xg.next;
  prng.quick = prng;
  if (state) {
    if (typeof(state) == 'object') copy(state, xg);
    prng.state = function() { return copy(xg, {}); };
  }
  return prng;
}

if (module && module.exports) {
  module.exports = impl;
} else if (define && define.amd) {
  define(function() { return impl; });
} else {
  this.tychei = impl;
}

})(
  commonjsGlobal,
  module,    // present in node.js
  (typeof undefined) == 'function'    // present with an AMD loader
);
}(tychei$1));

var seedrandom$1 = {exports: {}};

/*
Copyright 2019 David Bau.

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

(function (module) {
(function (global, pool, math) {
//
// The following constants are related to IEEE 754 limits.
//

var width = 256,        // each RC4 output is 0 <= x < 256
    chunks = 6,         // at least six RC4 outputs for each double
    digits = 52,        // there are 52 significant digits in a double
    rngname = 'random', // rngname: name for Math.random and Math.seedrandom
    startdenom = math.pow(width, chunks),
    significance = math.pow(2, digits),
    overflow = significance * 2,
    mask = width - 1,
    nodecrypto;         // node.js crypto module, initialized at the bottom.

//
// seedrandom()
// This is the seedrandom function described above.
//
function seedrandom(seed, options, callback) {
  var key = [];
  options = (options == true) ? { entropy: true } : (options || {});

  // Flatten the seed string or build one from local entropy if needed.
  var shortseed = mixkey(flatten(
    options.entropy ? [seed, tostring(pool)] :
    (seed == null) ? autoseed() : seed, 3), key);

  // Use the seed to initialize an ARC4 generator.
  var arc4 = new ARC4(key);

  // This function returns a random double in [0, 1) that contains
  // randomness in every bit of the mantissa of the IEEE 754 value.
  var prng = function() {
    var n = arc4.g(chunks),             // Start with a numerator n < 2 ^ 48
        d = startdenom,                 //   and denominator d = 2 ^ 48.
        x = 0;                          //   and no 'extra last byte'.
    while (n < significance) {          // Fill up all significant digits by
      n = (n + x) * width;              //   shifting numerator and
      d *= width;                       //   denominator and generating a
      x = arc4.g(1);                    //   new least-significant-byte.
    }
    while (n >= overflow) {             // To avoid rounding up, before adding
      n /= 2;                           //   last byte, shift everything
      d /= 2;                           //   right using integer math until
      x >>>= 1;                         //   we have exactly the desired bits.
    }
    return (n + x) / d;                 // Form the number within [0, 1).
  };

  prng.int32 = function() { return arc4.g(4) | 0; };
  prng.quick = function() { return arc4.g(4) / 0x100000000; };
  prng.double = prng;

  // Mix the randomness into accumulated entropy.
  mixkey(tostring(arc4.S), pool);

  // Calling convention: what to return as a function of prng, seed, is_math.
  return (options.pass || callback ||
      function(prng, seed, is_math_call, state) {
        if (state) {
          // Load the arc4 state from the given state if it has an S array.
          if (state.S) { copy(state, arc4); }
          // Only provide the .state method if requested via options.state.
          prng.state = function() { return copy(arc4, {}); };
        }

        // If called as a method of Math (Math.seedrandom()), mutate
        // Math.random because that is how seedrandom.js has worked since v1.0.
        if (is_math_call) { math[rngname] = prng; return seed; }

        // Otherwise, it is a newer calling convention, so return the
        // prng directly.
        else return prng;
      })(
  prng,
  shortseed,
  'global' in options ? options.global : (this == math),
  options.state);
}

//
// ARC4
//
// An ARC4 implementation.  The constructor takes a key in the form of
// an array of at most (width) integers that should be 0 <= x < (width).
//
// The g(count) method returns a pseudorandom integer that concatenates
// the next (count) outputs from ARC4.  Its return value is a number x
// that is in the range 0 <= x < (width ^ count).
//
function ARC4(key) {
  var t, keylen = key.length,
      me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];

  // The empty key [] is treated as [0].
  if (!keylen) { key = [keylen++]; }

  // Set up S using the standard key scheduling algorithm.
  while (i < width) {
    s[i] = i++;
  }
  for (i = 0; i < width; i++) {
    s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
    s[j] = t;
  }

  // The "g" method returns the next (count) outputs as one number.
  (me.g = function(count) {
    // Using instance members instead of closure state nearly doubles speed.
    var t, r = 0,
        i = me.i, j = me.j, s = me.S;
    while (count--) {
      t = s[i = mask & (i + 1)];
      r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
    }
    me.i = i; me.j = j;
    return r;
    // For robust unpredictability, the function call below automatically
    // discards an initial batch of values.  This is called RC4-drop[256].
    // See http://google.com/search?q=rsa+fluhrer+response&btnI
  })(width);
}

//
// copy()
// Copies internal state of ARC4 to or from a plain object.
//
function copy(f, t) {
  t.i = f.i;
  t.j = f.j;
  t.S = f.S.slice();
  return t;
}
//
// flatten()
// Converts an object tree to nested arrays of strings.
//
function flatten(obj, depth) {
  var result = [], typ = (typeof obj), prop;
  if (depth && typ == 'object') {
    for (prop in obj) {
      try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
    }
  }
  return (result.length ? result : typ == 'string' ? obj : obj + '\0');
}

//
// mixkey()
// Mixes a string seed into a key that is an array of integers, and
// returns a shortened string seed that is equivalent to the result key.
//
function mixkey(seed, key) {
  var stringseed = seed + '', smear, j = 0;
  while (j < stringseed.length) {
    key[mask & j] =
      mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
  }
  return tostring(key);
}

//
// autoseed()
// Returns an object for autoseeding, using window.crypto and Node crypto
// module if available.
//
function autoseed() {
  try {
    var out;
    if (nodecrypto && (out = nodecrypto.randomBytes)) {
      // The use of 'out' to remember randomBytes makes tight minified code.
      out = out(width);
    } else {
      out = new Uint8Array(width);
      (global.crypto || global.msCrypto).getRandomValues(out);
    }
    return tostring(out);
  } catch (e) {
    var browser = global.navigator,
        plugins = browser && browser.plugins;
    return [+new Date, global, plugins, global.screen, tostring(pool)];
  }
}

//
// tostring()
// Converts an array of charcodes to a string
//
function tostring(a) {
  return String.fromCharCode.apply(0, a);
}

//
// When seedrandom.js is loaded, we immediately mix a few bits
// from the built-in RNG into the entropy pool.  Because we do
// not want to interfere with deterministic PRNG state later,
// seedrandom will not call math.random on its own again after
// initialization.
//
mixkey(math.random(), pool);

//
// Nodejs and AMD support: export the implementation as a module using
// either convention.
//
if (module.exports) {
  module.exports = seedrandom;
  // When in node.js, try using crypto package for autoseeding.
  try {
    nodecrypto = require$$0__default["default"];
  } catch (ex) {}
} else {
  // When included as a plain script, set up Math.seedrandom global.
  math['seed' + rngname] = seedrandom;
}


// End anonymous scope, and pass initial values.
})(
  // global: `self` in browsers (including strict mode and web workers),
  // otherwise `this` in Node and other environments
  (typeof self !== 'undefined') ? self : commonjsGlobal,
  [],     // pool: entropy pool starts empty
  Math    // math: package containing random, pow, and seedrandom
);
}(seedrandom$1));

// A library of seedable RNGs implemented in Javascript.
//
// Usage:
//
// var seedrandom = require('seedrandom');
// var random = seedrandom(1); // or any seed.
// var x = random();       // 0 <= x < 1.  Every bit is random.
// var x = random.quick(); // 0 <= x < 1.  32 bits of randomness.

// alea, a 53-bit multiply-with-carry generator by Johannes Baagøe.
// Period: ~2^116
// Reported to pass all BigCrush tests.
var alea = alea$1.exports;

// xor128, a pure xor-shift generator by George Marsaglia.
// Period: 2^128-1.
// Reported to fail: MatrixRank and LinearComp.
var xor128 = xor128$1.exports;

// xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl.
// Period: 2^192-2^32
// Reported to fail: CollisionOver, SimpPoker, and LinearComp.
var xorwow = xorwow$1.exports;

// xorshift7, by François Panneton and Pierre L'ecuyer, takes
// a different approach: it adds robustness by allowing more shifts
// than Marsaglia's original three.  It is a 7-shift generator
// with 256 bits, that passes BigCrush with no systmatic failures.
// Period 2^256-1.
// No systematic BigCrush failures reported.
var xorshift7 = xorshift7$1.exports;

// xor4096, by Richard Brent, is a 4096-bit xor-shift with a
// very long period that also adds a Weyl generator. It also passes
// BigCrush with no systematic failures.  Its long period may
// be useful if you have many generators and need to avoid
// collisions.
// Period: 2^4128-2^32.
// No systematic BigCrush failures reported.
var xor4096 = xor4096$1.exports;

// Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random
// number generator derived from ChaCha, a modern stream cipher.
// https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf
// Period: ~2^127
// No systematic BigCrush failures reported.
var tychei = tychei$1.exports;

// The original ARC4-based prng included in this library.
// Period: ~2^1600
var sr = seedrandom$1.exports;

sr.alea = alea;
sr.xor128 = xor128;
sr.xorwow = xorwow;
sr.xorshift7 = xorshift7;
sr.xor4096 = xor4096;
sr.tychei = tychei;

var seedrandom = sr;

var singletonRandom = /* #__PURE__ */seedrandom(Date.now());
function createRng(randomSeed) {
  var random;

  // create a new random generator with given seed
  function setSeed(seed) {
    random = seed === null ? singletonRandom : seedrandom(String(seed));
  }

  // initialize a seeded pseudo random number generator with config's random seed
  setSeed(randomSeed);

  // wrapper function so the rng can be updated via generator
  function rng() {
    return random();
  }
  return rng;
}

var name$H = 'pickRandom';
var dependencies$H = ['typed', 'config', '?on'];
var createPickRandom = /* #__PURE__ */factory(name$H, dependencies$H, _ref => {
  var {
    typed,
    config,
    on
  } = _ref;
  // seeded pseudo random number generator
  var rng = createRng(config.randomSeed);
  if (on) {
    on('config', function (curr, prev) {
      if (curr.randomSeed !== prev.randomSeed) {
        rng = createRng(curr.randomSeed);
      }
    });
  }

  /**
   * Random pick one or more values from a one dimensional array.
   * Array elements are picked using a random function with uniform or weighted distribution.
   *
   * Syntax:
   *
   *     math.pickRandom(array)
   *     math.pickRandom(array, number)
   *     math.pickRandom(array, weights)
   *     math.pickRandom(array, number, weights)
   *     math.pickRandom(array, weights, number)
   *     math.pickRandom(array, { weights, number, elementWise })
   *
   * Examples:
   *
   *     math.pickRandom([3, 6, 12, 2])                  // returns one of the values in the array
   *     math.pickRandom([3, 6, 12, 2], 2)               // returns an array of two of the values in the array
   *     math.pickRandom([3, 6, 12, 2], { number: 2 })   // returns an array of two of the values in the array
   *     math.pickRandom([3, 6, 12, 2], [1, 3, 2, 1])    // returns one of the values in the array with weighted distribution
   *     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
   *     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
   *
   *     math.pickRandom([{x: 1.0, y: 2.0}, {x: 1.1, y: 2.0}], { elementWise: false })
   *         // returns one of the items in the array
   *
   * See also:
   *
   *     random, randomInt
   *
   * @param {Array | Matrix} array     A one dimensional array
   * @param {Int} number               An int or float
   * @param {Array | Matrix} weights   An array of ints or floats
   * @return {number | Array}          Returns a single random value from array when number is undefined.
   *                                   Returns an array with the configured number of elements when number is defined.
   */
  return typed(name$H, {
    'Array | Matrix': function ArrayMatrix(possibles) {
      return _pickRandom(possibles, {});
    },
    'Array | Matrix, Object': function ArrayMatrixObject(possibles, options) {
      return _pickRandom(possibles, options);
    },
    'Array | Matrix, number': function ArrayMatrixNumber(possibles, number) {
      return _pickRandom(possibles, {
        number
      });
    },
    'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(possibles, weights) {
      return _pickRandom(possibles, {
        weights
      });
    },
    'Array | Matrix, Array | Matrix, number': function ArrayMatrixArrayMatrixNumber(possibles, weights, number) {
      return _pickRandom(possibles, {
        number,
        weights
      });
    },
    'Array | Matrix, number, Array | Matrix': function ArrayMatrixNumberArrayMatrix(possibles, number, weights) {
      return _pickRandom(possibles, {
        number,
        weights
      });
    }
  });

  /**
   * @param {Array | Matrix} possibles
   * @param {{
   *   number?: number,
   *   weights?: Array | Matrix,
   *   elementWise: boolean
   * }} options
   * @returns {number | Array}
   * @private
   */
  function _pickRandom(possibles, _ref2) {
    var {
      number,
      weights,
      elementWise = true
    } = _ref2;
    var single = typeof number === 'undefined';
    if (single) {
      number = 1;
    }
    var createMatrix = isMatrix(possibles) ? possibles.create : isMatrix(weights) ? weights.create : null;
    possibles = possibles.valueOf(); // get Array
    if (weights) {
      weights = weights.valueOf(); // get Array
    }
    if (elementWise === true) {
      possibles = flatten(possibles);
      weights = flatten(weights);
    }
    var totalWeights = 0;
    if (typeof weights !== 'undefined') {
      if (weights.length !== possibles.length) {
        throw new Error('Weights must have the same length as possibles');
      }
      for (var i = 0, len = weights.length; i < len; i++) {
        if (!isNumber(weights[i]) || weights[i] < 0) {
          throw new Error('Weights must be an array of positive numbers');
        }
        totalWeights += weights[i];
      }
    }
    var length = possibles.length;
    var result = [];
    var pick;
    while (result.length < number) {
      if (typeof weights === 'undefined') {
        pick = possibles[Math.floor(rng() * length)];
      } else {
        var randKey = rng() * totalWeights;
        for (var _i = 0, _len = possibles.length; _i < _len; _i++) {
          randKey -= weights[_i];
          if (randKey < 0) {
            pick = possibles[_i];
            break;
          }
        }
      }
      result.push(pick);
    }
    return single ? result[0] : createMatrix ? createMatrix(result) : result;
  }
});

/**
 * This is a util function for generating a random matrix recursively.
 * @param {number[]} size
 * @param {function} random
 * @returns {Array}
 */
function randomMatrix(size, random) {
  var data = [];
  size = size.slice(0);
  if (size.length > 1) {
    for (var i = 0, length = size.shift(); i < length; i++) {
      data.push(randomMatrix(size, random));
    }
  } else {
    for (var _i = 0, _length = size.shift(); _i < _length; _i++) {
      data.push(random());
    }
  }
  return data;
}

var name$G = 'random';
var dependencies$G = ['typed', 'config', '?on'];
var createRandom = /* #__PURE__ */factory(name$G, dependencies$G, _ref => {
  var {
    typed,
    config,
    on
  } = _ref;
  // seeded pseudo random number generator
  var rng = createRng(config.randomSeed);
  if (on) {
    on('config', function (curr, prev) {
      if (curr.randomSeed !== prev.randomSeed) {
        rng = createRng(curr.randomSeed);
      }
    });
  }

  /**
   * Return a random number larger or equal to `min` and smaller than `max`
   * using a uniform distribution.
   *
   * Syntax:
   *
   *     math.random()                // generate a random number between 0 and 1
   *     math.random(max)             // generate a random number between 0 and max
   *     math.random(min, max)        // generate a random number between min and max
   *     math.random(size)            // generate a matrix with random numbers between 0 and 1
   *     math.random(size, max)       // generate a matrix with random numbers between 0 and max
   *     math.random(size, min, max)  // generate a matrix with random numbers between min and max
   *
   * Examples:
   *
   *     math.random()       // returns a random number between 0 and 1
   *     math.random(100)    // returns a random number between 0 and 100
   *     math.random(30, 40) // returns a random number between 30 and 40
   *     math.random([2, 3]) // returns a 2x3 matrix with random numbers between 0 and 1
   *
   * See also:
   *
   *     randomInt, pickRandom
   *
   * @param {Array | Matrix} [size] If provided, an array or matrix with given
   *                                size and filled with random values is returned
   * @param {number} [min]  Minimum boundary for the random value, included
   * @param {number} [max]  Maximum boundary for the random value, excluded
   * @return {number | Array | Matrix} A random number
   */
  return typed(name$G, {
    '': () => _random(0, 1),
    number: max => _random(0, max),
    'number, number': (min, max) => _random(min, max),
    'Array | Matrix': size => _randomMatrix(size, 0, 1),
    'Array | Matrix, number': (size, max) => _randomMatrix(size, 0, max),
    'Array | Matrix, number, number': (size, min, max) => _randomMatrix(size, min, max)
  });
  function _randomMatrix(size, min, max) {
    var res = randomMatrix(size.valueOf(), () => _random(min, max));
    return isMatrix(size) ? size.create(res) : res;
  }
  function _random(min, max) {
    return min + rng() * (max - min);
  }
});

var name$F = 'randomInt';
var dependencies$F = ['typed', 'config', '?on'];
var createRandomInt = /* #__PURE__ */factory(name$F, dependencies$F, _ref => {
  var {
    typed,
    config,
    on
  } = _ref;
  // seeded pseudo random number generator
  var rng = createRng(config.randomSeed);
  if (on) {
    on('config', function (curr, prev) {
      if (curr.randomSeed !== prev.randomSeed) {
        rng = createRng(curr.randomSeed);
      }
    });
  }

  /**
   * Return a random integer number larger or equal to `min` and smaller than `max`
   * using a uniform distribution.
   *
   * Syntax:
   *
   *     math.randomInt()                // generate a random integer between 0 and 1
   *     math.randomInt(max)             // generate a random integer between 0 and max
   *     math.randomInt(min, max)        // generate a random integer between min and max
   *     math.randomInt(size)            // generate a matrix with random integer between 0 and 1
   *     math.randomInt(size, max)       // generate a matrix with random integer between 0 and max
   *     math.randomInt(size, min, max)  // generate a matrix with random integer between min and max
   *
   * Examples:
   *
   *     math.randomInt(100)    // returns a random integer between 0 and 100
   *     math.randomInt(30, 40) // returns a random integer between 30 and 40
   *     math.randomInt([2, 3]) // returns a 2x3 matrix with random integers between 0 and 1
   *
   * See also:
   *
   *     random, pickRandom
   *
   * @param {Array | Matrix} [size] If provided, an array or matrix with given
   *                                size and filled with random values is returned
   * @param {number} [min]  Minimum boundary for the random value, included
   * @param {number} [max]  Maximum boundary for the random value, excluded
   * @return {number | Array | Matrix} A random integer value
   */
  return typed(name$F, {
    '': () => _randomInt(0, 1),
    number: max => _randomInt(0, max),
    'number, number': (min, max) => _randomInt(min, max),
    'Array | Matrix': size => _randomIntMatrix(size, 0, 1),
    'Array | Matrix, number': (size, max) => _randomIntMatrix(size, 0, max),
    'Array | Matrix, number, number': (size, min, max) => _randomIntMatrix(size, min, max)
  });
  function _randomIntMatrix(size, min, max) {
    var res = randomMatrix(size.valueOf(), () => _randomInt(min, max));
    return isMatrix(size) ? size.create(res) : res;
  }
  function _randomInt(min, max) {
    return Math.floor(min + rng() * (max - min));
  }
});

var name$E = 'stirlingS2';
var dependencies$E = ['typed', 'addScalar', 'subtractScalar', 'multiplyScalar', 'divideScalar', 'pow', 'factorial', 'combinations', 'isNegative', 'isInteger', 'number', '?bignumber', 'larger'];
var createStirlingS2 = /* #__PURE__ */factory(name$E, dependencies$E, _ref => {
  var {
    typed,
    addScalar,
    subtractScalar,
    multiplyScalar,
    divideScalar,
    pow,
    factorial,
    combinations,
    isNegative,
    isInteger,
    number,
    bignumber,
    larger
  } = _ref;
  var smallCache = [];
  var bigCache = [];
  /**
   * The 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 <= n, then s(n,k) = 1
   *  If k = 0 < n, then s(n,k) = 0
   *
   * Note that if either n or k is supplied as a BigNumber, the result will be
   * as well.
   *
   * Syntax:
   *
   *   math.stirlingS2(n, k)
   *
   * Examples:
   *
   *    math.stirlingS2(5, 3) //returns 25
   *
   * See also:
   *
   *    bellNumbers
   *
   * @param {Number | BigNumber} n    Total number of objects in the set
   * @param {Number | BigNumber} k    Number of objects in the subset
   * @return {Number | BigNumber}     S(n,k)
   */
  return typed(name$E, {
    'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(n, k) {
      if (!isInteger(n) || isNegative(n) || !isInteger(k) || isNegative(k)) {
        throw new TypeError('Non-negative integer value expected in function stirlingS2');
      } else if (larger(k, n)) {
        throw new TypeError('k must be less than or equal to n in function stirlingS2');
      }
      var big = !(isNumber(n) && isNumber(k));
      var cache = big ? bigCache : smallCache;
      var make = big ? bignumber : number;
      var nn = number(n);
      var nk = number(k);
      /* See if we already have the value: */
      if (cache[nn] && cache[nn].length > nk) {
        return cache[nn][nk];
      }
      /* Fill the cache */
      for (var m = 0; m <= nn; ++m) {
        if (!cache[m]) {
          cache[m] = [m === 0 ? make(1) : make(0)];
        }
        if (m === 0) continue;
        var row = cache[m];
        var prev = cache[m - 1];
        for (var i = row.length; i <= m && i <= nk; ++i) {
          if (i === m) {
            row[i] = 1;
          } else {
            row[i] = addScalar(multiplyScalar(make(i), prev[i]), prev[i - 1]);
          }
        }
      }
      return cache[nn][nk];
    }
  });
});

var name$D = 'bellNumbers';
var dependencies$D = ['typed', 'addScalar', 'isNegative', 'isInteger', 'stirlingS2'];
var createBellNumbers = /* #__PURE__ */factory(name$D, dependencies$D, _ref => {
  var {
    typed,
    addScalar,
    isNegative,
    isInteger,
    stirlingS2
  } = _ref;
  /**
   * 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
   *
   * Syntax:
   *
   *   math.bellNumbers(n)
   *
   * Examples:
   *
   *    math.bellNumbers(3) // returns 5
   *    math.bellNumbers(8) // returns 4140
   *
   * See also:
   *
   *    stirlingS2
   *
   * @param {Number | BigNumber} n    Total number of objects in the set
   * @return {Number | BigNumber}     B(n)
   */
  return typed(name$D, {
    'number | BigNumber': function numberBigNumber(n) {
      if (!isInteger(n) || isNegative(n)) {
        throw new TypeError('Non-negative integer value expected in function bellNumbers');
      }

      // Sum (k=0, n) S(n,k).
      var result = 0;
      for (var i = 0; i <= n; i++) {
        result = addScalar(result, stirlingS2(n, i));
      }
      return result;
    }
  });
});

var name$C = 'catalan';
var dependencies$C = ['typed', 'addScalar', 'divideScalar', 'multiplyScalar', 'combinations', 'isNegative', 'isInteger'];
var createCatalan = /* #__PURE__ */factory(name$C, dependencies$C, _ref => {
  var {
    typed,
    addScalar,
    divideScalar,
    multiplyScalar,
    combinations,
    isNegative,
    isInteger
  } = _ref;
  /**
   * The Catalan Numbers enumerate combinatorial structures of many different types.
   * catalan only takes integer arguments.
   * The following condition must be enforced: n >= 0
   *
   * Syntax:
   *
   *   math.catalan(n)
   *
   * Examples:
   *
   *    math.catalan(3) // returns 5
   *    math.catalan(8) // returns 1430
   *
   * See also:
   *
   *    bellNumbers
   *
   * @param {Number | BigNumber} n    nth Catalan number
   * @return {Number | BigNumber}     Cn(n)
   */
  return typed(name$C, {
    'number | BigNumber': function numberBigNumber(n) {
      if (!isInteger(n) || isNegative(n)) {
        throw new TypeError('Non-negative integer value expected in function catalan');
      }
      return divideScalar(combinations(multiplyScalar(n, 2), n), addScalar(n, 1));
    }
  });
});

var name$B = 'composition';
var dependencies$B = ['typed', 'addScalar', 'combinations', 'isNegative', 'isPositive', 'isInteger', 'larger'];
var createComposition = /* #__PURE__ */factory(name$B, dependencies$B, _ref => {
  var {
    typed,
    addScalar,
    combinations,
    isPositive,
    isNegative,
    isInteger,
    larger
  } = _ref;
  /**
   * The composition counts of n into k parts.
   *
   * composition only takes integer arguments.
   * The following condition must be enforced: k <= n.
   *
   * Syntax:
   *
   *   math.composition(n, k)
   *
   * Examples:
   *
   *    math.composition(5, 3) // returns 6
   *
   * See also:
   *
   *    combinations
   *
   * @param {Number | BigNumber} n    Total number of objects in the set
   * @param {Number | BigNumber} k    Number of objects in the subset
   * @return {Number | BigNumber}     Returns the composition counts of n into k parts.
   */
  return typed(name$B, {
    'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(n, k) {
      if (!isInteger(n) || !isPositive(n) || !isInteger(k) || !isPositive(k)) {
        throw new TypeError('Positive integer value expected in function composition');
      } else if (larger(k, n)) {
        throw new TypeError('k must be less than or equal to n in function composition');
      }
      return combinations(addScalar(n, -1), addScalar(k, -1));
    }
  });
});

var name$A = 'leafCount';
var dependencies$A = ['parse', 'typed'];
var createLeafCount = /* #__PURE__ */factory(name$A, dependencies$A, _ref => {
  var {
    parse,
    typed
  } = _ref;
  // This does the real work, but we don't have to recurse through
  // a typed call if we separate it out
  function countLeaves(node) {
    var count = 0;
    node.forEach(n => {
      count += countLeaves(n);
    });
    return count || 1;
  }

  /**
   * Gives the number of "leaf nodes" in the parse tree of the given expression
   * A leaf node is one that has no subexpressions, essentially either a
   * symbol or a constant. Note that `5!` has just one leaf, the '5'; the
   * unary factorial operator does not add a leaf. On the other hand,
   * function symbols do add leaves, so `sin(x)/cos(x)` has four leaves.
   *
   * The `simplify()` function should generally not increase the `leafCount()`
   * of an expression, although currently there is no guarantee that it never
   * does so. In many cases, `simplify()` reduces the leaf count.
   *
   * Syntax:
   *
   *     math.leafCount(expr)
   *
   * Examples:
   *
   *     math.leafCount('x') // 1
   *     math.leafCount(math.parse('a*d-b*c')) // 4
   *     math.leafCount('[a,b;c,d][0,1]') // 6
   *
   * See also:
   *
   *     simplify
   *
   * @param {Node|string} expr    The expression to count the leaves of
   *
   * @return {number}  The number of leaves of `expr`
   *
   */
  return typed(name$A, {
    Node: function Node(expr) {
      return countLeaves(expr);
    }
  });
});

function isNumericNode(x) {
  return isConstantNode(x) || isOperatorNode(x) && x.isUnary() && isConstantNode(x.args[0]);
}
function isConstantExpression(x) {
  if (isConstantNode(x)) {
    // Basic Constant types
    return true;
  }
  if ((isFunctionNode(x) || isOperatorNode(x)) && x.args.every(isConstantExpression)) {
    // Can be constant depending on arguments
    return true;
  }
  if (isParenthesisNode(x) && isConstantExpression(x.content)) {
    // Parenthesis are transparent
    return true;
  }
  return false; // Probably missing some edge cases
}

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var name$z = 'simplifyUtil';
var dependencies$z = ['FunctionNode', 'OperatorNode', 'SymbolNode'];
var createUtil = /* #__PURE__ */factory(name$z, dependencies$z, _ref => {
  var {
    FunctionNode,
    OperatorNode,
    SymbolNode
  } = _ref;
  // TODO commutative/associative properties rely on the arguments
  // e.g. multiply is not commutative for matrices
  // The properties should be calculated from an argument to simplify, or possibly something in math.config
  // the other option is for typed() to specify a return type so that we can evaluate the type of arguments

  /* So that properties of an operator fit on one line: */
  var T = true;
  var F = false;
  var defaultName = 'defaultF';
  var defaultContext = {
    /*      */add: {
      trivial: T,
      total: T,
      commutative: T,
      associative: T
    },
    /**/unaryPlus: {
      trivial: T,
      total: T,
      commutative: T,
      associative: T
    },
    /* */subtract: {
      trivial: F,
      total: T,
      commutative: F,
      associative: F
    },
    /* */multiply: {
      trivial: T,
      total: T,
      commutative: T,
      associative: T
    },
    /*   */divide: {
      trivial: F,
      total: T,
      commutative: F,
      associative: F
    },
    /*    */paren: {
      trivial: T,
      total: T,
      commutative: T,
      associative: F
    },
    /* */defaultF: {
      trivial: F,
      total: T,
      commutative: F,
      associative: F
    }
  };
  var realContext = {
    divide: {
      total: F
    },
    log: {
      total: F
    }
  };
  var positiveContext = {
    subtract: {
      total: F
    },
    abs: {
      trivial: T
    },
    log: {
      total: T
    }
  };
  function hasProperty(nodeOrName, property) {
    var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultContext;
    var name = defaultName;
    if (typeof nodeOrName === 'string') {
      name = nodeOrName;
    } else if (isOperatorNode(nodeOrName)) {
      name = nodeOrName.fn.toString();
    } else if (isFunctionNode(nodeOrName)) {
      name = nodeOrName.name;
    } else if (isParenthesisNode(nodeOrName)) {
      name = 'paren';
    }
    if (hasOwnProperty(context, name)) {
      var properties = context[name];
      if (hasOwnProperty(properties, property)) {
        return properties[property];
      }
      if (hasOwnProperty(defaultContext, name)) {
        return defaultContext[name][property];
      }
    }
    if (hasOwnProperty(context, defaultName)) {
      var _properties = context[defaultName];
      if (hasOwnProperty(_properties, property)) {
        return _properties[property];
      }
      return defaultContext[defaultName][property];
    }
    /* name not found in context and context has no global default */
    /* So use default context. */
    if (hasOwnProperty(defaultContext, name)) {
      var _properties2 = defaultContext[name];
      if (hasOwnProperty(_properties2, property)) {
        return _properties2[property];
      }
    }
    return defaultContext[defaultName][property];
  }
  function isCommutative(node) {
    var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultContext;
    return hasProperty(node, 'commutative', context);
  }
  function isAssociative(node) {
    var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultContext;
    return hasProperty(node, 'associative', context);
  }

  /**
   * Merge the given contexts, with primary overriding secondary
   * wherever they might conflict
   */
  function mergeContext(primary, secondary) {
    var merged = _objectSpread({}, primary);
    for (var prop in secondary) {
      if (hasOwnProperty(primary, prop)) {
        merged[prop] = _objectSpread(_objectSpread({}, secondary[prop]), primary[prop]);
      } else {
        merged[prop] = secondary[prop];
      }
    }
    return merged;
  }

  /**
   * Flatten all associative operators in an expression tree.
   * Assumes parentheses have already been removed.
   */
  function flatten(node, context) {
    if (!node.args || node.args.length === 0) {
      return node;
    }
    node.args = allChildren(node, context);
    for (var i = 0; i < node.args.length; i++) {
      flatten(node.args[i], context);
    }
  }

  /**
   * Get the children of a node as if it has been flattened.
   * TODO implement for FunctionNodes
   */
  function allChildren(node, context) {
    var op;
    var children = [];
    var findChildren = function findChildren(node) {
      for (var i = 0; i < node.args.length; i++) {
        var child = node.args[i];
        if (isOperatorNode(child) && op === child.op) {
          findChildren(child);
        } else {
          children.push(child);
        }
      }
    };
    if (isAssociative(node, context)) {
      op = node.op;
      findChildren(node);
      return children;
    } else {
      return node.args;
    }
  }

  /**
   *  Unflatten all flattened operators to a right-heavy binary tree.
   */
  function unflattenr(node, context) {
    if (!node.args || node.args.length === 0) {
      return;
    }
    var makeNode = createMakeNodeFunction(node);
    var l = node.args.length;
    for (var i = 0; i < l; i++) {
      unflattenr(node.args[i], context);
    }
    if (l > 2 && isAssociative(node, context)) {
      var curnode = node.args.pop();
      while (node.args.length > 0) {
        curnode = makeNode([node.args.pop(), curnode]);
      }
      node.args = curnode.args;
    }
  }

  /**
   *  Unflatten all flattened operators to a left-heavy binary tree.
   */
  function unflattenl(node, context) {
    if (!node.args || node.args.length === 0) {
      return;
    }
    var makeNode = createMakeNodeFunction(node);
    var l = node.args.length;
    for (var i = 0; i < l; i++) {
      unflattenl(node.args[i], context);
    }
    if (l > 2 && isAssociative(node, context)) {
      var curnode = node.args.shift();
      while (node.args.length > 0) {
        curnode = makeNode([curnode, node.args.shift()]);
      }
      node.args = curnode.args;
    }
  }
  function createMakeNodeFunction(node) {
    if (isOperatorNode(node)) {
      return function (args) {
        try {
          return new OperatorNode(node.op, node.fn, args, node.implicit);
        } catch (err) {
          console.error(err);
          return [];
        }
      };
    } else {
      return function (args) {
        return new FunctionNode(new SymbolNode(node.name), args);
      };
    }
  }
  return {
    createMakeNodeFunction,
    hasProperty,
    isCommutative,
    isAssociative,
    mergeContext,
    flatten,
    allChildren,
    unflattenr,
    unflattenl,
    defaultContext,
    realContext,
    positiveContext
  };
});

var name$y = 'simplify';
var dependencies$y = ['config', 'typed', 'parse', 'add', 'subtract', 'multiply', 'divide', 'pow', 'isZero', 'equal', 'resolve', 'simplifyConstant', 'simplifyCore', '?fraction', '?bignumber', 'mathWithTransform', 'matrix', 'AccessorNode', 'ArrayNode', 'ConstantNode', 'FunctionNode', 'IndexNode', 'ObjectNode', 'OperatorNode', 'ParenthesisNode', 'SymbolNode'];
var createSimplify = /* #__PURE__ */factory(name$y, dependencies$y, _ref => {
  var {
    config,
    typed,
    parse,
    add,
    subtract,
    multiply,
    divide,
    pow,
    isZero,
    equal,
    resolve,
    simplifyConstant,
    simplifyCore,
    fraction,
    bignumber,
    mathWithTransform,
    matrix,
    AccessorNode,
    ArrayNode,
    ConstantNode,
    FunctionNode,
    IndexNode,
    ObjectNode,
    OperatorNode,
    ParenthesisNode,
    SymbolNode
  } = _ref;
  var {
    hasProperty,
    isCommutative,
    isAssociative,
    mergeContext,
    flatten,
    unflattenr,
    unflattenl,
    createMakeNodeFunction,
    defaultContext,
    realContext,
    positiveContext
  } = createUtil({
    FunctionNode,
    OperatorNode,
    SymbolNode
  });

  /**
   * Simplify an expression tree.
   *
   * A list of rules are applied to an expression, repeating over the list until
   * no further changes are made.
   * It's possible to pass a custom set of rules to the function as second
   * argument. A rule can be specified as an object, string, or function:
   *
   *     const rules = [
   *       { l: 'n1*n3 + n2*n3', r: '(n1+n2)*n3' },
   *       'n1*n3 + n2*n3 -> (n1+n2)*n3',
   *       function (node) {
   *         // ... return a new node or return the node unchanged
   *         return node
   *       }
   *     ]
   *
   * String and object rules consist of a left and right pattern. The left is
   * used to match against the expression and the right determines what matches
   * are replaced with. The main difference between a pattern and a normal
   * expression is that variables starting with the following characters are
   * interpreted as wildcards:
   *
   * - 'n' - Matches any node [Node]
   * - 'c' - Matches a constant literal (5 or 3.2) [ConstantNode]
   * - 'cl' - Matches a constant literal; same as c [ConstantNode]
   * - 'cd' - Matches a decimal literal (5 or -3.2) [ConstantNode or unaryMinus wrapping a ConstantNode]
   * - 'ce' - Matches a constant expression (-5 or √3) [Expressions consisting of only ConstantNodes, functions, and operators]
   * - 'v' - Matches a variable; anything not matched by c (-5 or x) [Node that is not a ConstantNode]
   * - 'vl' - Matches a variable literal (x or y) [SymbolNode]
   * - 'vd' - Matches a non-decimal expression; anything not matched by cd (x or √3) [Node that is not a ConstantNode or unaryMinus that is wrapping a ConstantNode]
   * - 've' - Matches a variable expression; anything not matched by ce (x or 2x) [Expressions that contain a SymbolNode or other non-constant term]
   *
   * The default list of rules is exposed on the function as `simplify.rules`
   * and can be used as a basis to built a set of custom rules. Note that since
   * the `simplifyCore` function is in the default list of rules, by default
   * simplify will convert any function calls in the expression that have
   * operator equivalents to their operator forms.
   *
   * To specify a rule as a string, separate the left and right pattern by '->'
   * When specifying a rule as an object, the following keys are meaningful:
   * - l - the left pattern
   * - r - the right pattern
   * - s - in lieu of l and r, the string form that is broken at -> to give them
   * - repeat - whether to repeat this rule until the expression stabilizes
   * - assuming - gives a context object, as in the 'context' option to
   *     simplify. Every property in the context object must match the current
   *     context in order, or else the rule will not be applied.
   * - imposeContext - gives a context object, as in the 'context' option to
   *     simplify. Any settings specified will override the incoming context
   *     for all matches of this rule.
   *
   * For more details on the theory, see:
   *
   * - [Strategies for simplifying math expressions (Stackoverflow)](https://stackoverflow.com/questions/7540227/strategies-for-simplifying-math-expressions)
   * - [Symbolic computation - Simplification (Wikipedia)](https://en.wikipedia.org/wiki/Symbolic_computation#Simplification)
   *
   *  An optional `options` argument can be passed as last argument of `simplify`.
   *  Currently available options (defaults in parentheses):
   *  - `consoleDebug` (false): whether to write the expression being simplified
   *    and any changes to it, along with the rule responsible, to console
   *  - `context` (simplify.defaultContext): an object giving properties of
   *    each operator, which determine what simplifications are allowed. The
   *    currently meaningful properties are commutative, associative,
   *    total (whether the operation is defined for all arguments), and
   *    trivial (whether the operation applied to a single argument leaves
   *    that argument unchanged). The default context is very permissive and
   *    allows almost all simplifications. Only properties differing from
   *    the default need to be specified; the default context is used as a
   *    fallback. Additional contexts `simplify.realContext` and
   *    `simplify.positiveContext` are supplied to cause simplify to perform
   *    just simplifications guaranteed to preserve all values of the expression
   *    assuming all variables and subexpressions are real numbers or
   *    positive real numbers, respectively. (Note that these are in some cases
   *    more restrictive than the default context; for example, the default
   *    context will allow `x/x` to simplify to 1, whereas
   *    `simplify.realContext` will not, as `0/0` is not equal to 1.)
   *  - `exactFractions` (true): whether to try to convert all constants to
   *    exact rational numbers.
   *  - `fractionsLimit` (10000): when `exactFractions` is true, constants will
   *    be expressed as fractions only when both numerator and denominator
   *    are smaller than `fractionsLimit`.
   *
   * Syntax:
   *
   *     math.simplify(expr)
   *     math.simplify(expr, rules)
   *     math.simplify(expr, rules)
   *     math.simplify(expr, rules, scope)
   *     math.simplify(expr, rules, scope, options)
   *     math.simplify(expr, scope)
   *     math.simplify(expr, scope, options)
   *
   * Examples:
   *
   *     math.simplify('2 * 1 * x ^ (2 - 1)')      // Node "2 * x"
   *     math.simplify('2 * 3 * x', {x: 4})        // Node "24"
   *     const f = math.parse('2 * 1 * x ^ (2 - 1)')
   *     math.simplify(f)                          // Node "2 * x"
   *     math.simplify('0.4 * x', {}, {exactFractions: true})  // Node "x * 2 / 5"
   *     math.simplify('0.4 * x', {}, {exactFractions: false}) // Node "0.4 * x"
   *
   * See also:
   *
   *     simplifyCore, derivative, evaluate, parse, rationalize, resolve
   *
   * @param {Node | string} expr
   *            The expression to be simplified
   * @param {SimplifyRule[]} [rules]
   *            Optional list with custom rules
   * @param {Object} [scope] Optional scope with variables
   * @param {SimplifyOptions} [options] Optional configuration settings
   * @return {Node} Returns the simplified form of `expr`
   */
  typed.addConversion({
    from: 'Object',
    to: 'Map',
    convert: createMap$1
  });
  var simplify = typed('simplify', {
    Node: _simplify,
    'Node, Map': (expr, scope) => _simplify(expr, false, scope),
    'Node, Map, Object': (expr, scope, options) => _simplify(expr, false, scope, options),
    'Node, Array': _simplify,
    'Node, Array, Map': _simplify,
    'Node, Array, Map, Object': _simplify
  });
  typed.removeConversion({
    from: 'Object',
    to: 'Map',
    convert: createMap$1
  });
  simplify.defaultContext = defaultContext;
  simplify.realContext = realContext;
  simplify.positiveContext = positiveContext;
  function removeParens(node) {
    return node.transform(function (node, path, parent) {
      return isParenthesisNode(node) ? removeParens(node.content) : node;
    });
  }

  // All constants that are allowed in rules
  var SUPPORTED_CONSTANTS = {
    true: true,
    false: true,
    e: true,
    i: true,
    Infinity: true,
    LN2: true,
    LN10: true,
    LOG2E: true,
    LOG10E: true,
    NaN: true,
    phi: true,
    pi: true,
    SQRT1_2: true,
    SQRT2: true,
    tau: true
    // null: false,
    // undefined: false,
    // version: false,
  };

  // Array of strings, used to build the ruleSet.
  // Each l (left side) and r (right side) are parsed by
  // the expression parser into a node tree.
  // Left hand sides are matched to subtrees within the
  // expression to be parsed and replaced with the right
  // hand side.
  // TODO: Add support for constraints on constants (either in the form of a '=' expression or a callback [callback allows things like comparing symbols alphabetically])
  // 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.
  // It is possible to get into an infinite loop with conflicting rules
  simplify.rules = [simplifyCore,
  // { l: 'n+0', r: 'n' },     // simplifyCore
  // { l: 'n^0', r: '1' },     // simplifyCore
  // { l: '0*n', r: '0' },     // simplifyCore
  // { l: 'n/n', r: '1'},      // simplifyCore
  // { l: 'n^1', r: 'n' },     // simplifyCore
  // { l: '+n1', r:'n1' },     // simplifyCore
  // { l: 'n--n1', r:'n+n1' }, // simplifyCore
  {
    l: 'log(e)',
    r: '1'
  },
  // temporary rules
  // Note initially we tend constants to the right because like-term
  // collection prefers the left, and we would rather collect nonconstants
  {
    s: 'n-n1 -> n+-n1',
    // temporarily replace 'subtract' so we can further flatten the 'add' operator
    assuming: {
      subtract: {
        total: true
      }
    }
  }, {
    s: 'n-n -> 0',
    // partial alternative when we can't always subtract
    assuming: {
      subtract: {
        total: false
      }
    }
  }, {
    s: '-(cl*v) -> v * (-cl)',
    // make non-constant terms positive
    assuming: {
      multiply: {
        commutative: true
      },
      subtract: {
        total: true
      }
    }
  }, {
    s: '-(cl*v) -> (-cl) * v',
    // non-commutative version, part 1
    assuming: {
      multiply: {
        commutative: false
      },
      subtract: {
        total: true
      }
    }
  }, {
    s: '-(v*cl) -> v * (-cl)',
    // non-commutative version, part 2
    assuming: {
      multiply: {
        commutative: false
      },
      subtract: {
        total: true
      }
    }
  }, {
    l: '-(n1/n2)',
    r: '-n1/n2'
  }, {
    l: '-v',
    r: 'v * (-1)'
  },
  // finish making non-constant terms positive
  {
    l: '(n1 + n2)*(-1)',
    r: 'n1*(-1) + n2*(-1)',
    repeat: true
  },
  // expand negations to achieve as much sign cancellation as possible
  {
    l: 'n/n1^n2',
    r: 'n*n1^-n2'
  },
  // temporarily replace 'divide' so we can further flatten the 'multiply' operator
  {
    l: 'n/n1',
    r: 'n*n1^-1'
  }, {
    s: '(n1*n2)^n3 -> n1^n3 * n2^n3',
    assuming: {
      multiply: {
        commutative: true
      }
    }
  }, {
    s: '(n1*n2)^(-1) -> n2^(-1) * n1^(-1)',
    assuming: {
      multiply: {
        commutative: false
      }
    }
  },
  // expand nested exponentiation
  {
    s: '(n ^ n1) ^ n2 -> n ^ (n1 * n2)',
    assuming: {
      divide: {
        total: true
      }
    } // 1/(1/n) = n needs 1/n to exist
  },
  // collect like factors; into a sum, only do this for nonconstants
  {
    l: ' vd   * ( vd   * n1 + n2)',
    r: 'vd^2       * n1 +  vd   * n2'
  }, {
    s: ' vd   * (vd^n4 * n1 + n2)   ->  vd^(1+n4)  * n1 +  vd   * n2',
    assuming: {
      divide: {
        total: true
      }
    } // v*1/v = v^(1+-1) needs 1/v
  }, {
    s: 'vd^n3 * ( vd   * n1 + n2)   ->  vd^(n3+1)  * n1 + vd^n3 * n2',
    assuming: {
      divide: {
        total: true
      }
    }
  }, {
    s: 'vd^n3 * (vd^n4 * n1 + n2)   ->  vd^(n3+n4) * n1 + vd^n3 * n2',
    assuming: {
      divide: {
        total: true
      }
    }
  }, {
    l: 'n*n',
    r: 'n^2'
  }, {
    s: 'n * n^n1 -> n^(n1+1)',
    assuming: {
      divide: {
        total: true
      }
    } // n*1/n = n^(-1+1) needs 1/n
  }, {
    s: 'n^n1 * n^n2 -> n^(n1+n2)',
    assuming: {
      divide: {
        total: true
      }
    } // ditto for n^2*1/n^2
  },
  // Unfortunately, to deal with more complicated cancellations, it
  // becomes necessary to simplify constants twice per pass. It's not
  // terribly expensive compared to matching rules, so this should not
  // pose a performance problem.
  simplifyConstant,
  // First: before collecting like terms

  // collect like terms
  {
    s: 'n+n -> 2*n',
    assuming: {
      add: {
        total: true
      }
    } // 2 = 1 + 1 needs to exist
  }, {
    l: 'n+-n',
    r: '0'
  }, {
    l: 'vd*n + vd',
    r: 'vd*(n+1)'
  },
  // NOTE: leftmost position is special:
  {
    l: 'n3*n1 + n3*n2',
    r: 'n3*(n1+n2)'
  },
  // All sub-monomials tried there.
  {
    l: 'n3^(-n4)*n1 +   n3  * n2',
    r: 'n3^(-n4)*(n1 + n3^(n4+1) *n2)'
  }, {
    l: 'n3^(-n4)*n1 + n3^n5 * n2',
    r: 'n3^(-n4)*(n1 + n3^(n4+n5)*n2)'
  },
  // noncommutative additional cases (term collection & factoring)
  {
    s: 'n*vd + vd -> (n+1)*vd',
    assuming: {
      multiply: {
        commutative: false
      }
    }
  }, {
    s: 'vd + n*vd -> (1+n)*vd',
    assuming: {
      multiply: {
        commutative: false
      }
    }
  }, {
    s: 'n1*n3 + n2*n3 -> (n1+n2)*n3',
    assuming: {
      multiply: {
        commutative: false
      }
    }
  }, {
    s: 'n^n1 * n -> n^(n1+1)',
    assuming: {
      divide: {
        total: true
      },
      multiply: {
        commutative: false
      }
    }
  }, {
    s: 'n1*n3^(-n4) + n2 * n3    -> (n1 + n2*n3^(n4 +  1))*n3^(-n4)',
    assuming: {
      multiply: {
        commutative: false
      }
    }
  }, {
    s: 'n1*n3^(-n4) + n2 * n3^n5 -> (n1 + n2*n3^(n4 + n5))*n3^(-n4)',
    assuming: {
      multiply: {
        commutative: false
      }
    }
  }, {
    l: 'n*cd + cd',
    r: '(n+1)*cd'
  }, {
    s: 'cd*n + cd -> cd*(n+1)',
    assuming: {
      multiply: {
        commutative: false
      }
    }
  }, {
    s: 'cd + cd*n -> cd*(1+n)',
    assuming: {
      multiply: {
        commutative: false
      }
    }
  }, simplifyConstant,
  // Second: before returning expressions to "standard form"

  // make factors positive (and undo 'make non-constant terms positive')
  {
    s: '(-n)*n1 -> -(n*n1)',
    assuming: {
      subtract: {
        total: true
      }
    }
  }, {
    s: 'n1*(-n) -> -(n1*n)',
    // in case * non-commutative
    assuming: {
      subtract: {
        total: true
      },
      multiply: {
        commutative: false
      }
    }
  },
  // final ordering of constants
  {
    s: 'ce+ve -> ve+ce',
    assuming: {
      add: {
        commutative: true
      }
    },
    imposeContext: {
      add: {
        commutative: false
      }
    }
  }, {
    s: 'vd*cd -> cd*vd',
    assuming: {
      multiply: {
        commutative: true
      }
    },
    imposeContext: {
      multiply: {
        commutative: false
      }
    }
  },
  // undo temporary rules
  // { l: '(-1) * n', r: '-n' }, // #811 added test which proved this is redundant
  {
    l: 'n+-n1',
    r: 'n-n1'
  },
  // undo replace 'subtract'
  {
    l: 'n+-(n1)',
    r: 'n-(n1)'
  }, {
    s: 'n*(n1^-1) -> n/n1',
    // undo replace 'divide'; for * commutative
    assuming: {
      multiply: {
        commutative: true
      }
    } // o.w. / not conventional
  }, {
    s: 'n*n1^-n2 -> n/n1^n2',
    assuming: {
      multiply: {
        commutative: true
      }
    } // o.w. / not conventional
  }, {
    s: 'n^-1 -> 1/n',
    assuming: {
      multiply: {
        commutative: true
      }
    } // o.w. / not conventional
  }, {
    l: 'n^1',
    r: 'n'
  },
  // can be produced by power cancellation
  {
    s: 'n*(n1/n2) -> (n*n1)/n2',
    // '*' before '/'
    assuming: {
      multiply: {
        associative: true
      }
    }
  }, {
    s: 'n-(n1+n2) -> n-n1-n2',
    // '-' before '+'
    assuming: {
      addition: {
        associative: true,
        commutative: true
      }
    }
  },
  // { l: '(n1/n2)/n3', r: 'n1/(n2*n3)' },
  // { l: '(n*n1)/(n*n2)', r: 'n1/n2' },

  // simplifyConstant can leave an extra factor of 1, which can always
  // be eliminated, since the identity always commutes
  {
    l: '1*n',
    r: 'n',
    imposeContext: {
      multiply: {
        commutative: true
      }
    }
  }, {
    s: 'n1/(n2/n3) -> (n1*n3)/n2',
    assuming: {
      multiply: {
        associative: true
      }
    }
  }, {
    l: 'n1/(-n2)',
    r: '-n1/n2'
  }];

  /**
   * Takes any rule object as allowed by the specification in simplify
   * and puts it in a standard form used by applyRule
   */
  function _canonicalizeRule(ruleObject, context) {
    var newRule = {};
    if (ruleObject.s) {
      var lr = ruleObject.s.split('->');
      if (lr.length === 2) {
        newRule.l = lr[0];
        newRule.r = lr[1];
      } else {
        throw SyntaxError('Could not parse rule: ' + ruleObject.s);
      }
    } else {
      newRule.l = ruleObject.l;
      newRule.r = ruleObject.r;
    }
    newRule.l = removeParens(parse(newRule.l));
    newRule.r = removeParens(parse(newRule.r));
    for (var prop of ['imposeContext', 'repeat', 'assuming']) {
      if (prop in ruleObject) {
        newRule[prop] = ruleObject[prop];
      }
    }
    if (ruleObject.evaluate) {
      newRule.evaluate = parse(ruleObject.evaluate);
    }
    if (isAssociative(newRule.l, context)) {
      var nonCommutative = !isCommutative(newRule.l, context);
      var leftExpandsym;
      // Gen. the LHS placeholder used in this NC-context specific expansion rules
      if (nonCommutative) leftExpandsym = _getExpandPlaceholderSymbol();
      var makeNode = createMakeNodeFunction(newRule.l);
      var expandsym = _getExpandPlaceholderSymbol();
      newRule.expanded = {};
      newRule.expanded.l = makeNode([newRule.l, expandsym]);
      // Push the expandsym into the deepest possible branch.
      // This helps to match the newRule against nodes returned from getSplits() later on.
      flatten(newRule.expanded.l, context);
      unflattenr(newRule.expanded.l, context);
      newRule.expanded.r = makeNode([newRule.r, expandsym]);

      // In and for a non-commutative context, attempting with yet additional expansion rules makes
      // way for more matches cases of multi-arg expressions; such that associative rules (such as
      // 'n*n -> n^2') can be applied to exprs. such as 'a * b * b' and 'a * b * b * a'.
      if (nonCommutative) {
        // 'Non-commutative' 1: LHS (placeholder) only
        newRule.expandedNC1 = {};
        newRule.expandedNC1.l = makeNode([leftExpandsym, newRule.l]);
        newRule.expandedNC1.r = makeNode([leftExpandsym, newRule.r]);
        // 'Non-commutative' 2: farmost LHS and RHS placeholders
        newRule.expandedNC2 = {};
        newRule.expandedNC2.l = makeNode([leftExpandsym, newRule.expanded.l]);
        newRule.expandedNC2.r = makeNode([leftExpandsym, newRule.expanded.r]);
      }
    }
    return newRule;
  }

  /**
   * Parse the string array of rules into nodes
   *
   * Example syntax for rules:
   *
   * Position constants to the left in a product:
   * { l: 'n1 * c1', r: 'c1 * n1' }
   * n1 is any Node, and c1 is a ConstantNode.
   *
   * Apply difference of squares formula:
   * { l: '(n1 - n2) * (n1 + n2)', r: 'n1^2 - n2^2' }
   * n1, n2 mean any Node.
   *
   * Short hand notation:
   * 'n1 * c1 -> c1 * n1'
   */
  function _buildRules(rules, context) {
    // Array of rules to be used to simplify expressions
    var ruleSet = [];
    for (var i = 0; i < rules.length; i++) {
      var rule = rules[i];
      var newRule = void 0;
      var ruleType = typeof rule;
      switch (ruleType) {
        case 'string':
          rule = {
            s: rule
          };
        /* falls through */
        case 'object':
          newRule = _canonicalizeRule(rule, context);
          break;
        case 'function':
          newRule = rule;
          break;
        default:
          throw TypeError('Unsupported type of rule: ' + ruleType);
      }
      // console.log('Adding rule: ' + rules[i])
      // console.log(newRule)
      ruleSet.push(newRule);
    }
    return ruleSet;
  }
  var _lastsym = 0;
  function _getExpandPlaceholderSymbol() {
    return new SymbolNode('_p' + _lastsym++);
  }
  function _simplify(expr, rules) {
    var scope = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : createEmptyMap();
    var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
    var debug = options.consoleDebug;
    rules = _buildRules(rules || simplify.rules, options.context);
    var res = resolve(expr, scope);
    res = removeParens(res);
    var visited = {};
    var str = res.toString({
      parenthesis: 'all'
    });
    while (!visited[str]) {
      visited[str] = true;
      _lastsym = 0; // counter for placeholder symbols
      var laststr = str;
      if (debug) console.log('Working on: ', str);
      for (var i = 0; i < rules.length; i++) {
        var rulestr = '';
        if (typeof rules[i] === 'function') {
          res = rules[i](res, options);
          if (debug) rulestr = rules[i].name;
        } else {
          flatten(res, options.context);
          res = applyRule(res, rules[i], options.context);
          if (debug) {
            rulestr = "".concat(rules[i].l.toString(), " -> ").concat(rules[i].r.toString());
          }
        }
        if (debug) {
          var newstr = res.toString({
            parenthesis: 'all'
          });
          if (newstr !== laststr) {
            console.log('Applying', rulestr, 'produced', newstr);
            laststr = newstr;
          }
        }
        /* Use left-heavy binary tree internally,
         * since custom rule functions may expect it
         */
        unflattenl(res, options.context);
      }
      str = res.toString({
        parenthesis: 'all'
      });
    }
    return res;
  }
  function mapRule(nodes, rule, context) {
    var resNodes = nodes;
    if (nodes) {
      for (var i = 0; i < nodes.length; ++i) {
        var newNode = applyRule(nodes[i], rule, context);
        if (newNode !== nodes[i]) {
          if (resNodes === nodes) {
            resNodes = nodes.slice();
          }
          resNodes[i] = newNode;
        }
      }
    }
    return resNodes;
  }

  /**
   * Returns a simplfied form of node, or the original node if no simplification was possible.
   *
   * @param  {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
   * @param  {Object | Function} rule
   * @param  {Object} context -- information about assumed properties of operators
   * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The simplified form of `expr`, or the original node if no simplification was possible.
   */
  function applyRule(node, rule, context) {
    //    console.log('Entering applyRule("', rule.l.toString({parenthesis:'all'}), '->', rule.r.toString({parenthesis:'all'}), '",', node.toString({parenthesis:'all'}),')')

    // check that the assumptions for this rule are satisfied by the current
    // context:
    if (rule.assuming) {
      for (var symbol in rule.assuming) {
        for (var property in rule.assuming[symbol]) {
          if (hasProperty(symbol, property, context) !== rule.assuming[symbol][property]) {
            return node;
          }
        }
      }
    }
    var mergedContext = mergeContext(rule.imposeContext, context);

    // Do not clone node unless we find a match
    var res = node;

    // First replace our child nodes with their simplified versions
    // If a child could not be simplified, applying the rule to it
    // will have no effect since the node is returned unchanged
    if (res instanceof OperatorNode || res instanceof FunctionNode) {
      var newArgs = mapRule(res.args, rule, context);
      if (newArgs !== res.args) {
        res = res.clone();
        res.args = newArgs;
      }
    } else if (res instanceof ParenthesisNode) {
      if (res.content) {
        var newContent = applyRule(res.content, rule, context);
        if (newContent !== res.content) {
          res = new ParenthesisNode(newContent);
        }
      }
    } else if (res instanceof ArrayNode) {
      var newItems = mapRule(res.items, rule, context);
      if (newItems !== res.items) {
        res = new ArrayNode(newItems);
      }
    } else if (res instanceof AccessorNode) {
      var newObj = res.object;
      if (res.object) {
        newObj = applyRule(res.object, rule, context);
      }
      var newIndex = res.index;
      if (res.index) {
        newIndex = applyRule(res.index, rule, context);
      }
      if (newObj !== res.object || newIndex !== res.index) {
        res = new AccessorNode(newObj, newIndex);
      }
    } else if (res instanceof IndexNode) {
      var newDims = mapRule(res.dimensions, rule, context);
      if (newDims !== res.dimensions) {
        res = new IndexNode(newDims);
      }
    } else if (res instanceof ObjectNode) {
      var changed = false;
      var newProps = {};
      for (var prop in res.properties) {
        newProps[prop] = applyRule(res.properties[prop], rule, context);
        if (newProps[prop] !== res.properties[prop]) {
          changed = true;
        }
      }
      if (changed) {
        res = new ObjectNode(newProps);
      }
    }

    // Try to match a rule against this node
    var repl = rule.r;
    var matches = _ruleMatch(rule.l, res, mergedContext)[0];

    // If the rule is associative operator, we can try matching it while allowing additional terms.
    // 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.
    if (!matches && rule.expanded) {
      repl = rule.expanded.r;
      matches = _ruleMatch(rule.expanded.l, res, mergedContext)[0];
    }
    // Additional, non-commutative context expansion-rules
    if (!matches && rule.expandedNC1) {
      repl = rule.expandedNC1.r;
      matches = _ruleMatch(rule.expandedNC1.l, res, mergedContext)[0];
      if (!matches) {
        // Existence of NC1 implies NC2
        repl = rule.expandedNC2.r;
        matches = _ruleMatch(rule.expandedNC2.l, res, mergedContext)[0];
      }
    }
    if (matches) {
      // const before = res.toString({parenthesis: 'all'})

      // Create a new node by cloning the rhs of the matched rule
      // we keep any implicit multiplication state if relevant
      var implicit = res.implicit;
      res = repl.clone();
      if (implicit && 'implicit' in repl) {
        res.implicit = true;
      }

      // Replace placeholders with their respective nodes without traversing deeper into the replaced nodes
      res = res.transform(function (node) {
        if (node.isSymbolNode && hasOwnProperty(matches.placeholders, node.name)) {
          return matches.placeholders[node.name].clone();
        } else {
          return node;
        }
      });

      // const after = res.toString({parenthesis: 'all'})
      // console.log('Simplified ' + before + ' to ' + after)
    }
    if (rule.repeat && res !== node) {
      res = applyRule(res, rule, context);
    }
    return res;
  }

  /**
   * Get (binary) combinations of a flattened binary node
   * e.g. +(node1, node2, node3) -> [
   *        +(node1,  +(node2, node3)),
   *        +(node2,  +(node1, node3)),
   *        +(node3,  +(node1, node2))]
   *
   */
  function getSplits(node, context) {
    var res = [];
    var right, rightArgs;
    var makeNode = createMakeNodeFunction(node);
    if (isCommutative(node, context)) {
      for (var i = 0; i < node.args.length; i++) {
        rightArgs = node.args.slice(0);
        rightArgs.splice(i, 1);
        right = rightArgs.length === 1 ? rightArgs[0] : makeNode(rightArgs);
        res.push(makeNode([node.args[i], right]));
      }
    } else {
      // Keep order, but try all parenthesizations
      for (var _i = 1; _i < node.args.length; _i++) {
        var left = node.args[0];
        if (_i > 1) {
          left = makeNode(node.args.slice(0, _i));
        }
        rightArgs = node.args.slice(_i);
        right = rightArgs.length === 1 ? rightArgs[0] : makeNode(rightArgs);
        res.push(makeNode([left, right]));
      }
    }
    return res;
  }

  /**
   * Returns the set union of two match-placeholders or null if there is a conflict.
   */
  function mergeMatch(match1, match2) {
    var res = {
      placeholders: {}
    };

    // Some matches may not have placeholders; this is OK
    if (!match1.placeholders && !match2.placeholders) {
      return res;
    } else if (!match1.placeholders) {
      return match2;
    } else if (!match2.placeholders) {
      return match1;
    }

    // Placeholders with the same key must match exactly
    for (var key in match1.placeholders) {
      if (hasOwnProperty(match1.placeholders, key)) {
        res.placeholders[key] = match1.placeholders[key];
        if (hasOwnProperty(match2.placeholders, key)) {
          if (!_exactMatch(match1.placeholders[key], match2.placeholders[key])) {
            return null;
          }
        }
      }
    }
    for (var _key in match2.placeholders) {
      if (hasOwnProperty(match2.placeholders, _key)) {
        res.placeholders[_key] = match2.placeholders[_key];
      }
    }
    return res;
  }

  /**
   * Combine two lists of matches by applying mergeMatch to the cartesian product of two lists of matches.
   * Each list represents matches found in one child of a node.
   */
  function combineChildMatches(list1, list2) {
    var res = [];
    if (list1.length === 0 || list2.length === 0) {
      return res;
    }
    var merged;
    for (var i1 = 0; i1 < list1.length; i1++) {
      for (var i2 = 0; i2 < list2.length; i2++) {
        merged = mergeMatch(list1[i1], list2[i2]);
        if (merged) {
          res.push(merged);
        }
      }
    }
    return res;
  }

  /**
   * Combine multiple lists of matches by applying mergeMatch to the cartesian product of two lists of matches.
   * Each list represents matches found in one child of a node.
   * Returns a list of unique matches.
   */
  function mergeChildMatches(childMatches) {
    if (childMatches.length === 0) {
      return childMatches;
    }
    var sets = childMatches.reduce(combineChildMatches);
    var uniqueSets = [];
    var unique = {};
    for (var i = 0; i < sets.length; i++) {
      var s = JSON.stringify(sets[i]);
      if (!unique[s]) {
        unique[s] = true;
        uniqueSets.push(sets[i]);
      }
    }
    return uniqueSets;
  }

  /**
   * Determines whether node matches rule.
   *
   * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} rule
   * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
   * @param {Object} context -- provides assumed properties of operators
   * @param {Boolean} isSplit -- whether we are in process of splitting an
   *                    n-ary operator node into possible binary combinations.
   *                    Defaults to false.
   * @return {Object} Information about the match, if it exists.
   */
  function _ruleMatch(rule, node, context, isSplit) {
    //    console.log('Entering _ruleMatch(' + JSON.stringify(rule) + ', ' + JSON.stringify(node) + ')')
    //    console.log('rule = ' + rule)
    //    console.log('node = ' + node)

    //    console.log('Entering _ruleMatch(', rule.toString({parenthesis:'all'}), ', ', node.toString({parenthesis:'all'}), ', ', context, ')')
    var res = [{
      placeholders: {}
    }];
    if (rule instanceof OperatorNode && node instanceof OperatorNode || rule instanceof FunctionNode && node instanceof FunctionNode) {
      // If the rule is an OperatorNode or a FunctionNode, then node must match exactly
      if (rule instanceof OperatorNode) {
        if (rule.op !== node.op || rule.fn !== node.fn) {
          return [];
        }
      } else if (rule instanceof FunctionNode) {
        if (rule.name !== node.name) {
          return [];
        }
      }

      // rule and node match. Search the children of rule and node.
      if (node.args.length === 1 && rule.args.length === 1 || !isAssociative(node, context) && node.args.length === rule.args.length || isSplit) {
        // Expect non-associative operators to match exactly,
        // except in any order if operator is commutative
        var childMatches = [];
        for (var i = 0; i < rule.args.length; i++) {
          var childMatch = _ruleMatch(rule.args[i], node.args[i], context);
          if (childMatch.length === 0) {
            // Child did not match, so stop searching immediately
            break;
          }
          // The child matched, so add the information returned from the child to our result
          childMatches.push(childMatch);
        }
        if (childMatches.length !== rule.args.length) {
          if (!isCommutative(node, context) ||
          // exact match in order needed
          rule.args.length === 1) {
            // nothing to commute
            return [];
          }
          if (rule.args.length > 2) {
            /* Need to generate all permutations and try them.
             * It's a bit complicated, and unlikely to come up since there
             * are very few ternary or higher operators. So punt for now.
             */
            throw new Error('permuting >2 commutative non-associative rule arguments not yet implemented');
          }
          /* Exactly two arguments, try them reversed */
          var leftMatch = _ruleMatch(rule.args[0], node.args[1], context);
          if (leftMatch.length === 0) {
            return [];
          }
          var rightMatch = _ruleMatch(rule.args[1], node.args[0], context);
          if (rightMatch.length === 0) {
            return [];
          }
          childMatches = [leftMatch, rightMatch];
        }
        res = mergeChildMatches(childMatches);
      } else if (node.args.length >= 2 && rule.args.length === 2) {
        // node is flattened, rule is not
        // Associative operators/functions can be split in different ways so we check if the rule
        // matches for each of them and return their union.
        var splits = getSplits(node, context);
        var splitMatches = [];
        for (var _i2 = 0; _i2 < splits.length; _i2++) {
          var matchSet = _ruleMatch(rule, splits[_i2], context, true); // recursing at the same tree depth here
          splitMatches = splitMatches.concat(matchSet);
        }
        return splitMatches;
      } else if (rule.args.length > 2) {
        throw Error('Unexpected non-binary associative function: ' + rule.toString());
      } else {
        // Incorrect number of arguments in rule and node, so no match
        return [];
      }
    } else if (rule instanceof SymbolNode) {
      // If the rule is a SymbolNode, then it carries a special meaning
      // according to the first one or two characters of the symbol node name.
      // These meanings are expalined in the documentation for simplify()
      if (rule.name.length === 0) {
        throw new Error('Symbol in rule has 0 length...!?');
      }
      if (SUPPORTED_CONSTANTS[rule.name]) {
        // built-in constant must match exactly
        if (rule.name !== node.name) {
          return [];
        }
      } else {
        // wildcards are composed of up to two alphabetic or underscore characters
        switch (rule.name[1] >= 'a' && rule.name[1] <= 'z' ? rule.name.substring(0, 2) : rule.name[0]) {
          case 'n':
          case '_p':
            // rule matches _anything_, so assign this node to the rule.name placeholder
            // Assign node to the rule.name placeholder.
            // Our parent will check for matches among placeholders.
            res[0].placeholders[rule.name] = node;
            break;
          case 'c':
          case 'cl':
            // rule matches a ConstantNode
            if (isConstantNode(node)) {
              res[0].placeholders[rule.name] = node;
            } else {
              // mis-match: rule does not encompass current node
              return [];
            }
            break;
          case 'v':
            // rule matches anything other than a ConstantNode
            if (!isConstantNode(node)) {
              res[0].placeholders[rule.name] = node;
            } else {
              // mis-match: rule does not encompass current node
              return [];
            }
            break;
          case 'vl':
            // rule matches VariableNode
            if (isSymbolNode(node)) {
              res[0].placeholders[rule.name] = node;
            } else {
              // mis-match: rule does not encompass current node
              return [];
            }
            break;
          case 'cd':
            // rule matches a ConstantNode or unaryMinus-wrapped ConstantNode
            if (isNumericNode(node)) {
              res[0].placeholders[rule.name] = node;
            } else {
              // mis-match: rule does not encompass current node
              return [];
            }
            break;
          case 'vd':
            // rule matches anything other than a ConstantNode or unaryMinus-wrapped ConstantNode
            if (!isNumericNode(node)) {
              res[0].placeholders[rule.name] = node;
            } else {
              // mis-match: rule does not encompass current node
              return [];
            }
            break;
          case 'ce':
            // rule matches expressions that have a constant value
            if (isConstantExpression(node)) {
              res[0].placeholders[rule.name] = node;
            } else {
              // mis-match: rule does not encompass current node
              return [];
            }
            break;
          case 've':
            // rule matches expressions that do not have a constant value
            if (!isConstantExpression(node)) {
              res[0].placeholders[rule.name] = node;
            } else {
              // mis-match: rule does not encompass current node
              return [];
            }
            break;
          default:
            throw new Error('Invalid symbol in rule: ' + rule.name);
        }
      }
    } else if (rule instanceof ConstantNode) {
      // Literal constant must match exactly
      if (!equal(rule.value, node.value)) {
        return [];
      }
    } else {
      // Some other node was encountered which we aren't prepared for, so no match
      return [];
    }

    // It's a match!

    // console.log('_ruleMatch(' + rule.toString() + ', ' + node.toString() + ') found a match')
    return res;
  }

  /**
   * Determines whether p and q (and all their children nodes) are identical.
   *
   * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} p
   * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} q
   * @return {Object} Information about the match, if it exists.
   */
  function _exactMatch(p, q) {
    if (p instanceof ConstantNode && q instanceof ConstantNode) {
      if (!equal(p.value, q.value)) {
        return false;
      }
    } else if (p instanceof SymbolNode && q instanceof SymbolNode) {
      if (p.name !== q.name) {
        return false;
      }
    } else if (p instanceof OperatorNode && q instanceof OperatorNode || p instanceof FunctionNode && q instanceof FunctionNode) {
      if (p instanceof OperatorNode) {
        if (p.op !== q.op || p.fn !== q.fn) {
          return false;
        }
      } else if (p instanceof FunctionNode) {
        if (p.name !== q.name) {
          return false;
        }
      }
      if (p.args.length !== q.args.length) {
        return false;
      }
      for (var i = 0; i < p.args.length; i++) {
        if (!_exactMatch(p.args[i], q.args[i])) {
          return false;
        }
      }
    } else {
      return false;
    }
    return true;
  }
  return simplify;
});

var name$x = 'simplifyConstant';
var dependencies$x = ['typed', 'config', 'mathWithTransform', 'matrix', '?fraction', '?bignumber', 'AccessorNode', 'ArrayNode', 'ConstantNode', 'FunctionNode', 'IndexNode', 'ObjectNode', 'OperatorNode', 'SymbolNode'];
var createSimplifyConstant = /* #__PURE__ */factory(name$x, dependencies$x, _ref => {
  var {
    typed,
    config,
    mathWithTransform,
    matrix,
    fraction,
    bignumber,
    AccessorNode,
    ArrayNode,
    ConstantNode,
    FunctionNode,
    IndexNode,
    ObjectNode,
    OperatorNode,
    SymbolNode
  } = _ref;
  var {
    isCommutative,
    isAssociative,
    allChildren,
    createMakeNodeFunction
  } = createUtil({
    FunctionNode,
    OperatorNode,
    SymbolNode
  });

  /**
   * simplifyConstant() takes a mathjs expression (either a Node representing
   * a parse tree or a string which it parses to produce a node), and replaces
   * any subexpression of it consisting entirely of constants with the computed
   * value of that subexpression.
   *
   * Syntax:
   *
   *     math.simplifyConstant(expr)
   *     math.simplifyConstant(expr, options)
   *
   * Examples:
   *
   *     math.simplifyConstant('x + 4*3/6')  // Node "x + 2"
   *     math.simplifyConstant('z cos(0)')   // Node "z 1"
   *     math.simplifyConstant('(5.2 + 1.08)t', {exactFractions: false})  // Node "6.28 t"
   *
   * See also:
   *
   *     simplify, simplifyCore, resolve, derivative
   *
   * @param {Node | string} node
   *     The expression to be simplified
   * @param {Object} options
   *     Simplification options, as per simplify()
   * @return {Node} Returns expression with constant subexpressions evaluated
   */
  var simplifyConstant = typed('simplifyConstant', {
    Node: node => _ensureNode(foldFraction(node, {})),
    'Node, Object': function NodeObject(expr, options) {
      return _ensureNode(foldFraction(expr, options));
    }
  });
  function _removeFractions(thing) {
    if (isFraction(thing)) {
      return thing.valueOf();
    }
    if (thing instanceof Array) {
      return thing.map(_removeFractions);
    }
    if (isMatrix(thing)) {
      return matrix(_removeFractions(thing.valueOf()));
    }
    return thing;
  }
  function _eval(fnname, args, options) {
    try {
      return mathWithTransform[fnname].apply(null, args);
    } catch (ignore) {
      // sometimes the implicit type conversion causes the evaluation to fail, so we'll try again after removing Fractions
      args = args.map(_removeFractions);
      return _toNumber(mathWithTransform[fnname].apply(null, args), options);
    }
  }
  var _toNode = typed({
    Fraction: _fractionToNode,
    number: function number(n) {
      if (n < 0) {
        return unaryMinusNode(new ConstantNode(-n));
      }
      return new ConstantNode(n);
    },
    BigNumber: function BigNumber(n) {
      if (n < 0) {
        return unaryMinusNode(new ConstantNode(-n));
      }
      return new ConstantNode(n); // old parameters: (n.toString(), 'number')
    },
    bigint: function bigint(n) {
      if (n < 0n) {
        return unaryMinusNode(new ConstantNode(-n));
      }
      return new ConstantNode(n);
    },
    Complex: function Complex(s) {
      throw new Error('Cannot convert Complex number to Node');
    },
    string: function string(s) {
      return new ConstantNode(s);
    },
    Matrix: function Matrix(m) {
      return new ArrayNode(m.valueOf().map(e => _toNode(e)));
    }
  });
  function _ensureNode(thing) {
    if (isNode(thing)) {
      return thing;
    }
    return _toNode(thing);
  }

  // convert a number to a fraction only if it can be expressed exactly,
  // and when both numerator and denominator are small enough
  function _exactFraction(n, options) {
    var exactFractions = options && options.exactFractions !== false;
    if (exactFractions && isFinite(n) && fraction) {
      var f = fraction(n);
      var fractionsLimit = options && typeof options.fractionsLimit === 'number' ? options.fractionsLimit : Infinity; // no limit by default

      if (f.valueOf() === n && f.n < fractionsLimit && f.d < fractionsLimit) {
        return f;
      }
    }
    return n;
  }

  // Convert numbers to a preferred number type in preference order: Fraction, number, Complex
  // BigNumbers are left alone
  var _toNumber = typed({
    'string, Object': function stringObject(s, options) {
      var numericType = safeNumberType(s, config);
      if (numericType === 'BigNumber') {
        if (bignumber === undefined) {
          noBignumber();
        }
        return bignumber(s);
      } else if (numericType === 'bigint') {
        return BigInt(s);
      } else if (numericType === 'Fraction') {
        if (fraction === undefined) {
          noFraction();
        }
        return fraction(s);
      } else {
        var n = parseFloat(s);
        return _exactFraction(n, options);
      }
    },
    'Fraction, Object': function FractionObject(s, options) {
      return s;
    },
    // we don't need options here

    'BigNumber, Object': function BigNumberObject(s, options) {
      return s;
    },
    // we don't need options here

    'number, Object': function numberObject(s, options) {
      return _exactFraction(s, options);
    },
    'bigint, Object': function bigintObject(s, options) {
      return s;
    },
    'Complex, Object': function ComplexObject(s, options) {
      if (s.im !== 0) {
        return s;
      }
      return _exactFraction(s.re, options);
    },
    'Matrix, Object': function MatrixObject(s, options) {
      return matrix(_exactFraction(s.valueOf()));
    },
    'Array, Object': function ArrayObject(s, options) {
      return s.map(_exactFraction);
    }
  });
  function unaryMinusNode(n) {
    return new OperatorNode('-', 'unaryMinus', [n]);
  }
  function _fractionToNode(f) {
    var n;
    var vn = f.s * f.n;
    if (vn < 0) {
      n = new OperatorNode('-', 'unaryMinus', [new ConstantNode(-vn)]);
    } else {
      n = new ConstantNode(vn);
    }
    if (f.d === 1) {
      return n;
    }
    return new OperatorNode('/', 'divide', [n, new ConstantNode(f.d)]);
  }

  /* Handles constant indexing of ArrayNodes, matrices, and ObjectNodes */
  function _foldAccessor(obj, index, options) {
    if (!isIndexNode(index)) {
      // don't know what to do with that...
      return new AccessorNode(_ensureNode(obj), _ensureNode(index));
    }
    if (isArrayNode(obj) || isMatrix(obj)) {
      var remainingDims = Array.from(index.dimensions);
      /* We will resolve constant indices one at a time, looking
       * just in the first or second dimensions because (a) arrays
       * of more than two dimensions are likely rare, and (b) pulling
       * out the third or higher dimension would be pretty intricate.
       * The price is that we miss simplifying [..3d array][x,y,1]
       */
      while (remainingDims.length > 0) {
        if (isConstantNode(remainingDims[0]) && typeof remainingDims[0].value !== 'string') {
          var first = _toNumber(remainingDims.shift().value, options);
          if (isArrayNode(obj)) {
            obj = obj.items[first - 1];
          } else {
            // matrix
            obj = obj.valueOf()[first - 1];
            if (obj instanceof Array) {
              obj = matrix(obj);
            }
          }
        } else if (remainingDims.length > 1 && isConstantNode(remainingDims[1]) && typeof remainingDims[1].value !== 'string') {
          var second = _toNumber(remainingDims[1].value, options);
          var tryItems = [];
          var fromItems = isArrayNode(obj) ? obj.items : obj.valueOf();
          for (var item of fromItems) {
            if (isArrayNode(item)) {
              tryItems.push(item.items[second - 1]);
            } else if (isMatrix(obj)) {
              tryItems.push(item[second - 1]);
            } else {
              break;
            }
          }
          if (tryItems.length === fromItems.length) {
            if (isArrayNode(obj)) {
              obj = new ArrayNode(tryItems);
            } else {
              // matrix
              obj = matrix(tryItems);
            }
            remainingDims.splice(1, 1);
          } else {
            // extracting slice along 2nd dimension failed, give up
            break;
          }
        } else {
          // neither 1st or 2nd dimension is constant, give up
          break;
        }
      }
      if (remainingDims.length === index.dimensions.length) {
        /* No successful constant indexing */
        return new AccessorNode(_ensureNode(obj), index);
      }
      if (remainingDims.length > 0) {
        /* Indexed some but not all dimensions */
        index = new IndexNode(remainingDims);
        return new AccessorNode(_ensureNode(obj), index);
      }
      /* All dimensions were constant, access completely resolved */
      return obj;
    }
    if (isObjectNode(obj) && index.dimensions.length === 1 && isConstantNode(index.dimensions[0])) {
      var key = index.dimensions[0].value;
      if (key in obj.properties) {
        return obj.properties[key];
      }
      return new ConstantNode(); // undefined
    }
    /* Don't know how to index this sort of obj, at least not with this index */
    return new AccessorNode(_ensureNode(obj), index);
  }

  /*
   * Create a binary tree from a list of Fractions and Nodes.
   * Tries to fold Fractions by evaluating them until the first Node in the list is hit, so
   * `args` should be sorted to have the Fractions at the start (if the operator is commutative).
   * @param args - list of Fractions and Nodes
   * @param fn - evaluator for the binary operation evaluator that accepts two Fractions
   * @param makeNode - creates a binary OperatorNode/FunctionNode from a list of child Nodes
   * if args.length is 1, returns args[0]
   * @return - Either a Node representing a binary expression or Fraction
   */
  function foldOp(fn, args, makeNode, options) {
    var first = args.shift();

    // In the following reduction, sofar always has one of the three following
    // forms: [NODE], [CONSTANT], or [NODE, CONSTANT]
    var reduction = args.reduce((sofar, next) => {
      if (!isNode(next)) {
        var last = sofar.pop();
        if (isNode(last)) {
          return [last, next];
        }
        // Two constants in a row, try to fold them into one
        try {
          sofar.push(_eval(fn, [last, next], options));
          return sofar;
        } catch (ignoreandcontinue) {
          sofar.push(last);
          // fall through to Node case
        }
      }

      // Encountered a Node, or failed folding --
      // collapse everything so far into a single tree:
      sofar.push(_ensureNode(sofar.pop()));
      var newtree = sofar.length === 1 ? sofar[0] : makeNode(sofar);
      return [makeNode([newtree, _ensureNode(next)])];
    }, [first]);
    if (reduction.length === 1) {
      return reduction[0];
    }
    // Might end up with a tree and a constant at the end:
    return makeNode([reduction[0], _toNode(reduction[1])]);
  }

  // destroys the original node and returns a folded one
  function foldFraction(node, options) {
    switch (node.type) {
      case 'SymbolNode':
        return node;
      case 'ConstantNode':
        switch (typeof node.value) {
          case 'number':
            return _toNumber(node.value, options);
          case 'bigint':
            return _toNumber(node.value, options);
          case 'string':
            return node.value;
          default:
            if (!isNaN(node.value)) return _toNumber(node.value, options);
        }
        return node;
      case 'FunctionNode':
        if (mathWithTransform[node.name] && mathWithTransform[node.name].rawArgs) {
          return node;
        }
        {
          // Process operators as OperatorNode
          var operatorFunctions = ['add', 'multiply'];
          if (!operatorFunctions.includes(node.name)) {
            var args = node.args.map(arg => foldFraction(arg, options));

            // If all args are numbers
            if (!args.some(isNode)) {
              try {
                return _eval(node.name, args, options);
              } catch (ignoreandcontinue) {}
            }

            // Size of a matrix does not depend on entries
            if (node.name === 'size' && args.length === 1 && isArrayNode(args[0])) {
              var sz = [];
              var section = args[0];
              while (isArrayNode(section)) {
                sz.push(section.items.length);
                section = section.items[0];
              }
              return matrix(sz);
            }

            // Convert all args to nodes and construct a symbolic function call
            return new FunctionNode(node.name, args.map(_ensureNode));
          }
        }
      /* falls through */
      case 'OperatorNode':
        {
          var fn = node.fn.toString();
          var _args;
          var res;
          var makeNode = createMakeNodeFunction(node);
          if (isOperatorNode(node) && node.isUnary()) {
            _args = [foldFraction(node.args[0], options)];
            if (!isNode(_args[0])) {
              res = _eval(fn, _args, options);
            } else {
              res = makeNode(_args);
            }
          } else if (isAssociative(node, options.context)) {
            _args = allChildren(node, options.context);
            _args = _args.map(arg => foldFraction(arg, options));
            if (isCommutative(fn, options.context)) {
              // commutative binary operator
              var consts = [];
              var vars = [];
              for (var i = 0; i < _args.length; i++) {
                if (!isNode(_args[i])) {
                  consts.push(_args[i]);
                } else {
                  vars.push(_args[i]);
                }
              }
              if (consts.length > 1) {
                res = foldOp(fn, consts, makeNode, options);
                vars.unshift(res);
                res = foldOp(fn, vars, makeNode, options);
              } else {
                // we won't change the children order since it's not neccessary
                res = foldOp(fn, _args, makeNode, options);
              }
            } else {
              // non-commutative binary operator
              res = foldOp(fn, _args, makeNode, options);
            }
          } else {
            // non-associative binary operator
            _args = node.args.map(arg => foldFraction(arg, options));
            res = foldOp(fn, _args, makeNode, options);
          }
          return res;
        }
      case 'ParenthesisNode':
        // remove the uneccessary parenthesis
        return foldFraction(node.content, options);
      case 'AccessorNode':
        return _foldAccessor(foldFraction(node.object, options), foldFraction(node.index, options), options);
      case 'ArrayNode':
        {
          var foldItems = node.items.map(item => foldFraction(item, options));
          if (foldItems.some(isNode)) {
            return new ArrayNode(foldItems.map(_ensureNode));
          }
          /* All literals -- return a Matrix so we can operate on it */
          return matrix(foldItems);
        }
      case 'IndexNode':
        {
          return new IndexNode(node.dimensions.map(n => simplifyConstant(n, options)));
        }
      case 'ObjectNode':
        {
          var foldProps = {};
          for (var prop in node.properties) {
            foldProps[prop] = simplifyConstant(node.properties[prop], options);
          }
          return new ObjectNode(foldProps);
        }
      case 'AssignmentNode':
      /* falls through */
      case 'BlockNode':
      /* falls through */
      case 'FunctionAssignmentNode':
      /* falls through */
      case 'RangeNode':
      /* falls through */
      case 'ConditionalNode':
      /* falls through */
      default:
        throw new Error("Unimplemented node type in simplifyConstant: ".concat(node.type));
    }
  }
  return simplifyConstant;
});

var name$w = 'simplifyCore';
var dependencies$w = ['typed', 'parse', 'equal', 'isZero', 'add', 'subtract', 'multiply', 'divide', 'pow', 'AccessorNode', 'ArrayNode', 'ConstantNode', 'FunctionNode', 'IndexNode', 'ObjectNode', 'OperatorNode', 'ParenthesisNode', 'SymbolNode'];
var createSimplifyCore = /* #__PURE__ */factory(name$w, dependencies$w, _ref => {
  var {
    typed,
    parse,
    equal,
    isZero,
    add,
    subtract,
    multiply,
    divide,
    pow,
    AccessorNode,
    ArrayNode,
    ConstantNode,
    FunctionNode,
    IndexNode,
    ObjectNode,
    OperatorNode,
    ParenthesisNode,
    SymbolNode
  } = _ref;
  var node0 = new ConstantNode(0);
  var node1 = new ConstantNode(1);
  var nodeT = new ConstantNode(true);
  var nodeF = new ConstantNode(false);
  // test if a node will always have a boolean value (true/false)
  // not sure if this list is complete
  function isAlwaysBoolean(node) {
    return isOperatorNode(node) && ['and', 'not', 'or'].includes(node.op);
  }
  var {
    hasProperty,
    isCommutative
  } = createUtil({
    FunctionNode,
    OperatorNode,
    SymbolNode
  });
  /**
   * simplifyCore() performs single pass simplification suitable for
   * applications requiring ultimate performance. To roughly summarize,
   * it handles cases along the lines of simplifyConstant() but where
   * knowledge of a single argument is sufficient to determine the value.
   * In contrast, simplify() extends simplifyCore() with additional passes
   * to provide deeper simplification (such as gathering like terms).
   *
   * Specifically, simplifyCore:
   *
   * * Converts all function calls with operator equivalents to their
   *   operator forms.
   * * Removes operators or function calls that are guaranteed to have no
   *   effect (such as unary '+').
   * * Removes double unary '-', '~', and 'not'
   * * Eliminates addition/subtraction of 0 and multiplication/division/powers
   *   by 1 or 0.
   * * Converts addition of a negation into subtraction.
   * * Eliminates logical operations with constant true or false leading
   *   arguments.
   * * Puts constants on the left of a product, if multiplication is
   *   considered commutative by the options (which is the default)
   *
   * Syntax:
   *
   *     math.simplifyCore(expr)
   *     math.simplifyCore(expr, options)
   *
   * Examples:
   *
   *     const f = math.parse('2 * 1 * x ^ (1 - 0)')
   *     math.simplifyCore(f)                          // Node "2 * x"
   *     math.simplify('2 * 1 * x ^ (1 - 0)', [math.simplifyCore]) // Node "2 * x"
   *
   * See also:
   *
   *     simplify, simplifyConstant, resolve, derivative
   *
   * @param {Node | string} node
   *     The expression to be simplified
   * @param {Object} options
   *     Simplification options, as per simplify()
   * @return {Node} Returns expression with basic simplifications applied
   */
  function _simplifyCore(nodeToSimplify) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var context = options ? options.context : undefined;
    if (hasProperty(nodeToSimplify, 'trivial', context)) {
      // This node does nothing if it has only one argument, so if so,
      // return that argument simplified
      if (isFunctionNode(nodeToSimplify) && nodeToSimplify.args.length === 1) {
        return _simplifyCore(nodeToSimplify.args[0], options);
      }
      // For other node types, we try the generic methods
      var simpChild = false;
      var childCount = 0;
      nodeToSimplify.forEach(c => {
        ++childCount;
        if (childCount === 1) {
          simpChild = _simplifyCore(c, options);
        }
      });
      if (childCount === 1) {
        return simpChild;
      }
    }
    var node = nodeToSimplify;
    if (isFunctionNode(node)) {
      var op = getOperator(node.name);
      if (op) {
        // Replace FunctionNode with a new OperatorNode
        if (node.args.length > 2 && hasProperty(node, 'associative', context)) {
          // unflatten into binary operations since that's what simplifyCore handles
          while (node.args.length > 2) {
            var last = node.args.pop();
            var seclast = node.args.pop();
            node.args.push(new OperatorNode(op, node.name, [last, seclast]));
          }
        }
        node = new OperatorNode(op, node.name, node.args);
      } else {
        return new FunctionNode(_simplifyCore(node.fn), node.args.map(n => _simplifyCore(n, options)));
      }
    }
    if (isOperatorNode(node) && node.isUnary()) {
      var a0 = _simplifyCore(node.args[0], options);
      if (node.op === '~') {
        // bitwise not
        if (isOperatorNode(a0) && a0.isUnary() && a0.op === '~') {
          return a0.args[0];
        }
      }
      if (node.op === 'not') {
        // logical not
        if (isOperatorNode(a0) && a0.isUnary() && a0.op === 'not') {
          // Has the effect of turning the argument into a boolean
          // So can only eliminate the double negation if
          // the inside is already boolean
          if (isAlwaysBoolean(a0.args[0])) {
            return a0.args[0];
          }
        }
      }
      var finish = true;
      if (node.op === '-') {
        // unary minus
        if (isOperatorNode(a0)) {
          if (a0.isBinary() && a0.fn === 'subtract') {
            node = new OperatorNode('-', 'subtract', [a0.args[1], a0.args[0]]);
            finish = false; // continue to process the new binary node
          }
          if (a0.isUnary() && a0.op === '-') {
            return a0.args[0];
          }
        }
      }
      if (finish) return new OperatorNode(node.op, node.fn, [a0]);
    }
    if (isOperatorNode(node) && node.isBinary()) {
      var _a = _simplifyCore(node.args[0], options);
      var a1 = _simplifyCore(node.args[1], options);
      if (node.op === '+') {
        if (isConstantNode(_a) && isZero(_a.value)) {
          return a1;
        }
        if (isConstantNode(a1) && isZero(a1.value)) {
          return _a;
        }
        if (isOperatorNode(a1) && a1.isUnary() && a1.op === '-') {
          a1 = a1.args[0];
          node = new OperatorNode('-', 'subtract', [_a, a1]);
        }
      }
      if (node.op === '-') {
        if (isOperatorNode(a1) && a1.isUnary() && a1.op === '-') {
          return _simplifyCore(new OperatorNode('+', 'add', [_a, a1.args[0]]), options);
        }
        if (isConstantNode(_a) && isZero(_a.value)) {
          return _simplifyCore(new OperatorNode('-', 'unaryMinus', [a1]));
        }
        if (isConstantNode(a1) && isZero(a1.value)) {
          return _a;
        }
        return new OperatorNode(node.op, node.fn, [_a, a1]);
      }
      if (node.op === '*') {
        if (isConstantNode(_a)) {
          if (isZero(_a.value)) {
            return node0;
          } else if (equal(_a.value, 1)) {
            return a1;
          }
        }
        if (isConstantNode(a1)) {
          if (isZero(a1.value)) {
            return node0;
          } else if (equal(a1.value, 1)) {
            return _a;
          }
          if (isCommutative(node, context)) {
            return new OperatorNode(node.op, node.fn, [a1, _a], node.implicit); // constants on left
          }
        }
        return new OperatorNode(node.op, node.fn, [_a, a1], node.implicit);
      }
      if (node.op === '/') {
        if (isConstantNode(_a) && isZero(_a.value)) {
          return node0;
        }
        if (isConstantNode(a1) && equal(a1.value, 1)) {
          return _a;
        }
        return new OperatorNode(node.op, node.fn, [_a, a1]);
      }
      if (node.op === '^') {
        if (isConstantNode(a1)) {
          if (isZero(a1.value)) {
            return node1;
          } else if (equal(a1.value, 1)) {
            return _a;
          }
        }
      }
      if (node.op === 'and') {
        if (isConstantNode(_a)) {
          if (_a.value) {
            if (isAlwaysBoolean(a1)) return a1;
            if (isConstantNode(a1)) {
              return a1.value ? nodeT : nodeF;
            }
          } else {
            return nodeF;
          }
        }
        if (isConstantNode(a1)) {
          if (a1.value) {
            if (isAlwaysBoolean(_a)) return _a;
          } else {
            return nodeF;
          }
        }
      }
      if (node.op === 'or') {
        if (isConstantNode(_a)) {
          if (_a.value) {
            return nodeT;
          } else {
            if (isAlwaysBoolean(a1)) return a1;
          }
        }
        if (isConstantNode(a1)) {
          if (a1.value) {
            return nodeT;
          } else {
            if (isAlwaysBoolean(_a)) return _a;
          }
        }
      }
      return new OperatorNode(node.op, node.fn, [_a, a1]);
    }
    if (isOperatorNode(node)) {
      return new OperatorNode(node.op, node.fn, node.args.map(a => _simplifyCore(a, options)));
    }
    if (isArrayNode(node)) {
      return new ArrayNode(node.items.map(n => _simplifyCore(n, options)));
    }
    if (isAccessorNode(node)) {
      return new AccessorNode(_simplifyCore(node.object, options), _simplifyCore(node.index, options));
    }
    if (isIndexNode(node)) {
      return new IndexNode(node.dimensions.map(n => _simplifyCore(n, options)));
    }
    if (isObjectNode(node)) {
      var newProps = {};
      for (var prop in node.properties) {
        newProps[prop] = _simplifyCore(node.properties[prop], options);
      }
      return new ObjectNode(newProps);
    }
    // cannot simplify
    return node;
  }
  return typed(name$w, {
    Node: _simplifyCore,
    'Node,Object': _simplifyCore
  });
});

var name$v = 'resolve';
var dependencies$v = ['typed', 'parse', 'ConstantNode', 'FunctionNode', 'OperatorNode', 'ParenthesisNode'];
var createResolve = /* #__PURE__ */factory(name$v, dependencies$v, _ref => {
  var {
    typed,
    parse,
    ConstantNode,
    FunctionNode,
    OperatorNode,
    ParenthesisNode
  } = _ref;
  /**
   * resolve(expr, scope) replaces variable nodes with their scoped values
   *
   * Syntax:
   *
   *     math.resolve(expr, scope)
   *
   * Examples:
   *
   *     math.resolve('x + y', {x:1, y:2})           // Node '1 + 2'
   *     math.resolve(math.parse('x+y'), {x:1, y:2}) // Node '1 + 2'
   *     math.simplify('x+y', {x:2, y: math.parse('x+x')}).toString() // "6"
   *
   * See also:
   *
   *     simplify, evaluate
   *
   * @param {Node | Node[]} node
   *     The expression tree (or trees) to be simplified
   * @param {Object} scope
   *     Scope specifying variables to be resolved
   * @return {Node | Node[]} Returns `node` with variables recursively substituted.
   * @throws {ReferenceError}
   *     If there is a cyclic dependency among the variables in `scope`,
   *     resolution is impossible and a ReferenceError is thrown.
   */
  function _resolve(node, scope) {
    var within = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set();
    // note `within`:
    // `within` is not documented, since it is for internal cycle
    // detection only
    if (!scope) {
      return node;
    }
    if (isSymbolNode(node)) {
      if (within.has(node.name)) {
        var variables = Array.from(within).join(', ');
        throw new ReferenceError("recursive loop of variable definitions among {".concat(variables, "}"));
      }
      var value = scope.get(node.name);
      if (isNode(value)) {
        var nextWithin = new Set(within);
        nextWithin.add(node.name);
        return _resolve(value, scope, nextWithin);
      } else if (typeof value === 'number') {
        return parse(String(value));
      } else if (value !== undefined) {
        return new ConstantNode(value);
      } else {
        return node;
      }
    } else if (isOperatorNode(node)) {
      var args = node.args.map(function (arg) {
        return _resolve(arg, scope, within);
      });
      return new OperatorNode(node.op, node.fn, args, node.implicit);
    } else if (isParenthesisNode(node)) {
      return new ParenthesisNode(_resolve(node.content, scope, within));
    } else if (isFunctionNode(node)) {
      var _args = node.args.map(function (arg) {
        return _resolve(arg, scope, within);
      });
      return new FunctionNode(node.name, _args);
    }

    // Otherwise just recursively resolve any children (might also work
    // for some of the above special cases)
    return node.map(child => _resolve(child, scope, within));
  }
  return typed('resolve', {
    Node: _resolve,
    'Node, Map | null | undefined': _resolve,
    'Node, Object': (n, scope) => _resolve(n, createMap$1(scope)),
    // For arrays and matrices, we map `self` rather than `_resolve`
    // because resolve is fairly expensive anyway, and this way
    // we get nice error messages if one entry in the array has wrong type.
    'Array | Matrix': typed.referToSelf(self => A => A.map(n => self(n))),
    'Array | Matrix, null | undefined': typed.referToSelf(self => A => A.map(n => self(n))),
    'Array, Object': typed.referTo('Array,Map', selfAM => (A, scope) => selfAM(A, createMap$1(scope))),
    'Matrix, Object': typed.referTo('Matrix,Map', selfMM => (A, scope) => selfMM(A, createMap$1(scope))),
    'Array | Matrix, Map': typed.referToSelf(self => (A, scope) => A.map(n => self(n, scope)))
  });
});

var name$u = 'symbolicEqual';
var dependencies$u = ['parse', 'simplify', 'typed', 'OperatorNode'];
var createSymbolicEqual = /* #__PURE__ */factory(name$u, dependencies$u, _ref => {
  var {
    parse,
    simplify,
    typed,
    OperatorNode
  } = _ref;
  /**
   * Attempts to determine if two expressions are symbolically equal, i.e.
   * one is the result of valid algebraic manipulations on the other.
   * Currently, this simply checks if the difference of the two expressions
   * simplifies down to 0. So there are two important caveats:
   * 1. whether two expressions are symbolically equal depends on the
   *     manipulations allowed. Therefore, this function takes an optional
   *     third argument, which are the options that control the behavior
   *     as documented for the `simplify()` function.
   * 2. it is in general intractable to find the minimal simplification of
   *     an arbitrarily complicated expression. So while a `true` value
   *     of `symbolicEqual` ensures that the two expressions can be manipulated
   *     to match each other, a `false` value does not absolutely rule this out.
   *
   * Syntax:
   *
   *     math.symbolicEqual(expr1, expr2)
   *     math.symbolicEqual(expr1, expr2, options)
   *
   * Examples:
   *
   *     math.symbolicEqual('x*y', 'y*x') // Returns true
   *     math.symbolicEqual('x*y', 'y*x', {context: {multiply: {commutative: false}}}) // Returns false
   *     math.symbolicEqual('x/y', '(y*x^(-1))^(-1)') // Returns true
   *     math.symbolicEqual('abs(x)','x') // Returns false
   *     math.symbolicEqual('abs(x)','x', simplify.positiveContext) // Returns true
   *
   * See also:
   *
   *     simplify, evaluate
   *
   * @param {Node|string} expr1  The first expression to compare
   * @param {Node|string} expr2  The second expression to compare
   * @param {Object} [options] Optional option object, passed to simplify
   * @returns {boolean}
   *     Returns true if a valid manipulation making the expressions equal
   *     is found.
   */
  function _symbolicEqual(e1, e2) {
    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    var diff = new OperatorNode('-', 'subtract', [e1, e2]);
    var simplified = simplify(diff, {}, options);
    return isConstantNode(simplified) && !simplified.value;
  }
  return typed(name$u, {
    'Node, Node': _symbolicEqual,
    'Node, Node, Object': _symbolicEqual
  });
});

var name$t = 'derivative';
var dependencies$t = ['typed', 'config', 'parse', 'simplify', 'equal', 'isZero', 'numeric', 'ConstantNode', 'FunctionNode', 'OperatorNode', 'ParenthesisNode', 'SymbolNode'];
var createDerivative = /* #__PURE__ */factory(name$t, dependencies$t, _ref => {
  var {
    typed,
    config,
    parse,
    simplify,
    equal,
    isZero,
    numeric,
    ConstantNode,
    FunctionNode,
    OperatorNode,
    ParenthesisNode,
    SymbolNode
  } = _ref;
  /**
   * 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.
   *
   * This uses rules of differentiation which can be found here:
   *
   * - [Differentiation rules (Wikipedia)](https://en.wikipedia.org/wiki/Differentiation_rules)
   *
   * Syntax:
   *
   *     math.derivative(expr, variable)
   *     math.derivative(expr, variable, options)
   *
   * Examples:
   *
   *     math.derivative('x^2', 'x')                     // Node '2 * x'
   *     math.derivative('x^2', 'x', {simplify: false})  // Node '2 * 1 * x ^ (2 - 1)'
   *     math.derivative('sin(2x)', 'x'))                // Node '2 * cos(2 * x)'
   *     math.derivative('2*x', 'x').evaluate()          // number 2
   *     math.derivative('x^2', 'x').evaluate({x: 4})    // number 8
   *     const f = math.parse('x^2')
   *     const x = math.parse('x')
   *     math.derivative(f, x)                           // Node {2 * x}
   *
   * See also:
   *
   *     simplify, parse, evaluate
   *
   * @param  {Node | string} expr           The expression to differentiate
   * @param  {SymbolNode | string} variable The variable over which to differentiate
   * @param  {{simplify: boolean}} [options]
   *                         There is one option available, `simplify`, which
   *                         is true by default. When false, output will not
   *                         be simplified.
   * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode}    The derivative of `expr`
   */
  function plainDerivative(expr, variable) {
    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
      simplify: true
    };
    var constNodes = {};
    constTag(constNodes, expr, variable.name);
    var res = _derivative(expr, constNodes);
    return options.simplify ? simplify(res) : res;
  }
  typed.addConversion({
    from: 'identifier',
    to: 'SymbolNode',
    convert: parse
  });
  var derivative = typed(name$t, {
    'Node, SymbolNode': plainDerivative,
    'Node, SymbolNode, Object': plainDerivative

    /* TODO: implement and test syntax with order of derivatives -> implement as an option {order: number}
    'Node, SymbolNode, ConstantNode': function (expr, variable, {order}) {
      let res = expr
      for (let i = 0; i < order; i++) {
        let constNodes = {}
        constTag(constNodes, expr, variable.name)
        res = _derivative(res, constNodes)
      }
      return res
    }
    */
  });
  typed.removeConversion({
    from: 'identifier',
    to: 'SymbolNode',
    convert: parse
  });
  derivative._simplify = true;
  derivative.toTex = function (deriv) {
    return _derivTex.apply(null, deriv.args);
  };

  // FIXME: move the toTex method of derivative to latex.js. Difficulty is that it relies on parse.
  // NOTE: the optional "order" parameter here is currently unused
  var _derivTex = typed('_derivTex', {
    'Node, SymbolNode': function NodeSymbolNode(expr, x) {
      if (isConstantNode(expr) && typeOf(expr.value) === 'string') {
        return _derivTex(parse(expr.value).toString(), x.toString(), 1);
      } else {
        return _derivTex(expr.toTex(), x.toString(), 1);
      }
    },
    'Node, ConstantNode': function NodeConstantNode(expr, x) {
      if (typeOf(x.value) === 'string') {
        return _derivTex(expr, parse(x.value));
      } else {
        throw new Error("The second parameter to 'derivative' is a non-string constant");
      }
    },
    'Node, SymbolNode, ConstantNode': function NodeSymbolNodeConstantNode(expr, x, order) {
      return _derivTex(expr.toString(), x.name, order.value);
    },
    'string, string, number': function stringStringNumber(expr, x, order) {
      var d;
      if (order === 1) {
        d = '{d\\over d' + x + '}';
      } else {
        d = '{d^{' + order + '}\\over d' + x + '^{' + order + '}}';
      }
      return d + "\\left[".concat(expr, "\\right]");
    }
  });

  /**
   * Does a depth-first search on the expression tree to identify what Nodes
   * are constants (e.g. 2 + 2), and stores the ones that are constants in
   * constNodes. Classification is done as follows:
   *
   *   1. ConstantNodes are constants.
   *   2. If there exists a SymbolNode, of which we are differentiating over,
   *      in the subtree it is not constant.
   *
   * @param  {Object} constNodes  Holds the nodes that are constant
   * @param  {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
   * @param  {string} varName     Variable that we are differentiating
   * @return {boolean}  if node is constant
   */
  // TODO: can we rewrite constTag into a pure function?
  var constTag = typed('constTag', {
    'Object, ConstantNode, string': function ObjectConstantNodeString(constNodes, node) {
      constNodes[node] = true;
      return true;
    },
    'Object, SymbolNode, string': function ObjectSymbolNodeString(constNodes, node, varName) {
      // Treat other variables like constants. For reasoning, see:
      //   https://en.wikipedia.org/wiki/Partial_derivative
      if (node.name !== varName) {
        constNodes[node] = true;
        return true;
      }
      return false;
    },
    'Object, ParenthesisNode, string': function ObjectParenthesisNodeString(constNodes, node, varName) {
      return constTag(constNodes, node.content, varName);
    },
    'Object, FunctionAssignmentNode, string': function ObjectFunctionAssignmentNodeString(constNodes, node, varName) {
      if (!node.params.includes(varName)) {
        constNodes[node] = true;
        return true;
      }
      return constTag(constNodes, node.expr, varName);
    },
    'Object, FunctionNode | OperatorNode, string': function ObjectFunctionNodeOperatorNodeString(constNodes, node, varName) {
      if (node.args.length > 0) {
        var isConst = constTag(constNodes, node.args[0], varName);
        for (var i = 1; i < node.args.length; ++i) {
          isConst = constTag(constNodes, node.args[i], varName) && isConst;
        }
        if (isConst) {
          constNodes[node] = true;
          return true;
        }
      }
      return false;
    }
  });

  /**
   * Applies differentiation rules.
   *
   * @param  {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
   * @param  {Object} constNodes  Holds the nodes that are constant
   * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode}    The derivative of `expr`
   */
  var _derivative = typed('_derivative', {
    'ConstantNode, Object': function ConstantNodeObject(node) {
      return createConstantNode(0);
    },
    'SymbolNode, Object': function SymbolNodeObject(node, constNodes) {
      if (constNodes[node] !== undefined) {
        return createConstantNode(0);
      }
      return createConstantNode(1);
    },
    'ParenthesisNode, Object': function ParenthesisNodeObject(node, constNodes) {
      return new ParenthesisNode(_derivative(node.content, constNodes));
    },
    'FunctionAssignmentNode, Object': function FunctionAssignmentNodeObject(node, constNodes) {
      if (constNodes[node] !== undefined) {
        return createConstantNode(0);
      }
      return _derivative(node.expr, constNodes);
    },
    'FunctionNode, Object': function FunctionNodeObject(node, constNodes) {
      if (constNodes[node] !== undefined) {
        return createConstantNode(0);
      }
      var arg0 = node.args[0];
      var arg1;
      var div = false; // is output a fraction?
      var negative = false; // is output negative?

      var funcDerivative;
      switch (node.name) {
        case 'cbrt':
          // d/dx(cbrt(x)) = 1 / (3x^(2/3))
          div = true;
          funcDerivative = new OperatorNode('*', 'multiply', [createConstantNode(3), new OperatorNode('^', 'pow', [arg0, new OperatorNode('/', 'divide', [createConstantNode(2), createConstantNode(3)])])]);
          break;
        case 'sqrt':
        case 'nthRoot':
          // d/dx(sqrt(x)) = 1 / (2*sqrt(x))
          if (node.args.length === 1) {
            div = true;
            funcDerivative = new OperatorNode('*', 'multiply', [createConstantNode(2), new FunctionNode('sqrt', [arg0])]);
          } else if (node.args.length === 2) {
            // Rearrange from nthRoot(x, a) -> x^(1/a)
            arg1 = new OperatorNode('/', 'divide', [createConstantNode(1), node.args[1]]);

            // Is a variable?
            constNodes[arg1] = constNodes[node.args[1]];
            return _derivative(new OperatorNode('^', 'pow', [arg0, arg1]), constNodes);
          }
          break;
        case 'log10':
          arg1 = createConstantNode(10);
        /* fall through! */
        case 'log':
          if (!arg1 && node.args.length === 1) {
            // d/dx(log(x)) = 1 / x
            funcDerivative = arg0.clone();
            div = true;
          } else if (node.args.length === 1 && arg1 || node.args.length === 2 && constNodes[node.args[1]] !== undefined) {
            // d/dx(log(x, c)) = 1 / (x*ln(c))
            funcDerivative = new OperatorNode('*', 'multiply', [arg0.clone(), new FunctionNode('log', [arg1 || node.args[1]])]);
            div = true;
          } else if (node.args.length === 2) {
            // d/dx(log(f(x), g(x))) = d/dx(log(f(x)) / log(g(x)))
            return _derivative(new OperatorNode('/', 'divide', [new FunctionNode('log', [arg0]), new FunctionNode('log', [node.args[1]])]), constNodes);
          }
          break;
        case 'pow':
          if (node.args.length === 2) {
            constNodes[arg1] = constNodes[node.args[1]];
            // Pass to pow operator node parser
            return _derivative(new OperatorNode('^', 'pow', [arg0, node.args[1]]), constNodes);
          }
          break;
        case 'exp':
          // d/dx(e^x) = e^x
          funcDerivative = new FunctionNode('exp', [arg0.clone()]);
          break;
        case 'sin':
          // d/dx(sin(x)) = cos(x)
          funcDerivative = new FunctionNode('cos', [arg0.clone()]);
          break;
        case 'cos':
          // d/dx(cos(x)) = -sin(x)
          funcDerivative = new OperatorNode('-', 'unaryMinus', [new FunctionNode('sin', [arg0.clone()])]);
          break;
        case 'tan':
          // d/dx(tan(x)) = sec(x)^2
          funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('sec', [arg0.clone()]), createConstantNode(2)]);
          break;
        case 'sec':
          // d/dx(sec(x)) = sec(x)tan(x)
          funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('tan', [arg0.clone()])]);
          break;
        case 'csc':
          // d/dx(csc(x)) = -csc(x)cot(x)
          negative = true;
          funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('cot', [arg0.clone()])]);
          break;
        case 'cot':
          // d/dx(cot(x)) = -csc(x)^2
          negative = true;
          funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('csc', [arg0.clone()]), createConstantNode(2)]);
          break;
        case 'asin':
          // d/dx(asin(x)) = 1 / sqrt(1 - x^2)
          div = true;
          funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])]);
          break;
        case 'acos':
          // d/dx(acos(x)) = -1 / sqrt(1 - x^2)
          div = true;
          negative = true;
          funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])]);
          break;
        case 'atan':
          // d/dx(atan(x)) = 1 / (x^2 + 1)
          div = true;
          funcDerivative = new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)]);
          break;
        case 'asec':
          // d/dx(asec(x)) = 1 / (|x|*sqrt(x^2 - 1))
          div = true;
          funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]);
          break;
        case 'acsc':
          // d/dx(acsc(x)) = -1 / (|x|*sqrt(x^2 - 1))
          div = true;
          negative = true;
          funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]);
          break;
        case 'acot':
          // d/dx(acot(x)) = -1 / (x^2 + 1)
          div = true;
          negative = true;
          funcDerivative = new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)]);
          break;
        case 'sinh':
          // d/dx(sinh(x)) = cosh(x)
          funcDerivative = new FunctionNode('cosh', [arg0.clone()]);
          break;
        case 'cosh':
          // d/dx(cosh(x)) = sinh(x)
          funcDerivative = new FunctionNode('sinh', [arg0.clone()]);
          break;
        case 'tanh':
          // d/dx(tanh(x)) = sech(x)^2
          funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('sech', [arg0.clone()]), createConstantNode(2)]);
          break;
        case 'sech':
          // d/dx(sech(x)) = -sech(x)tanh(x)
          negative = true;
          funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('tanh', [arg0.clone()])]);
          break;
        case 'csch':
          // d/dx(csch(x)) = -csch(x)coth(x)
          negative = true;
          funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('coth', [arg0.clone()])]);
          break;
        case 'coth':
          // d/dx(coth(x)) = -csch(x)^2
          negative = true;
          funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('csch', [arg0.clone()]), createConstantNode(2)]);
          break;
        case 'asinh':
          // d/dx(asinh(x)) = 1 / sqrt(x^2 + 1)
          div = true;
          funcDerivative = new FunctionNode('sqrt', [new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])]);
          break;
        case 'acosh':
          // d/dx(acosh(x)) = 1 / sqrt(x^2 - 1); XXX potentially only for x >= 1 (the real spectrum)
          div = true;
          funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])]);
          break;
        case 'atanh':
          // d/dx(atanh(x)) = 1 / (1 - x^2)
          div = true;
          funcDerivative = new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])]);
          break;
        case 'asech':
          // d/dx(asech(x)) = -1 / (x*sqrt(1 - x^2))
          div = true;
          negative = true;
          funcDerivative = new OperatorNode('*', 'multiply', [arg0.clone(), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])])]);
          break;
        case 'acsch':
          // d/dx(acsch(x)) = -1 / (|x|*sqrt(x^2 + 1))
          div = true;
          negative = true;
          funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]);
          break;
        case 'acoth':
          // d/dx(acoth(x)) = -1 / (1 - x^2)
          div = true;
          negative = true;
          funcDerivative = new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])]);
          break;
        case 'abs':
          // d/dx(abs(x)) = abs(x)/x
          funcDerivative = new OperatorNode('/', 'divide', [new FunctionNode(new SymbolNode('abs'), [arg0.clone()]), arg0.clone()]);
          break;
        case 'gamma': // Needs digamma function, d/dx(gamma(x)) = gamma(x)digamma(x)
        default:
          throw new Error('Cannot process function "' + node.name + '" in derivative: ' + 'the function is not supported, undefined, or the number of arguments passed to it are not supported');
      }
      var op, func;
      if (div) {
        op = '/';
        func = 'divide';
      } else {
        op = '*';
        func = 'multiply';
      }

      /* Apply chain rule to all functions:
         F(x)  = f(g(x))
         F'(x) = g'(x)*f'(g(x)) */
      var chainDerivative = _derivative(arg0, constNodes);
      if (negative) {
        chainDerivative = new OperatorNode('-', 'unaryMinus', [chainDerivative]);
      }
      return new OperatorNode(op, func, [chainDerivative, funcDerivative]);
    },
    'OperatorNode, Object': function OperatorNodeObject(node, constNodes) {
      if (constNodes[node] !== undefined) {
        return createConstantNode(0);
      }
      if (node.op === '+') {
        // d/dx(sum(f(x)) = sum(f'(x))
        return new OperatorNode(node.op, node.fn, node.args.map(function (arg) {
          return _derivative(arg, constNodes);
        }));
      }
      if (node.op === '-') {
        // d/dx(+/-f(x)) = +/-f'(x)
        if (node.isUnary()) {
          return new OperatorNode(node.op, node.fn, [_derivative(node.args[0], constNodes)]);
        }

        // Linearity of differentiation, d/dx(f(x) +/- g(x)) = f'(x) +/- g'(x)
        if (node.isBinary()) {
          return new OperatorNode(node.op, node.fn, [_derivative(node.args[0], constNodes), _derivative(node.args[1], constNodes)]);
        }
      }
      if (node.op === '*') {
        // d/dx(c*f(x)) = c*f'(x)
        var constantTerms = node.args.filter(function (arg) {
          return constNodes[arg] !== undefined;
        });
        if (constantTerms.length > 0) {
          var nonConstantTerms = node.args.filter(function (arg) {
            return constNodes[arg] === undefined;
          });
          var nonConstantNode = nonConstantTerms.length === 1 ? nonConstantTerms[0] : new OperatorNode('*', 'multiply', nonConstantTerms);
          var newArgs = constantTerms.concat(_derivative(nonConstantNode, constNodes));
          return new OperatorNode('*', 'multiply', newArgs);
        }

        // Product Rule, d/dx(f(x)*g(x)) = f'(x)*g(x) + f(x)*g'(x)
        return new OperatorNode('+', 'add', node.args.map(function (argOuter) {
          return new OperatorNode('*', 'multiply', node.args.map(function (argInner) {
            return argInner === argOuter ? _derivative(argInner, constNodes) : argInner.clone();
          }));
        }));
      }
      if (node.op === '/' && node.isBinary()) {
        var arg0 = node.args[0];
        var arg1 = node.args[1];

        // d/dx(f(x) / c) = f'(x) / c
        if (constNodes[arg1] !== undefined) {
          return new OperatorNode('/', 'divide', [_derivative(arg0, constNodes), arg1]);
        }

        // Reciprocal Rule, d/dx(c / f(x)) = -c(f'(x)/f(x)^2)
        if (constNodes[arg0] !== undefined) {
          return new OperatorNode('*', 'multiply', [new OperatorNode('-', 'unaryMinus', [arg0]), new OperatorNode('/', 'divide', [_derivative(arg1, constNodes), new OperatorNode('^', 'pow', [arg1.clone(), createConstantNode(2)])])]);
        }

        // Quotient rule, d/dx(f(x) / g(x)) = (f'(x)g(x) - f(x)g'(x)) / g(x)^2
        return new OperatorNode('/', 'divide', [new OperatorNode('-', 'subtract', [new OperatorNode('*', 'multiply', [_derivative(arg0, constNodes), arg1.clone()]), new OperatorNode('*', 'multiply', [arg0.clone(), _derivative(arg1, constNodes)])]), new OperatorNode('^', 'pow', [arg1.clone(), createConstantNode(2)])]);
      }
      if (node.op === '^' && node.isBinary()) {
        var _arg = node.args[0];
        var _arg2 = node.args[1];
        if (constNodes[_arg] !== undefined) {
          // If is secretly constant; 0^f(x) = 1 (in JS), 1^f(x) = 1
          if (isConstantNode(_arg) && (isZero(_arg.value) || equal(_arg.value, 1))) {
            return createConstantNode(0);
          }

          // d/dx(c^f(x)) = c^f(x)*ln(c)*f'(x)
          return new OperatorNode('*', 'multiply', [node, new OperatorNode('*', 'multiply', [new FunctionNode('log', [_arg.clone()]), _derivative(_arg2.clone(), constNodes)])]);
        }
        if (constNodes[_arg2] !== undefined) {
          if (isConstantNode(_arg2)) {
            // If is secretly constant; f(x)^0 = 1 -> d/dx(1) = 0
            if (isZero(_arg2.value)) {
              return createConstantNode(0);
            }
            // Ignore exponent; f(x)^1 = f(x)
            if (equal(_arg2.value, 1)) {
              return _derivative(_arg, constNodes);
            }
          }

          // Elementary Power Rule, d/dx(f(x)^c) = c*f'(x)*f(x)^(c-1)
          var powMinusOne = new OperatorNode('^', 'pow', [_arg.clone(), new OperatorNode('-', 'subtract', [_arg2, createConstantNode(1)])]);
          return new OperatorNode('*', 'multiply', [_arg2.clone(), new OperatorNode('*', 'multiply', [_derivative(_arg, constNodes), powMinusOne])]);
        }

        // Functional Power Rule, d/dx(f^g) = f^g*[f'*(g/f) + g'ln(f)]
        return new OperatorNode('*', 'multiply', [new OperatorNode('^', 'pow', [_arg.clone(), _arg2.clone()]), new OperatorNode('+', 'add', [new OperatorNode('*', 'multiply', [_derivative(_arg, constNodes), new OperatorNode('/', 'divide', [_arg2.clone(), _arg.clone()])]), new OperatorNode('*', 'multiply', [_derivative(_arg2, constNodes), new FunctionNode('log', [_arg.clone()])])])]);
      }
      throw new Error('Cannot process operator "' + node.op + '" in derivative: ' + 'the operator is not supported, undefined, or the number of arguments passed to it are not supported');
    }
  });

  /**
   * Helper function to create a constant node with a specific type
   * (number, BigNumber, Fraction)
   * @param {number} value
   * @param {string} [valueType]
   * @return {ConstantNode}
   */
  function createConstantNode(value, valueType) {
    return new ConstantNode(numeric(value, valueType || safeNumberType(String(value), config)));
  }
  return derivative;
});

var name$s = 'rationalize';
var dependencies$s = ['config', 'typed', 'equal', 'isZero', 'add', 'subtract', 'multiply', 'divide', 'pow', 'parse', 'simplifyConstant', 'simplifyCore', 'simplify', '?bignumber', '?fraction', 'mathWithTransform', 'matrix', 'AccessorNode', 'ArrayNode', 'ConstantNode', 'FunctionNode', 'IndexNode', 'ObjectNode', 'OperatorNode', 'SymbolNode', 'ParenthesisNode'];
var createRationalize = /* #__PURE__ */factory(name$s, dependencies$s, _ref => {
  var {
    config,
    typed,
    equal,
    isZero,
    add,
    subtract,
    multiply,
    divide,
    pow,
    parse,
    simplifyConstant,
    simplifyCore,
    simplify,
    fraction,
    bignumber,
    mathWithTransform,
    matrix,
    AccessorNode,
    ArrayNode,
    ConstantNode,
    FunctionNode,
    IndexNode,
    ObjectNode,
    OperatorNode,
    SymbolNode,
    ParenthesisNode
  } = _ref;
  /**
   * 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.
   *
   * Syntax:
   *
   *     math.rationalize(expr)
   *     math.rationalize(expr, detailed)
   *     math.rationalize(expr, scope)
   *     math.rationalize(expr, scope, detailed)
   *
   * Examples:
   *
   *     math.rationalize('sin(x)+y')
   *                   //  Error: There is an unsolved function call
   *     math.rationalize('2x/y - y/(x+1)')
   *                   // (2*x^2-y^2+2*x)/(x*y+y)
   *     math.rationalize('(2x+1)^6')
   *                   // 64*x^6+192*x^5+240*x^4+160*x^3+60*x^2+12*x+1
   *     math.rationalize('2x/( (2x-1) / (3x+2) ) - 5x/ ( (3x+4) / (2x^2-5) ) + 3')
   *                   // -20*x^4+28*x^3+104*x^2+6*x-12)/(6*x^2+5*x-4)
   *     math.rationalize('x/(1-x)/(x-2)/(x-3)/(x-4) + 2x/ ( (1-2x)/(2-3x) )/ ((3-4x)/(4-5x) )') =
   *                   // (-30*x^7+344*x^6-1506*x^5+3200*x^4-3472*x^3+1846*x^2-381*x)/
   *                   //     (-8*x^6+90*x^5-383*x^4+780*x^3-797*x^2+390*x-72)
   *
   *     math.rationalize('x+x+x+y',{y:1}) // 3*x+1
   *     math.rationalize('x+x+x+y',{})    // 3*x+y
   *
   *     const ret = math.rationalize('x+x+x+y',{},true)
   *                   // ret.expression=3*x+y, ret.variables = ["x","y"]
   *     const ret = math.rationalize('-2+5x^2',{},true)
   *                   // ret.expression=5*x^2-2, ret.variables = ["x"], ret.coefficients=[-2,0,5]
   *
   * See also:
   *
   *     simplify
   *
   * @param  {Node|string} expr    The expression to check if is a polynomial expression
   * @param  {Object|boolean}      optional scope of expression or true for already evaluated rational expression at input
   * @param  {Boolean}  detailed   optional True if return an object, false if return expression node (default)
   *
   * @return {Object | Node}    The rational polynomial of `expr` or an object
   *            `{expression, numerator, denominator, variables, coefficients}`, where
   *              `expression` is a `Node` with the node simplified expression,
   *              `numerator` is a `Node` with the simplified numerator of expression,
   *              `denominator` is a `Node` or `boolean` with the simplified denominator or `false` (if there is no denominator),
   *              `variables` is an array with variable names,
   *              and `coefficients` is an array with coefficients of numerator sorted by increased exponent
   *           {Expression Node}  node simplified expression
   *
   */
  function _rationalize(expr) {
    var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var detailed = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    var setRules = rulesRationalize(); // Rules for change polynomial in near canonical form
    var polyRet = polynomial(expr, scope, true, setRules.firstRules); // Check if expression is a rationalizable polynomial
    var nVars = polyRet.variables.length;
    var noExactFractions = {
      exactFractions: false
    };
    var withExactFractions = {
      exactFractions: true
    };
    expr = polyRet.expression;
    if (nVars >= 1) {
      // If expression in not a constant
      expr = expandPower(expr); // First expand power of polynomials (cannot be made from rules!)
      var sBefore; // Previous expression
      var rules;
      var eDistrDiv = true;
      var redoInic = false;
      // Apply the initial rules, including succ div rules:
      expr = simplify(expr, setRules.firstRules, {}, noExactFractions);
      var s;
      while (true) {
        // Alternate applying successive division rules and distr.div.rules
        // until there are no more changes:
        rules = eDistrDiv ? setRules.distrDivRules : setRules.sucDivRules;
        expr = simplify(expr, rules, {}, withExactFractions);
        eDistrDiv = !eDistrDiv; // Swap between Distr.Div and Succ. Div. Rules

        s = expr.toString();
        if (s === sBefore) {
          break; // No changes : end of the loop
        }
        redoInic = true;
        sBefore = s;
      }
      if (redoInic) {
        // Apply first rules again without succ div rules (if there are changes)
        expr = simplify(expr, setRules.firstRulesAgain, {}, noExactFractions);
      }
      // Apply final rules:
      expr = simplify(expr, setRules.finalRules, {}, noExactFractions);
    } // NVars >= 1

    var coefficients = [];
    var retRationalize = {};
    if (expr.type === 'OperatorNode' && expr.isBinary() && expr.op === '/') {
      // Separate numerator from denominator
      if (nVars === 1) {
        expr.args[0] = polyToCanonical(expr.args[0], coefficients);
        expr.args[1] = polyToCanonical(expr.args[1]);
      }
      if (detailed) {
        retRationalize.numerator = expr.args[0];
        retRationalize.denominator = expr.args[1];
      }
    } else {
      if (nVars === 1) {
        expr = polyToCanonical(expr, coefficients);
      }
      if (detailed) {
        retRationalize.numerator = expr;
        retRationalize.denominator = null;
      }
    }
    // nVars

    if (!detailed) return expr;
    retRationalize.coefficients = coefficients;
    retRationalize.variables = polyRet.variables;
    retRationalize.expression = expr;
    return retRationalize;
  }
  return typed(name$s, {
    Node: _rationalize,
    'Node, boolean': (expr, detailed) => _rationalize(expr, {}, detailed),
    'Node, Object': _rationalize,
    'Node, Object, boolean': _rationalize
  }); // end of typed rationalize

  /**
   *  Function to simplify an expression using an optional scope and
   *  return it if the expression is a polynomial expression, i.e.
   *  an expression with one or more variables and the operators
   *  +, -, *, and ^, where the exponent can only be a positive integer.
   *
   * Syntax:
   *
   *     polynomial(expr,scope,extended, rules)
   *
   * @param  {Node | string} expr     The expression to simplify and check if is polynomial expression
   * @param  {object} scope           Optional scope for expression simplification
   * @param  {boolean} extended       Optional. Default is false. When true allows divide operator.
   * @param  {array}  rules           Optional. Default is no rule.
   *
   *
   * @return {Object}
   *            {Object} node:   node simplified expression
   *            {Array}  variables:  variable names
   */
  function polynomial(expr, scope, extended, rules) {
    var variables = [];
    var node = simplify(expr, rules, scope, {
      exactFractions: false
    }); // Resolves any variables and functions with all defined parameters
    extended = !!extended;
    var oper = '+-*' + (extended ? '/' : '');
    recPoly(node);
    var retFunc = {};
    retFunc.expression = node;
    retFunc.variables = variables;
    return retFunc;

    // -------------------------------------------------------------------------------------------------------

    /**
     *  Function to simplify an expression using an optional scope and
     *  return it if the expression is a polynomial expression, i.e.
     *  an expression with one or more variables and the operators
     *  +, -, *, and ^, where the exponent can only be a positive integer.
     *
     * Syntax:
     *
     *     recPoly(node)
     *
     *
     * @param  {Node} node               The current sub tree expression in recursion
     *
     * @return                           nothing, throw an exception if error
     */
    function recPoly(node) {
      var tp = node.type; // node type
      if (tp === 'FunctionNode') {
        // No function call in polynomial expression
        throw new Error('There is an unsolved function call');
      } else if (tp === 'OperatorNode') {
        if (node.op === '^') {
          // TODO: handle negative exponents like in '1/x^(-2)'
          if (node.args[1].type !== 'ConstantNode' || !isInteger(parseFloat(node.args[1].value))) {
            throw new Error('There is a non-integer exponent');
          } else {
            recPoly(node.args[0]);
          }
        } else {
          if (!oper.includes(node.op)) {
            throw new Error('Operator ' + node.op + ' invalid in polynomial expression');
          }
          for (var i = 0; i < node.args.length; i++) {
            recPoly(node.args[i]);
          }
        } // type of operator
      } else if (tp === 'SymbolNode') {
        var _name = node.name; // variable name
        var pos = variables.indexOf(_name);
        if (pos === -1) {
          // new variable in expression
          variables.push(_name);
        }
      } else if (tp === 'ParenthesisNode') {
        recPoly(node.content);
      } else if (tp !== 'ConstantNode') {
        throw new Error('type ' + tp + ' is not allowed in polynomial expression');
      }
    } // end of recPoly
  } // end of polynomial

  // ---------------------------------------------------------------------------------------
  /**
   * Return a rule set to rationalize an polynomial expression in rationalize
   *
   * Syntax:
   *
   *     rulesRationalize()
   *
   * @return {array}        rule set to rationalize an polynomial expression
   */
  function rulesRationalize() {
    var oldRules = [simplifyCore,
    // sCore
    {
      l: 'n+n',
      r: '2*n'
    }, {
      l: 'n+-n',
      r: '0'
    }, simplifyConstant,
    // sConstant
    {
      l: 'n*(n1^-1)',
      r: 'n/n1'
    }, {
      l: 'n*n1^-n2',
      r: 'n/n1^n2'
    }, {
      l: 'n1^-1',
      r: '1/n1'
    }, {
      l: 'n*(n1/n2)',
      r: '(n*n1)/n2'
    }, {
      l: '1*n',
      r: 'n'
    }];
    var rulesFirst = [{
      l: '(-n1)/(-n2)',
      r: 'n1/n2'
    },
    // Unary division
    {
      l: '(-n1)*(-n2)',
      r: 'n1*n2'
    },
    // Unary multiplication
    {
      l: 'n1--n2',
      r: 'n1+n2'
    },
    // '--' elimination
    {
      l: 'n1-n2',
      r: 'n1+(-n2)'
    },
    // Subtraction turn into add with un�ry minus
    {
      l: '(n1+n2)*n3',
      r: '(n1*n3 + n2*n3)'
    },
    // Distributive 1
    {
      l: 'n1*(n2+n3)',
      r: '(n1*n2+n1*n3)'
    },
    // Distributive 2
    {
      l: 'c1*n + c2*n',
      r: '(c1+c2)*n'
    },
    // Joining constants
    {
      l: 'c1*n + n',
      r: '(c1+1)*n'
    },
    // Joining constants
    {
      l: 'c1*n - c2*n',
      r: '(c1-c2)*n'
    },
    // Joining constants
    {
      l: 'c1*n - n',
      r: '(c1-1)*n'
    },
    // Joining constants
    {
      l: 'v/c',
      r: '(1/c)*v'
    },
    // variable/constant (new!)
    {
      l: 'v/-c',
      r: '-(1/c)*v'
    },
    // variable/constant (new!)
    {
      l: '-v*-c',
      r: 'c*v'
    },
    // Inversion constant and variable 1
    {
      l: '-v*c',
      r: '-c*v'
    },
    // Inversion constant and variable 2
    {
      l: 'v*-c',
      r: '-c*v'
    },
    // Inversion constant and variable 3
    {
      l: 'v*c',
      r: 'c*v'
    },
    // Inversion constant and variable 4
    {
      l: '-(-n1*n2)',
      r: '(n1*n2)'
    },
    // Unary propagation
    {
      l: '-(n1*n2)',
      r: '(-n1*n2)'
    },
    // Unary propagation
    {
      l: '-(-n1+n2)',
      r: '(n1-n2)'
    },
    // Unary propagation
    {
      l: '-(n1+n2)',
      r: '(-n1-n2)'
    },
    // Unary propagation
    {
      l: '(n1^n2)^n3',
      r: '(n1^(n2*n3))'
    },
    // Power to Power
    {
      l: '-(-n1/n2)',
      r: '(n1/n2)'
    },
    // Division and Unary
    {
      l: '-(n1/n2)',
      r: '(-n1/n2)'
    }]; // Divisao and Unary

    var rulesDistrDiv = [{
      l: '(n1/n2 + n3/n4)',
      r: '((n1*n4 + n3*n2)/(n2*n4))'
    },
    // Sum of fractions
    {
      l: '(n1/n2 + n3)',
      r: '((n1 + n3*n2)/n2)'
    },
    // Sum fraction with number 1
    {
      l: '(n1 + n2/n3)',
      r: '((n1*n3 + n2)/n3)'
    }]; // Sum fraction with number 1

    var rulesSucDiv = [{
      l: '(n1/(n2/n3))',
      r: '((n1*n3)/n2)'
    },
    // Division simplification
    {
      l: '(n1/n2/n3)',
      r: '(n1/(n2*n3))'
    }];
    var setRules = {}; // rules set in 4 steps.

    // All rules => infinite loop
    // setRules.allRules =oldRules.concat(rulesFirst,rulesDistrDiv,rulesSucDiv)

    setRules.firstRules = oldRules.concat(rulesFirst, rulesSucDiv); // First rule set
    setRules.distrDivRules = rulesDistrDiv; // Just distr. div. rules
    setRules.sucDivRules = rulesSucDiv; // Jus succ. div. rules
    setRules.firstRulesAgain = oldRules.concat(rulesFirst); // Last rules set without succ. div.

    // Division simplification

    // Second rule set.
    // There is no aggregate expression with parentesis, but the only variable can be scattered.
    setRules.finalRules = [simplifyCore,
    // simplify.rules[0]
    {
      l: 'n*-n',
      r: '-n^2'
    },
    // Joining multiply with power 1
    {
      l: 'n*n',
      r: 'n^2'
    },
    // Joining multiply with power 2
    simplifyConstant,
    // simplify.rules[14] old 3rd index in oldRules
    {
      l: 'n*-n^n1',
      r: '-n^(n1+1)'
    },
    // Joining multiply with power 3
    {
      l: 'n*n^n1',
      r: 'n^(n1+1)'
    },
    // Joining multiply with power 4
    {
      l: 'n^n1*-n^n2',
      r: '-n^(n1+n2)'
    },
    // Joining multiply with power 5
    {
      l: 'n^n1*n^n2',
      r: 'n^(n1+n2)'
    },
    // Joining multiply with power 6
    {
      l: 'n^n1*-n',
      r: '-n^(n1+1)'
    },
    // Joining multiply with power 7
    {
      l: 'n^n1*n',
      r: 'n^(n1+1)'
    },
    // Joining multiply with power 8
    {
      l: 'n^n1/-n',
      r: '-n^(n1-1)'
    },
    // Joining multiply with power 8
    {
      l: 'n^n1/n',
      r: 'n^(n1-1)'
    },
    // Joining division with power 1
    {
      l: 'n/-n^n1',
      r: '-n^(1-n1)'
    },
    // Joining division with power 2
    {
      l: 'n/n^n1',
      r: 'n^(1-n1)'
    },
    // Joining division with power 3
    {
      l: 'n^n1/-n^n2',
      r: 'n^(n1-n2)'
    },
    // Joining division with power 4
    {
      l: 'n^n1/n^n2',
      r: 'n^(n1-n2)'
    },
    // Joining division with power 5
    {
      l: 'n1+(-n2*n3)',
      r: 'n1-n2*n3'
    },
    // Solving useless parenthesis 1
    {
      l: 'v*(-c)',
      r: '-c*v'
    },
    // Solving useless unary 2
    {
      l: 'n1+-n2',
      r: 'n1-n2'
    },
    // Solving +- together (new!)
    {
      l: 'v*c',
      r: 'c*v'
    },
    // inversion constant with variable
    {
      l: '(n1^n2)^n3',
      r: '(n1^(n2*n3))'
    } // Power to Power
    ];
    return setRules;
  } // End rulesRationalize

  // ---------------------------------------------------------------------------------------
  /**
   *  Expand recursively a tree node for handling with expressions with exponents
   *  (it's not for constants, symbols or functions with exponents)
   *  PS: The other parameters are internal for recursion
   *
   * Syntax:
   *
   *     expandPower(node)
   *
   * @param  {Node} node         Current expression node
   * @param  {node} parent       Parent current node inside the recursion
   * @param  (int}               Parent number of chid inside the rercursion
   *
   * @return {node}        node expression with all powers expanded.
   */
  function expandPower(node, parent, indParent) {
    var tp = node.type;
    var internal = arguments.length > 1; // TRUE in internal calls

    if (tp === 'OperatorNode' && node.isBinary()) {
      var does = false;
      var val;
      if (node.op === '^') {
        // First operator: Parenthesis or UnaryMinus
        if ((node.args[0].type === 'ParenthesisNode' || node.args[0].type === 'OperatorNode') && node.args[1].type === 'ConstantNode') {
          // Second operator: Constant
          val = parseFloat(node.args[1].value);
          does = val >= 2 && isInteger(val);
        }
      }
      if (does) {
        // Exponent >= 2
        // Before:
        //            operator A --> Subtree
        // parent pow
        //            constant
        //
        if (val > 2) {
          // Exponent > 2,
          // AFTER:  (exponent > 2)
          //             operator A --> Subtree
          // parent  *
          //                 deep clone (operator A --> Subtree
          //             pow
          //                 constant - 1
          //
          var nEsqTopo = node.args[0];
          var nDirTopo = new OperatorNode('^', 'pow', [node.args[0].cloneDeep(), new ConstantNode(val - 1)]);
          node = new OperatorNode('*', 'multiply', [nEsqTopo, nDirTopo]);
        } else {
          // Expo = 2 - no power
          // AFTER:  (exponent =  2)
          //             operator A --> Subtree
          // parent   oper
          //            deep clone (operator A --> Subtree)
          //
          node = new OperatorNode('*', 'multiply', [node.args[0], node.args[0].cloneDeep()]);
        }
        if (internal) {
          // Change parent references in internal recursive calls
          if (indParent === 'content') {
            parent.content = node;
          } else {
            parent.args[indParent] = node;
          }
        }
      } // does
    } // binary OperatorNode

    if (tp === 'ParenthesisNode') {
      // Recursion
      expandPower(node.content, node, 'content');
    } else if (tp !== 'ConstantNode' && tp !== 'SymbolNode') {
      for (var i = 0; i < node.args.length; i++) {
        expandPower(node.args[i], node, i);
      }
    }
    if (!internal) {
      // return the root node
      return node;
    }
  } // End expandPower

  // ---------------------------------------------------------------------------------------
  /**
   * Auxilary function for rationalize
   * Convert near canonical polynomial in one variable in a canonical polynomial
   * with one term for each exponent in decreasing order
   *
   * Syntax:
   *
   *     polyToCanonical(node [, coefficients])
   *
   * @param  {Node | string} expr       The near canonical polynomial expression to convert in a a canonical polynomial expression
   *
   *        The string or tree expression needs to be at below syntax, with free spaces:
   *         (  (^(-)? | [+-]? )cte (*)? var (^expo)?  | cte )+
   *       Where 'var' is one variable with any valid name
   *             'cte' are real numeric constants with any value. It can be omitted if equal than 1
   *             'expo' are integers greater than 0. It can be omitted if equal than 1.
   *
   * @param  {array}   coefficients             Optional returns coefficients sorted by increased exponent
   *
   *
   * @return {node}        new node tree with one variable polynomial or string error.
   */
  function polyToCanonical(node, coefficients) {
    if (coefficients === undefined) {
      coefficients = [];
    } // coefficients.

    coefficients[0] = 0; // index is the exponent
    var o = {};
    o.cte = 1;
    o.oper = '+';

    // fire: mark with * or ^ when finds * or ^ down tree, reset to "" with + and -.
    //       It is used to deduce the exponent: 1 for *, 0 for "".
    o.fire = '';
    var maxExpo = 0; // maximum exponent
    var varname = ''; // variable name

    recurPol(node, null, o);
    maxExpo = coefficients.length - 1;
    var first = true;
    var no;
    for (var i = maxExpo; i >= 0; i--) {
      if (coefficients[i] === 0) continue;
      var n1 = new ConstantNode(first ? coefficients[i] : Math.abs(coefficients[i]));
      var op = coefficients[i] < 0 ? '-' : '+';
      if (i > 0) {
        // Is not a constant without variable
        var n2 = new SymbolNode(varname);
        if (i > 1) {
          var n3 = new ConstantNode(i);
          n2 = new OperatorNode('^', 'pow', [n2, n3]);
        }
        if (coefficients[i] === -1 && first) {
          n1 = new OperatorNode('-', 'unaryMinus', [n2]);
        } else if (Math.abs(coefficients[i]) === 1) {
          n1 = n2;
        } else {
          n1 = new OperatorNode('*', 'multiply', [n1, n2]);
        }
      }
      if (first) {
        no = n1;
      } else if (op === '+') {
        no = new OperatorNode('+', 'add', [no, n1]);
      } else {
        no = new OperatorNode('-', 'subtract', [no, n1]);
      }
      first = false;
    } // for

    if (first) {
      return new ConstantNode(0);
    } else {
      return no;
    }

    /**
     * Recursive auxilary function inside polyToCanonical for
     * converting expression in canonical form
     *
     * Syntax:
     *
     *     recurPol(node, noPai, obj)
     *
     * @param  {Node} node        The current subpolynomial expression
     * @param  {Node | Null}  noPai   The current parent node
     * @param  {object}    obj        Object with many internal flags
     *
     * @return {}                    No return. If error, throws an exception
     */
    function recurPol(node, noPai, o) {
      var tp = node.type;
      if (tp === 'FunctionNode') {
        // ***** FunctionName *****
        // No function call in polynomial expression
        throw new Error('There is an unsolved function call');
      } else if (tp === 'OperatorNode') {
        // ***** OperatorName *****
        if (!'+-*^'.includes(node.op)) throw new Error('Operator ' + node.op + ' invalid');
        if (noPai !== null) {
          // -(unary),^  : children of *,+,-
          if ((node.fn === 'unaryMinus' || node.fn === 'pow') && noPai.fn !== 'add' && noPai.fn !== 'subtract' && noPai.fn !== 'multiply') {
            throw new Error('Invalid ' + node.op + ' placing');
          }

          // -,+,* : children of +,-
          if ((node.fn === 'subtract' || node.fn === 'add' || node.fn === 'multiply') && noPai.fn !== 'add' && noPai.fn !== 'subtract') {
            throw new Error('Invalid ' + node.op + ' placing');
          }

          // -,+ : first child
          if ((node.fn === 'subtract' || node.fn === 'add' || node.fn === 'unaryMinus') && o.noFil !== 0) {
            throw new Error('Invalid ' + node.op + ' placing');
          }
        } // Has parent

        // Firers: ^,*       Old:   ^,&,-(unary): firers
        if (node.op === '^' || node.op === '*') {
          o.fire = node.op;
        }
        for (var _i = 0; _i < node.args.length; _i++) {
          // +,-: reset fire
          if (node.fn === 'unaryMinus') o.oper = '-';
          if (node.op === '+' || node.fn === 'subtract') {
            o.fire = '';
            o.cte = 1; // default if there is no constant
            o.oper = _i === 0 ? '+' : node.op;
          }
          o.noFil = _i; // number of son
          recurPol(node.args[_i], node, o);
        } // for in children
      } else if (tp === 'SymbolNode') {
        // ***** SymbolName *****
        if (node.name !== varname && varname !== '') {
          throw new Error('There is more than one variable');
        }
        varname = node.name;
        if (noPai === null) {
          coefficients[1] = 1;
          return;
        }

        // ^: Symbol is First child
        if (noPai.op === '^' && o.noFil !== 0) {
          throw new Error('In power the variable should be the first parameter');
        }

        // *: Symbol is Second child
        if (noPai.op === '*' && o.noFil !== 1) {
          throw new Error('In multiply the variable should be the second parameter');
        }

        // Symbol: firers '',* => it means there is no exponent above, so it's 1 (cte * var)
        if (o.fire === '' || o.fire === '*') {
          if (maxExpo < 1) coefficients[1] = 0;
          coefficients[1] += o.cte * (o.oper === '+' ? 1 : -1);
          maxExpo = Math.max(1, maxExpo);
        }
      } else if (tp === 'ConstantNode') {
        var valor = parseFloat(node.value);
        if (noPai === null) {
          coefficients[0] = valor;
          return;
        }
        if (noPai.op === '^') {
          // cte: second  child of power
          if (o.noFil !== 1) throw new Error('Constant cannot be powered');
          if (!isInteger(valor) || valor <= 0) {
            throw new Error('Non-integer exponent is not allowed');
          }
          for (var _i2 = maxExpo + 1; _i2 < valor; _i2++) coefficients[_i2] = 0;
          if (valor > maxExpo) coefficients[valor] = 0;
          coefficients[valor] += o.cte * (o.oper === '+' ? 1 : -1);
          maxExpo = Math.max(valor, maxExpo);
          return;
        }
        o.cte = valor;

        // Cte: firer '' => There is no exponent and no multiplication, so the exponent is 0.
        if (o.fire === '') {
          coefficients[0] += o.cte * (o.oper === '+' ? 1 : -1);
        }
      } else {
        throw new Error('Type ' + tp + ' is not allowed');
      }
    } // End of recurPol
  } // End of polyToCanonical
});

var name$r = 'zpk2tf';
var dependencies$r = ['typed', 'add', 'multiply', 'Complex', 'number'];
var createZpk2tf = /* #__PURE__ */factory(name$r, dependencies$r, _ref => {
  var {
    typed,
    add,
    multiply,
    Complex,
    number
  } = _ref;
  /**
     * Compute the transfer function of a zero-pole-gain model.
     *
     * Syntax:
     *      math.zpk2tf(z, p, k)
     *
     * Examples:
     *    math.zpk2tf([1, 2], [-1, -2], 1)    // returns [[1, -3, 2], [1, 3, 2]]
     *
     * See also:
     *   freqz
     *
     * @param {Array} z Array of zeros values
     * @param {Array} p Array of poles values
     * @param {number} k Gain value
     * @return {Array} Two dimensional array containing the numerator (first row) and denominator (second row) polynomials
     *
     */
  return typed(name$r, {
    'Array,Array,number': function ArrayArrayNumber(z, p, k) {
      return _zpk2tf(z, p, k);
    },
    'Array,Array': function ArrayArray(z, p) {
      return _zpk2tf(z, p, 1);
    },
    'Matrix,Matrix,number': function MatrixMatrixNumber(z, p, k) {
      return _zpk2tf(z.valueOf(), p.valueOf(), k);
    },
    'Matrix,Matrix': function MatrixMatrix(z, p) {
      return _zpk2tf(z.valueOf(), p.valueOf(), 1);
    }
  });
  function _zpk2tf(z, p, k) {
    // if z is bignumber, convert it to number
    if (z.some(el => el.type === 'BigNumber')) {
      z = z.map(el => number(el));
    }
    // if p is bignumber, convert it to number
    if (p.some(el => el.type === 'BigNumber')) {
      p = p.map(el => number(el));
    }
    var num = [Complex(1, 0)];
    var den = [Complex(1, 0)];
    for (var i = 0; i < z.length; i++) {
      var zero = z[i];
      if (typeof zero === 'number') zero = Complex(zero, 0);
      num = _multiply(num, [Complex(1, 0), Complex(-zero.re, -zero.im)]);
    }
    for (var _i = 0; _i < p.length; _i++) {
      var pole = p[_i];
      if (typeof pole === 'number') pole = Complex(pole, 0);
      den = _multiply(den, [Complex(1, 0), Complex(-pole.re, -pole.im)]);
    }
    for (var _i2 = 0; _i2 < num.length; _i2++) {
      num[_i2] = multiply(num[_i2], k);
    }
    return [num, den];
  }
  function _multiply(a, b) {
    var c = [];
    for (var i = 0; i < a.length + b.length - 1; i++) {
      c[i] = Complex(0, 0);
      for (var j = 0; j < a.length; j++) {
        if (i - j >= 0 && i - j < b.length) {
          c[i] = add(c[i], multiply(a[j], b[i - j]));
        }
      }
    }
    return c;
  }
});

var name$q = 'freqz';
var dependencies$q = ['typed', 'add', 'multiply', 'Complex', 'divide', 'matrix'];
var createFreqz = /* #__PURE__ */factory(name$q, dependencies$q, _ref => {
  var {
    typed,
    add,
    multiply,
    Complex,
    divide,
    matrix
  } = _ref;
  /**
     * Calculates the frequency response of a filter given its numerator and denominator coefficients.
     *
     * Syntax:
     *    math.freqz(b, a)
     *    math.freqz(b, a, w)
     *
     * Examples:
     *   math.freqz([1, 2], [1, 2, 3], 4) // returns { h: [0.5 + 0i, 0.4768589245763655 + 0.2861153547458193i, 0.25000000000000006 + 0.75i, -0.770976571635189 + 0.4625859429811135i], w: [0, 0.7853981633974483, 1.5707963267948966, 2.356194490192345 ] }
     *   math.freqz([1, 2], [1, 2, 3], [0, 1]) // returns { h: [0.5 + 0i, 0.45436781 + 0.38598051i], w: [0, 1] }
     *
     * See also:
     *  zpk2tf
     *
     * @param {Array.<number>} b The numerator coefficients of the filter.
     * @param {Array.<number>} a The denominator coefficients of the filter.
     * @param {Array.<number>} [w] A vector of frequencies (in radians/sample) at which the frequency response is to be computed or the number of points to compute (if a number is not provided, the default is 512 points)
     * @returns {Object} An object with two properties: h, a vector containing the complex frequency response, and w, a vector containing the normalized frequencies (in radians/sample) at which the response was computed.
     *
     *
     */
  return typed(name$q, {
    'Array, Array': function ArrayArray(b, a) {
      var w = createBins(512);
      return _freqz(b, a, w);
    },
    'Array, Array, Array': function ArrayArrayArray(b, a, w) {
      return _freqz(b, a, w);
    },
    'Array, Array, number': function ArrayArrayNumber(b, a, w) {
      if (w < 0) {
        throw new Error('w must be a positive number');
      }
      var w2 = createBins(w);
      return _freqz(b, a, w2);
    },
    'Matrix, Matrix': function MatrixMatrix(b, a) {
      // console.log('here')
      var _w = createBins(512);
      var {
        w,
        h
      } = _freqz(b.valueOf(), a.valueOf(), _w);
      return {
        w: matrix(w),
        h: matrix(h)
      };
    },
    'Matrix, Matrix, Matrix': function MatrixMatrixMatrix(b, a, w) {
      var {
        h
      } = _freqz(b.valueOf(), a.valueOf(), w.valueOf());
      return {
        h: matrix(h),
        w: matrix(w)
      };
    },
    'Matrix, Matrix, number': function MatrixMatrixNumber(b, a, w) {
      if (w < 0) {
        throw new Error('w must be a positive number');
      }
      var _w = createBins(w);
      var {
        h
      } = _freqz(b.valueOf(), a.valueOf(), _w);
      return {
        h: matrix(h),
        w: matrix(_w)
      };
    }
  });
  function _freqz(b, a, w) {
    var num = [];
    var den = [];
    for (var i = 0; i < w.length; i++) {
      var sumNum = Complex(0, 0);
      var sumDen = Complex(0, 0);
      for (var j = 0; j < b.length; j++) {
        sumNum = add(sumNum, multiply(b[j], Complex(Math.cos(-j * w[i]), Math.sin(-j * w[i]))));
      }
      for (var _j = 0; _j < a.length; _j++) {
        sumDen = add(sumDen, multiply(a[_j], Complex(Math.cos(-_j * w[i]), Math.sin(-_j * w[i]))));
      }
      num.push(sumNum);
      den.push(sumDen);
    }
    var h = [];
    for (var _i = 0; _i < num.length; _i++) {
      h.push(divide(num[_i], den[_i]));
    }
    return {
      h,
      w
    };
  }
  function createBins(n) {
    var bins = [];
    for (var i = 0; i < n; i++) {
      bins.push(i / n * Math.PI);
    }
    return bins;
  }
});

var name$p = 'reviver';
var dependencies$p = ['classes'];
var createReviver = /* #__PURE__ */factory(name$p, dependencies$p, _ref => {
  var {
    classes
  } = _ref;
  /**
   * Instantiate mathjs data types from their JSON representation
   * @param {string} key
   * @param {*} value
   * @returns {*} Returns the revived object
   */
  return function reviver(key, value) {
    var constructor = classes[value && value.mathjs];
    if (constructor && typeof constructor.fromJSON === 'function') {
      return constructor.fromJSON(value);
    }
    return value;
  };
});

var name$o = 'replacer';
var dependencies$o = [];
var createReplacer = /* #__PURE__ */factory(name$o, dependencies$o, () => {
  /**
   * Stringify data types into their JSON representation.
   * Most data types can be serialized using their `.toJSON` method,
   * but not all, for example the number `Infinity`. For these cases you have
   * to use the replacer. Example usage:
   *
   *     JSON.stringify([2, Infinity], math.replacer)
   *
   * @param {string} key
   * @param {*} value
   * @returns {*} Returns the replaced object
   */
  return function replacer(key, value) {
    // the numeric values Infinitiy, -Infinity, and NaN cannot be serialized to JSON
    if (typeof value === 'number' && (!isFinite(value) || isNaN(value))) {
      return {
        mathjs: 'number',
        value: String(value)
      };
    }
    if (typeof value === 'bigint') {
      return {
        mathjs: 'bigint',
        value: String(value)
      };
    }
    return value;
  };
});

var version = '13.0.0';
// Note: This file is automatically generated when building math.js.
// Changes made in this file will be overwritten.

var createTrue = /* #__PURE__ */factory('true', [], () => true);
var createFalse = /* #__PURE__ */factory('false', [], () => false);
var createNull = /* #__PURE__ */factory('null', [], () => null);
var createInfinity = /* #__PURE__ */recreateFactory('Infinity', ['config', '?BigNumber'], _ref => {
  var {
    config,
    BigNumber
  } = _ref;
  return config.number === 'BigNumber' ? new BigNumber(Infinity) : Infinity;
});
var createNaN = /* #__PURE__ */recreateFactory('NaN', ['config', '?BigNumber'], _ref2 => {
  var {
    config,
    BigNumber
  } = _ref2;
  return config.number === 'BigNumber' ? new BigNumber(NaN) : NaN;
});
var createPi = /* #__PURE__ */recreateFactory('pi', ['config', '?BigNumber'], _ref3 => {
  var {
    config,
    BigNumber
  } = _ref3;
  return config.number === 'BigNumber' ? createBigNumberPi(BigNumber) : pi;
});
var createTau = /* #__PURE__ */recreateFactory('tau', ['config', '?BigNumber'], _ref4 => {
  var {
    config,
    BigNumber
  } = _ref4;
  return config.number === 'BigNumber' ? createBigNumberTau(BigNumber) : tau;
});
var createE = /* #__PURE__ */recreateFactory('e', ['config', '?BigNumber'], _ref5 => {
  var {
    config,
    BigNumber
  } = _ref5;
  return config.number === 'BigNumber' ? createBigNumberE(BigNumber) : e;
});

// golden ratio, (1+sqrt(5))/2
var createPhi = /* #__PURE__ */recreateFactory('phi', ['config', '?BigNumber'], _ref6 => {
  var {
    config,
    BigNumber
  } = _ref6;
  return config.number === 'BigNumber' ? createBigNumberPhi(BigNumber) : phi;
});
var createLN2 = /* #__PURE__ */recreateFactory('LN2', ['config', '?BigNumber'], _ref7 => {
  var {
    config,
    BigNumber
  } = _ref7;
  return config.number === 'BigNumber' ? new BigNumber(2).ln() : Math.LN2;
});
var createLN10 = /* #__PURE__ */recreateFactory('LN10', ['config', '?BigNumber'], _ref8 => {
  var {
    config,
    BigNumber
  } = _ref8;
  return config.number === 'BigNumber' ? new BigNumber(10).ln() : Math.LN10;
});
var createLOG2E = /* #__PURE__ */recreateFactory('LOG2E', ['config', '?BigNumber'], _ref9 => {
  var {
    config,
    BigNumber
  } = _ref9;
  return config.number === 'BigNumber' ? new BigNumber(1).div(new BigNumber(2).ln()) : Math.LOG2E;
});
var createLOG10E = /* #__PURE__ */recreateFactory('LOG10E', ['config', '?BigNumber'], _ref10 => {
  var {
    config,
    BigNumber
  } = _ref10;
  return config.number === 'BigNumber' ? new BigNumber(1).div(new BigNumber(10).ln()) : Math.LOG10E;
});
var createSQRT1_2 = /* #__PURE__ */recreateFactory(
// eslint-disable-line camelcase
'SQRT1_2', ['config', '?BigNumber'], _ref11 => {
  var {
    config,
    BigNumber
  } = _ref11;
  return config.number === 'BigNumber' ? new BigNumber('0.5').sqrt() : Math.SQRT1_2;
});
var createSQRT2 = /* #__PURE__ */recreateFactory('SQRT2', ['config', '?BigNumber'], _ref12 => {
  var {
    config,
    BigNumber
  } = _ref12;
  return config.number === 'BigNumber' ? new BigNumber(2).sqrt() : Math.SQRT2;
});
var createI = /* #__PURE__ */recreateFactory('i', ['Complex'], _ref13 => {
  var {
    Complex
  } = _ref13;
  return Complex.I;
});

// for backward compatibility with v5
var createUppercasePi = /* #__PURE__ */factory('PI', ['pi'], _ref14 => {
  var {
    pi
  } = _ref14;
  return pi;
});
var createUppercaseE = /* #__PURE__ */factory('E', ['e'], _ref15 => {
  var {
    e
  } = _ref15;
  return e;
});
var createVersion = /* #__PURE__ */factory('version', [], () => version);

// helper function to create a factory with a flag recreateOnConfigChange
// idea: allow passing optional properties to be attached to the factory function as 4th argument?
function recreateFactory(name, dependencies, create) {
  return factory(name, dependencies, create, {
    recreateOnConfigChange: true
  });
}

// Source: https://en.wikipedia.org/wiki/Physical_constant

// Universal constants
var createSpeedOfLight = /* #__PURE__ */unitFactory('speedOfLight', '299792458', 'm s^-1');
var createGravitationConstant = /* #__PURE__ */unitFactory('gravitationConstant', '6.67430e-11', 'm^3 kg^-1 s^-2');
var createPlanckConstant = /* #__PURE__ */unitFactory('planckConstant', '6.62607015e-34', 'J s');
var createReducedPlanckConstant = /* #__PURE__ */unitFactory('reducedPlanckConstant', '1.0545718176461565e-34', 'J s');

// Electromagnetic constants
var createMagneticConstant = /* #__PURE__ */unitFactory('magneticConstant', '1.25663706212e-6', 'N A^-2');
var createElectricConstant = /* #__PURE__ */unitFactory('electricConstant', '8.8541878128e-12', 'F m^-1');
var createVacuumImpedance = /* #__PURE__ */unitFactory('vacuumImpedance', '376.730313667', 'ohm');
var createCoulomb = /* #__PURE__ */unitFactory('coulomb', '8.987551792261171e9', 'N m^2 C^-2');
var createElementaryCharge = /* #__PURE__ */unitFactory('elementaryCharge', '1.602176634e-19', 'C');
var createBohrMagneton = /* #__PURE__ */unitFactory('bohrMagneton', '9.2740100783e-24', 'J T^-1');
var createConductanceQuantum = /* #__PURE__ */unitFactory('conductanceQuantum', '7.748091729863649e-5', 'S');
var createInverseConductanceQuantum = /* #__PURE__ */unitFactory('inverseConductanceQuantum', '12906.403729652257', 'ohm');
var createMagneticFluxQuantum = /* #__PURE__ */unitFactory('magneticFluxQuantum', '2.0678338484619295e-15', 'Wb');
var createNuclearMagneton = /* #__PURE__ */unitFactory('nuclearMagneton', '5.0507837461e-27', 'J T^-1');
var createKlitzing = /* #__PURE__ */unitFactory('klitzing', '25812.807459304513', 'ohm');

// Atomic and nuclear constants
var createBohrRadius = /* #__PURE__ */unitFactory('bohrRadius', '5.29177210903e-11', 'm');
var createClassicalElectronRadius = /* #__PURE__ */unitFactory('classicalElectronRadius', '2.8179403262e-15', 'm');
var createElectronMass = /* #__PURE__ */unitFactory('electronMass', '9.1093837015e-31', 'kg');
var createFermiCoupling = /* #__PURE__ */unitFactory('fermiCoupling', '1.1663787e-5', 'GeV^-2');
var createFineStructure = numberFactory('fineStructure', 7.2973525693e-3);
var createHartreeEnergy = /* #__PURE__ */unitFactory('hartreeEnergy', '4.3597447222071e-18', 'J');
var createProtonMass = /* #__PURE__ */unitFactory('protonMass', '1.67262192369e-27', 'kg');
var createDeuteronMass = /* #__PURE__ */unitFactory('deuteronMass', '3.3435830926e-27', 'kg');
var createNeutronMass = /* #__PURE__ */unitFactory('neutronMass', '1.6749271613e-27', 'kg');
var createQuantumOfCirculation = /* #__PURE__ */unitFactory('quantumOfCirculation', '3.6369475516e-4', 'm^2 s^-1');
var createRydberg = /* #__PURE__ */unitFactory('rydberg', '10973731.568160', 'm^-1');
var createThomsonCrossSection = /* #__PURE__ */unitFactory('thomsonCrossSection', '6.6524587321e-29', 'm^2');
var createWeakMixingAngle = numberFactory('weakMixingAngle', 0.22290);
var createEfimovFactor = numberFactory('efimovFactor', 22.7);

// Physico-chemical constants
var createAtomicMass = /* #__PURE__ */unitFactory('atomicMass', '1.66053906660e-27', 'kg');
var createAvogadro = /* #__PURE__ */unitFactory('avogadro', '6.02214076e23', 'mol^-1');
var createBoltzmann = /* #__PURE__ */unitFactory('boltzmann', '1.380649e-23', 'J K^-1');
var createFaraday = /* #__PURE__ */unitFactory('faraday', '96485.33212331001', 'C mol^-1');
var createFirstRadiation = /* #__PURE__ */unitFactory('firstRadiation', '3.7417718521927573e-16', 'W m^2');
// TODO spectralRadiance = 1.1910429723971881e-16 W m^2 sr^-1
var createLoschmidt = /* #__PURE__ */unitFactory('loschmidt', '2.686780111798444e25', 'm^-3');
var createGasConstant = /* #__PURE__ */unitFactory('gasConstant', '8.31446261815324', 'J K^-1 mol^-1');
var createMolarPlanckConstant = /* #__PURE__ */unitFactory('molarPlanckConstant', '3.990312712893431e-10', 'J s mol^-1');
var createMolarVolume = /* #__PURE__ */unitFactory('molarVolume', '0.022413969545014137', 'm^3 mol^-1');
var createSackurTetrode = numberFactory('sackurTetrode', -1.16487052358);
var createSecondRadiation = /* #__PURE__ */unitFactory('secondRadiation', '0.014387768775039337', 'm K');
var createStefanBoltzmann = /* #__PURE__ */unitFactory('stefanBoltzmann', '5.67037441918443e-8', 'W m^-2 K^-4');
var createWienDisplacement = /* #__PURE__ */unitFactory('wienDisplacement', '2.897771955e-3', 'm K');

// Adopted values
var createMolarMass = /* #__PURE__ */unitFactory('molarMass', '0.99999999965e-3', 'kg mol^-1');
var createMolarMassC12 = /* #__PURE__ */unitFactory('molarMassC12', '11.9999999958e-3', 'kg mol^-1');
var createGravity = /* #__PURE__ */unitFactory('gravity', '9.80665', 'm s^-2');
// atm is defined in Unit.js

// Natural units
var createPlanckLength = /* #__PURE__ */unitFactory('planckLength', '1.616255e-35', 'm');
var createPlanckMass = /* #__PURE__ */unitFactory('planckMass', '2.176435e-8', 'kg');
var createPlanckTime = /* #__PURE__ */unitFactory('planckTime', '5.391245e-44', 's');
var createPlanckCharge = /* #__PURE__ */unitFactory('planckCharge', '1.87554603778e-18', 'C');
var createPlanckTemperature = /* #__PURE__ */unitFactory('planckTemperature', '1.416785e+32', 'K');

// helper function to create a factory function which creates a physical constant,
// a Unit with either a number value or a BigNumber value depending on the configuration
function unitFactory(name, valueStr, unitStr) {
  var dependencies = ['config', 'Unit', 'BigNumber'];
  return factory(name, dependencies, _ref => {
    var {
      config,
      Unit,
      BigNumber
    } = _ref;
    // Note that we can parse into number or BigNumber.
    // We do not parse into Fractions as that doesn't make sense: we would lose precision of the values
    // Therefore we dont use Unit.parse()
    var value = config.number === 'BigNumber' ? new BigNumber(valueStr) : parseFloat(valueStr);
    var unit = new Unit(value, unitStr);
    unit.fixPrefix = true;
    return unit;
  });
}

// helper function to create a factory function which creates a numeric constant,
// either a number or BigNumber depending on the configuration
function numberFactory(name, value) {
  var dependencies = ['config', 'BigNumber'];
  return factory(name, dependencies, _ref2 => {
    var {
      config,
      BigNumber
    } = _ref2;
    return config.number === 'BigNumber' ? new BigNumber(value) : value;
  });
}

var name$n = 'apply';
var dependencies$n = ['typed', 'isInteger'];

/**
 * Attach a transform function to math.apply
 * Adds a property transform containing the transform function.
 *
 * This transform changed the last `dim` parameter of function apply
 * from one-based to zero based
 */
var createApplyTransform = /* #__PURE__ */factory(name$n, dependencies$n, _ref => {
  var {
    typed,
    isInteger
  } = _ref;
  var apply = createApply({
    typed,
    isInteger
  });

  // @see: comment of concat itself
  return typed('apply', {
    '...any': function any(args) {
      // change dim from one-based to zero-based
      var dim = args[1];
      if (isNumber(dim)) {
        args[1] = dim - 1;
      } else if (isBigNumber(dim)) {
        args[1] = dim.minus(1);
      }
      try {
        return apply.apply(null, args);
      } catch (err) {
        throw errorTransform(err);
      }
    }
  });
}, {
  isTransformFunction: true
});

var name$m = 'column';
var dependencies$m = ['typed', 'Index', 'matrix', 'range'];

/**
 * Attach a transform function to matrix.column
 * Adds a property transform containing the transform function.
 *
 * This transform changed the last `index` parameter of function column
 * from zero-based to one-based
 */
var createColumnTransform = /* #__PURE__ */factory(name$m, dependencies$m, _ref => {
  var {
    typed,
    Index,
    matrix,
    range
  } = _ref;
  var column = createColumn({
    typed,
    Index,
    matrix,
    range
  });

  // @see: comment of column itself
  return typed('column', {
    '...any': function any(args) {
      // change last argument from zero-based to one-based
      var lastIndex = args.length - 1;
      var last = args[lastIndex];
      if (isNumber(last)) {
        args[lastIndex] = last - 1;
      }
      try {
        return column.apply(null, args);
      } catch (err) {
        throw errorTransform(err);
      }
    }
  });
}, {
  isTransformFunction: true
});

/**
 * Compile an inline expression like "x > 0"
 * @param {Node} expression
 * @param {Object} math
 * @param {Map} scope
 * @return {function} Returns a function with one argument which fills in the
 *                    undefined variable (like "x") and evaluates the expression
 */
function compileInlineExpression(expression, math, scope) {
  // find an undefined symbol
  var symbol = expression.filter(function (node) {
    return isSymbolNode(node) && !(node.name in math) && !scope.has(node.name);
  })[0];
  if (!symbol) {
    throw new Error('No undefined variable found in inline expression "' + expression + '"');
  }

  // create a test function for this equation
  var name = symbol.name; // variable name
  var argsScope = new Map();
  var subScope = new PartitionedMap(scope, argsScope, new Set([name]));
  var eq = expression.compile();
  return function inlineExpression(x) {
    argsScope.set(name, x);
    return eq.evaluate(subScope);
  };
}

var name$l = 'filter';
var dependencies$l = ['typed'];
var createFilterTransform = /* #__PURE__ */factory(name$l, dependencies$l, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Attach a transform function to math.filter
   * Adds a property transform containing the transform function.
   *
   * This transform adds support for equations as test function for math.filter,
   * so you can do something like 'filter([3, -2, 5], x > 0)'.
   */
  function filterTransform(args, math, scope) {
    var x, callback;
    if (args[0]) {
      x = args[0].compile().evaluate(scope);
    }
    if (args[1]) {
      if (isSymbolNode(args[1]) || isFunctionAssignmentNode(args[1])) {
        // a function pointer, like filter([3, -2, 5], myTestFunction)
        callback = args[1].compile().evaluate(scope);
      } else {
        // an expression like filter([3, -2, 5], x > 0)
        callback = compileInlineExpression(args[1], math, scope);
      }
    }
    return filter(x, callback);
  }
  filterTransform.rawArgs = true;

  // one based version of function filter
  var filter = typed('filter', {
    'Array, function': _filter,
    'Matrix, function': function MatrixFunction(x, test) {
      return x.create(_filter(x.toArray(), test));
    },
    'Array, RegExp': filterRegExp,
    'Matrix, RegExp': function MatrixRegExp(x, test) {
      return x.create(filterRegExp(x.toArray(), test));
    }
  });
  return filterTransform;
}, {
  isTransformFunction: true
});

/**
 * Filter values in a callback given a callback function
 *
 * !!! Passes a one-based index !!!
 *
 * @param {Array} x
 * @param {Function} callback
 * @return {Array} Returns the filtered array
 * @private
 */
function _filter(x, callback) {
  return filter(x, function (value, index, array) {
    // invoke the callback function with the right number of arguments
    return applyCallback(callback, value, [index + 1], array, 'filter');
  });
}

var name$k = 'forEach';
var dependencies$k = ['typed'];
var createForEachTransform = /* #__PURE__ */factory(name$k, dependencies$k, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Attach a transform function to math.forEach
   * Adds a property transform containing the transform function.
   *
   * This transform creates a one-based index instead of a zero-based index
   */
  function forEachTransform(args, math, scope) {
    var x, callback;
    if (args[0]) {
      x = args[0].compile().evaluate(scope);
    }
    if (args[1]) {
      if (isSymbolNode(args[1]) || isFunctionAssignmentNode(args[1])) {
        // a function pointer, like forEach([3, -2, 5], myTestFunction)
        callback = args[1].compile().evaluate(scope);
      } else {
        // an expression like forEach([3, -2, 5], x > 0 ? callback1(x) : callback2(x) )
        callback = compileInlineExpression(args[1], math, scope);
      }
    }
    return _forEach(x, callback);
  }
  forEachTransform.rawArgs = true;

  // one-based version of forEach
  var _forEach = typed('forEach', {
    'Array | Matrix, function': function ArrayMatrixFunction(array, callback) {
      var recurse = function recurse(value, index) {
        if (Array.isArray(value)) {
          forEach(value, function (child, i) {
            // we create a copy of the index array and append the new index value
            recurse(child, index.concat(i + 1)); // one based index, hence i+1
          });
        } else {
          // invoke the callback function with the right number of arguments
          return applyCallback(callback, value, index, array, 'forEach');
        }
      };
      recurse(array.valueOf(), []); // pass Array
    }
  });
  return forEachTransform;
}, {
  isTransformFunction: true
});

var name$j = 'index';
var dependencies$j = ['Index', 'getMatrixDataType'];
var createIndexTransform = /* #__PURE__ */factory(name$j, dependencies$j, _ref => {
  var {
    Index,
    getMatrixDataType
  } = _ref;
  /**
   * Attach a transform function to math.index
   * Adds a property transform containing the transform function.
   *
   * This transform creates a one-based index instead of a zero-based index
   */
  return function indexTransform() {
    var args = [];
    for (var i = 0, ii = arguments.length; i < ii; i++) {
      var arg = arguments[i];

      // change from one-based to zero based, convert BigNumber to number and leave Array of Booleans as is
      if (isRange(arg)) {
        arg.start--;
        arg.end -= arg.step > 0 ? 0 : 2;
      } else if (arg && arg.isSet === true) {
        arg = arg.map(function (v) {
          return v - 1;
        });
      } else if (isArray(arg) || isMatrix(arg)) {
        if (getMatrixDataType(arg) !== 'boolean') {
          arg = arg.map(function (v) {
            return v - 1;
          });
        }
      } else if (isNumber(arg)) {
        arg--;
      } else if (isBigNumber(arg)) {
        arg = arg.toNumber() - 1;
      } else if (typeof arg === 'string') ; else {
        throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range');
      }
      args[i] = arg;
    }
    var res = new Index();
    Index.apply(res, args);
    return res;
  };
}, {
  isTransformFunction: true
});

var name$i = 'map';
var dependencies$i = ['typed'];
var createMapTransform = /* #__PURE__ */factory(name$i, dependencies$i, _ref => {
  var {
    typed
  } = _ref;
  /**
   * Attach a transform function to math.map
   * Adds a property transform containing the transform function.
   *
   * This transform creates a one-based index instead of a zero-based index
   */
  function mapTransform(args, math, scope) {
    var x, callback;
    if (args[0]) {
      x = args[0].compile().evaluate(scope);
    }
    if (args[1]) {
      if (isSymbolNode(args[1]) || isFunctionAssignmentNode(args[1])) {
        // a function pointer, like filter([3, -2, 5], myTestFunction)
        callback = args[1].compile().evaluate(scope);
      } else {
        // an expression like filter([3, -2, 5], x > 0)
        callback = compileInlineExpression(args[1], math, scope);
      }
    }
    return map(x, callback);
  }
  mapTransform.rawArgs = true;

  // one-based version of map function
  var map = typed('map', {
    'Array, function': function ArrayFunction(x, callback) {
      return _map(x, callback, x);
    },
    'Matrix, function': function MatrixFunction(x, callback) {
      return x.create(_map(x.valueOf(), callback, x));
    }
  });
  return mapTransform;
}, {
  isTransformFunction: true
});

/**
 * Map for a multidimensional array. One-based indexes
 * @param {Array} array
 * @param {function} callback
 * @param {Array} orig
 * @return {Array}
 * @private
 */
function _map(array, callback, orig) {
  function recurse(value, index) {
    if (Array.isArray(value)) {
      return map(value, function (child, i) {
        // we create a copy of the index array and append the new index value
        return recurse(child, index.concat(i + 1)); // one based index, hence i + 1
      });
    } else {
      // invoke the (typed) callback function with the right number of arguments
      return applyCallback(callback, value, index, orig, 'map');
    }
  }
  return recurse(array, []);
}

/**
 * Change last argument dim from one-based to zero-based.
 */
function lastDimToZeroBase(args) {
  if (args.length === 2 && isCollection(args[0])) {
    args = args.slice();
    var dim = args[1];
    if (isNumber(dim)) {
      args[1] = dim - 1;
    } else if (isBigNumber(dim)) {
      args[1] = dim.minus(1);
    }
  }
  return args;
}

var name$h = 'max';
var dependencies$h = ['typed', 'config', 'numeric', 'larger'];
var createMaxTransform = /* #__PURE__ */factory(name$h, dependencies$h, _ref => {
  var {
    typed,
    config,
    numeric,
    larger
  } = _ref;
  var max = createMax({
    typed,
    config,
    numeric,
    larger
  });

  /**
   * Attach a transform function to math.max
   * Adds a property transform containing the transform function.
   *
   * This transform changed the last `dim` parameter of function max
   * from one-based to zero based
   */
  return typed('max', {
    '...any': function any(args) {
      args = lastDimToZeroBase(args);
      try {
        return max.apply(null, args);
      } catch (err) {
        throw errorTransform(err);
      }
    }
  });
}, {
  isTransformFunction: true
});

var name$g = 'mean';
var dependencies$g = ['typed', 'add', 'divide'];
var createMeanTransform = /* #__PURE__ */factory(name$g, dependencies$g, _ref => {
  var {
    typed,
    add,
    divide
  } = _ref;
  var mean = createMean({
    typed,
    add,
    divide
  });

  /**
   * Attach a transform function to math.mean
   * Adds a property transform containing the transform function.
   *
   * This transform changed the last `dim` parameter of function mean
   * from one-based to zero based
   */
  return typed('mean', {
    '...any': function any(args) {
      args = lastDimToZeroBase(args);
      try {
        return mean.apply(null, args);
      } catch (err) {
        throw errorTransform(err);
      }
    }
  });
}, {
  isTransformFunction: true
});

var name$f = 'min';
var dependencies$f = ['typed', 'config', 'numeric', 'smaller'];
var createMinTransform = /* #__PURE__ */factory(name$f, dependencies$f, _ref => {
  var {
    typed,
    config,
    numeric,
    smaller
  } = _ref;
  var min = createMin({
    typed,
    config,
    numeric,
    smaller
  });

  /**
   * Attach a transform function to math.min
   * Adds a property transform containing the transform function.
   *
   * This transform changed the last `dim` parameter of function min
   * from one-based to zero based
   */
  return typed('min', {
    '...any': function any(args) {
      args = lastDimToZeroBase(args);
      try {
        return min.apply(null, args);
      } catch (err) {
        throw errorTransform(err);
      }
    }
  });
}, {
  isTransformFunction: true
});

var name$e = 'range';
var dependencies$e = ['typed', 'config', '?matrix', '?bignumber', 'smaller', 'smallerEq', 'larger', 'largerEq', 'add', 'isPositive'];
var createRangeTransform = /* #__PURE__ */factory(name$e, dependencies$e, _ref => {
  var {
    typed,
    config,
    matrix,
    bignumber,
    smaller,
    smallerEq,
    larger,
    largerEq,
    add,
    isPositive
  } = _ref;
  var range = createRange({
    typed,
    config,
    matrix,
    bignumber,
    smaller,
    smallerEq,
    larger,
    largerEq,
    add,
    isPositive
  });

  /**
   * Attach a transform function to math.range
   * Adds a property transform containing the transform function.
   *
   * This transform creates a range which includes the end value
   */
  return typed('range', {
    '...any': function any(args) {
      var lastIndex = args.length - 1;
      var last = args[lastIndex];
      if (typeof last !== 'boolean') {
        // append a parameter includeEnd=true
        args.push(true);
      }
      return range.apply(null, args);
    }
  });
}, {
  isTransformFunction: true
});

var name$d = 'row';
var dependencies$d = ['typed', 'Index', 'matrix', 'range'];

/**
 * Attach a transform function to matrix.column
 * Adds a property transform containing the transform function.
 *
 * This transform changed the last `index` parameter of function column
 * from zero-based to one-based
 */
var createRowTransform = /* #__PURE__ */factory(name$d, dependencies$d, _ref => {
  var {
    typed,
    Index,
    matrix,
    range
  } = _ref;
  var row = createRow({
    typed,
    Index,
    matrix,
    range
  });

  // @see: comment of row itself
  return typed('row', {
    '...any': function any(args) {
      // change last argument from zero-based to one-based
      var lastIndex = args.length - 1;
      var last = args[lastIndex];
      if (isNumber(last)) {
        args[lastIndex] = last - 1;
      }
      try {
        return row.apply(null, args);
      } catch (err) {
        throw errorTransform(err);
      }
    }
  });
}, {
  isTransformFunction: true
});

var name$c = 'subset';
var dependencies$c = ['typed', 'matrix', 'zeros', 'add'];
var createSubsetTransform = /* #__PURE__ */factory(name$c, dependencies$c, _ref => {
  var {
    typed,
    matrix,
    zeros,
    add
  } = _ref;
  var subset = createSubset({
    typed,
    matrix,
    zeros,
    add
  });

  /**
   * Attach a transform function to math.subset
   * Adds a property transform containing the transform function.
   *
   * This transform creates a range which includes the end value
   */
  return typed('subset', {
    '...any': function any(args) {
      try {
        return subset.apply(null, args);
      } catch (err) {
        throw errorTransform(err);
      }
    }
  });
}, {
  isTransformFunction: true
});

var name$b = 'concat';
var dependencies$b = ['typed', 'matrix', 'isInteger'];
var createConcatTransform = /* #__PURE__ */factory(name$b, dependencies$b, _ref => {
  var {
    typed,
    matrix,
    isInteger
  } = _ref;
  var concat = createConcat({
    typed,
    matrix,
    isInteger
  });

  /**
   * Attach a transform function to math.range
   * Adds a property transform containing the transform function.
   *
   * This transform changed the last `dim` parameter of function concat
   * from one-based to zero based
   */
  return typed('concat', {
    '...any': function any(args) {
      // change last argument from one-based to zero-based
      var lastIndex = args.length - 1;
      var last = args[lastIndex];
      if (isNumber(last)) {
        args[lastIndex] = last - 1;
      } else if (isBigNumber(last)) {
        args[lastIndex] = last.minus(1);
      }
      try {
        return concat.apply(null, args);
      } catch (err) {
        throw errorTransform(err);
      }
    }
  });
}, {
  isTransformFunction: true
});

var name$a = 'diff';
var dependencies$a = ['typed', 'matrix', 'subtract', 'number', 'bignumber'];
var createDiffTransform = /* #__PURE__ */factory(name$a, dependencies$a, _ref => {
  var {
    typed,
    matrix,
    subtract,
    number,
    bignumber
  } = _ref;
  var diff = createDiff({
    typed,
    matrix,
    subtract,
    number,
    bignumber
  });

  /**
   * Attach a transform function to math.diff
   * Adds a property transform containing the transform function.
   *
   * This transform creates a range which includes the end value
   */
  return typed(name$a, {
    '...any': function any(args) {
      args = lastDimToZeroBase(args);
      try {
        return diff.apply(null, args);
      } catch (err) {
        throw errorTransform(err);
      }
    }
  });
}, {
  isTransformFunction: true
});

var name$9 = 'std';
var dependencies$9 = ['typed', 'map', 'sqrt', 'variance'];

/**
 * Attach a transform function to math.std
 * Adds a property transform containing the transform function.
 *
 * This transform changed the `dim` parameter of function std
 * from one-based to zero based
 */
var createStdTransform = /* #__PURE__ */factory(name$9, dependencies$9, _ref => {
  var {
    typed,
    map,
    sqrt,
    variance
  } = _ref;
  var std = createStd({
    typed,
    map,
    sqrt,
    variance
  });
  return typed('std', {
    '...any': function any(args) {
      args = lastDimToZeroBase(args);
      try {
        return std.apply(null, args);
      } catch (err) {
        throw errorTransform(err);
      }
    }
  });
}, {
  isTransformFunction: true
});

/**
 * Attach a transform function to math.sum
 * Adds a property transform containing the transform function.
 *
 * This transform changed the last `dim` parameter of function sum
 * from one-based to zero based
 */
var name$8 = 'sum';
var dependencies$8 = ['typed', 'config', 'add', 'numeric'];
var createSumTransform = /* #__PURE__ */factory(name$8, dependencies$8, _ref => {
  var {
    typed,
    config,
    add,
    numeric
  } = _ref;
  var sum = createSum({
    typed,
    config,
    add,
    numeric
  });
  return typed(name$8, {
    '...any': function any(args) {
      args = lastDimToZeroBase(args);
      try {
        return sum.apply(null, args);
      } catch (err) {
        throw errorTransform(err);
      }
    }
  });
}, {
  isTransformFunction: true
});

var name$7 = 'quantileSeq';
var dependencies$7 = ['typed', 'bignumber', 'add', 'subtract', 'divide', 'multiply', 'partitionSelect', 'compare', 'isInteger', 'smaller', 'smallerEq', 'larger'];

/**
 * Attach a transform function to math.quantileSeq
 * Adds a property transform containing the transform function.
 *
 * This transform changed the `dim` parameter of function std
 * from one-based to zero based
 */
var createQuantileSeqTransform = /* #__PURE__ */factory(name$7, dependencies$7, _ref => {
  var {
    typed,
    bignumber,
    add,
    subtract,
    divide,
    multiply,
    partitionSelect,
    compare,
    isInteger,
    smaller,
    smallerEq,
    larger
  } = _ref;
  var quantileSeq = createQuantileSeq({
    typed,
    bignumber,
    add,
    subtract,
    divide,
    multiply,
    partitionSelect,
    compare,
    isInteger,
    smaller,
    smallerEq,
    larger
  });
  return typed('quantileSeq', {
    'Array | Matrix, number | BigNumber': quantileSeq,
    'Array | Matrix, number | BigNumber, number': (arr, prob, dim) => quantileSeq(arr, prob, dimToZeroBase(dim)),
    'Array | Matrix, number | BigNumber, boolean': quantileSeq,
    'Array | Matrix, number | BigNumber, boolean, number': (arr, prob, sorted, dim) => quantileSeq(arr, prob, sorted, dimToZeroBase(dim)),
    'Array | Matrix, Array | Matrix': quantileSeq,
    'Array | Matrix, Array | Matrix, number': (data, prob, dim) => quantileSeq(data, prob, dimToZeroBase(dim)),
    'Array | Matrix, Array | Matrix, boolean': quantileSeq,
    'Array | Matrix, Array | Matrix, boolean, number': (data, prob, sorted, dim) => quantileSeq(data, prob, sorted, dimToZeroBase(dim))
  });
  function dimToZeroBase(dim) {
    // TODO: find a better way, maybe lastDimToZeroBase could apply to more cases.
    return lastDimToZeroBase([[], dim])[1];
  }
}, {
  isTransformFunction: true
});

/**
 * Attach a transform function to math.sum
 * Adds a property transform containing the transform function.
 *
 * This transform changed the last `dim` parameter of function sum
 * from one-based to zero based
 */
var name$6 = 'cumsum';
var dependencies$6 = ['typed', 'add', 'unaryPlus'];
var createCumSumTransform = /* #__PURE__ */factory(name$6, dependencies$6, _ref => {
  var {
    typed,
    add,
    unaryPlus
  } = _ref;
  var cumsum = createCumSum({
    typed,
    add,
    unaryPlus
  });
  return typed(name$6, {
    '...any': function any(args) {
      // change last argument dim from one-based to zero-based
      if (args.length === 2 && isCollection(args[0])) {
        var dim = args[1];
        if (isNumber(dim)) {
          args[1] = dim - 1;
        } else if (isBigNumber(dim)) {
          args[1] = dim.minus(1);
        }
      }
      try {
        return cumsum.apply(null, args);
      } catch (err) {
        throw errorTransform(err);
      }
    }
  });
}, {
  isTransformFunction: true
});

var name$5 = 'variance';
var dependencies$5 = ['typed', 'add', 'subtract', 'multiply', 'divide', 'apply', 'isNaN'];

/**
 * Attach a transform function to math.var
 * Adds a property transform containing the transform function.
 *
 * This transform changed the `dim` parameter of function var
 * from one-based to zero based
 */
var createVarianceTransform = /* #__PURE__ */factory(name$5, dependencies$5, _ref => {
  var {
    typed,
    add,
    subtract,
    multiply,
    divide,
    apply,
    isNaN
  } = _ref;
  var variance = createVariance({
    typed,
    add,
    subtract,
    multiply,
    divide,
    apply,
    isNaN
  });
  return typed(name$5, {
    '...any': function any(args) {
      args = lastDimToZeroBase(args);
      try {
        return variance.apply(null, args);
      } catch (err) {
        throw errorTransform(err);
      }
    }
  });
}, {
  isTransformFunction: true
});

var name$4 = 'print';
var dependencies$4 = ['typed', 'matrix', 'zeros', 'add'];
var createPrintTransform = /* #__PURE__ */factory(name$4, dependencies$4, _ref => {
  var {
    typed,
    matrix,
    zeros,
    add
  } = _ref;
  var print = createPrint({
    typed,
    matrix,
    zeros,
    add
  });
  return typed(name$4, {
    'string, Object | Array': function stringObjectArray(template, values) {
      return print(_convertTemplateToZeroBasedIndex(template), values);
    },
    'string, Object | Array, number | Object': function stringObjectArrayNumberObject(template, values, options) {
      return print(_convertTemplateToZeroBasedIndex(template), values, options);
    }
  });
  function _convertTemplateToZeroBasedIndex(template) {
    return template.replace(printTemplate, x => {
      var parts = x.slice(1).split('.');
      var result = parts.map(function (part) {
        if (!isNaN(part) && part.length > 0) {
          return parseInt(part) - 1;
        } else {
          return part;
        }
      });
      return '$' + result.join('.');
    });
  }
}, {
  isTransformFunction: true
});

var name$3 = 'and';
var dependencies$3 = ['typed', 'matrix', 'zeros', 'add', 'equalScalar', 'not', 'concat'];
var createAndTransform = /* #__PURE__ */factory(name$3, dependencies$3, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    zeros,
    not,
    concat
  } = _ref;
  var and = createAnd({
    typed,
    matrix,
    equalScalar,
    zeros,
    not,
    concat
  });
  function andTransform(args, math, scope) {
    var condition1 = args[0].compile().evaluate(scope);
    if (!isCollection(condition1) && !and(condition1, true)) {
      return false;
    }
    var condition2 = args[1].compile().evaluate(scope);
    return and(condition1, condition2);
  }
  andTransform.rawArgs = true;
  return andTransform;
}, {
  isTransformFunction: true
});

var name$2 = 'or';
var dependencies$2 = ['typed', 'matrix', 'equalScalar', 'DenseMatrix', 'concat'];
var createOrTransform = /* #__PURE__ */factory(name$2, dependencies$2, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    DenseMatrix,
    concat
  } = _ref;
  var or = createOr({
    typed,
    matrix,
    equalScalar,
    DenseMatrix,
    concat
  });
  function orTransform(args, math, scope) {
    var condition1 = args[0].compile().evaluate(scope);
    if (!isCollection(condition1) && or(condition1, false)) {
      return true;
    }
    var condition2 = args[1].compile().evaluate(scope);
    return or(condition1, condition2);
  }
  orTransform.rawArgs = true;
  return orTransform;
}, {
  isTransformFunction: true
});

var name$1 = 'bitAnd';
var dependencies$1 = ['typed', 'matrix', 'zeros', 'add', 'equalScalar', 'not', 'concat'];
var createBitAndTransform = /* #__PURE__ */factory(name$1, dependencies$1, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    zeros,
    not,
    concat
  } = _ref;
  var bitAnd = createBitAnd({
    typed,
    matrix,
    equalScalar,
    zeros,
    not,
    concat
  });
  function bitAndTransform(args, math, scope) {
    var condition1 = args[0].compile().evaluate(scope);
    if (!isCollection(condition1)) {
      if (isNaN(condition1)) {
        return NaN;
      }
      if (condition1 === 0 || condition1 === false) {
        return 0;
      }
    }
    var condition2 = args[1].compile().evaluate(scope);
    return bitAnd(condition1, condition2);
  }
  bitAndTransform.rawArgs = true;
  return bitAndTransform;
}, {
  isTransformFunction: true
});

var name = 'bitOr';
var dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix', 'concat'];
var createBitOrTransform = /* #__PURE__ */factory(name, dependencies, _ref => {
  var {
    typed,
    matrix,
    equalScalar,
    DenseMatrix,
    concat
  } = _ref;
  var bitOr = createBitOr({
    typed,
    matrix,
    equalScalar,
    DenseMatrix,
    concat
  });
  function bitOrTransform(args, math, scope) {
    var condition1 = args[0].compile().evaluate(scope);
    if (!isCollection(condition1)) {
      if (isNaN(condition1)) {
        return NaN;
      }
      if (condition1 === -1) {
        return -1;
      }
      if (condition1 === true) {
        return 1;
      }
    }
    var condition2 = args[1].compile().evaluate(scope);
    return bitOr(condition1, condition2);
  }
  bitOrTransform.rawArgs = true;
  return bitOrTransform;
}, {
  isTransformFunction: true
});

var allFactories = /*#__PURE__*/Object.freeze({
    __proto__: null,
    createTyped: createTyped,
    createResultSet: createResultSet,
    createBigNumberClass: createBigNumberClass,
    createComplexClass: createComplexClass,
    createFractionClass: createFractionClass,
    createRangeClass: createRangeClass,
    createMatrixClass: createMatrixClass,
    createDenseMatrixClass: createDenseMatrixClass,
    createClone: createClone,
    createIsInteger: createIsInteger,
    createIsNegative: createIsNegative,
    createIsNumeric: createIsNumeric,
    createHasNumericValue: createHasNumericValue,
    createIsPositive: createIsPositive,
    createIsZero: createIsZero,
    createIsNaN: createIsNaN,
    createTypeOf: createTypeOf,
    createEqualScalar: createEqualScalar,
    createSparseMatrixClass: createSparseMatrixClass,
    createNumber: createNumber,
    createBigint: createBigint,
    createString: createString,
    createBoolean: createBoolean,
    createBignumber: createBignumber,
    createComplex: createComplex,
    createFraction: createFraction,
    createMatrix: createMatrix,
    createMatrixFromFunction: createMatrixFromFunction,
    createMatrixFromRows: createMatrixFromRows,
    createMatrixFromColumns: createMatrixFromColumns,
    createSplitUnit: createSplitUnit,
    createUnaryMinus: createUnaryMinus,
    createUnaryPlus: createUnaryPlus,
    createAbs: createAbs,
    createApply: createApply,
    createAddScalar: createAddScalar,
    createSubtractScalar: createSubtractScalar,
    createCbrt: createCbrt,
    createCeil: createCeil,
    createCube: createCube,
    createExp: createExp,
    createExpm1: createExpm1,
    createFix: createFix,
    createFloor: createFloor,
    createGcd: createGcd,
    createLcm: createLcm,
    createLog10: createLog10,
    createLog2: createLog2,
    createMod: createMod,
    createMultiplyScalar: createMultiplyScalar,
    createMultiply: createMultiply,
    createNthRoot: createNthRoot,
    createSign: createSign,
    createSqrt: createSqrt,
    createSquare: createSquare,
    createSubtract: createSubtract,
    createXgcd: createXgcd,
    createInvmod: createInvmod,
    createDotMultiply: createDotMultiply,
    createBitAnd: createBitAnd,
    createBitNot: createBitNot,
    createBitOr: createBitOr,
    createBitXor: createBitXor,
    createArg: createArg,
    createConj: createConj,
    createIm: createIm,
    createRe: createRe,
    createNot: createNot,
    createOr: createOr,
    createXor: createXor,
    createConcat: createConcat,
    createColumn: createColumn,
    createCount: createCount,
    createCross: createCross,
    createDiag: createDiag,
    createFilter: createFilter,
    createFlatten: createFlatten,
    createForEach: createForEach,
    createGetMatrixDataType: createGetMatrixDataType,
    createIdentity: createIdentity,
    createKron: createKron,
    createMap: createMap,
    createDiff: createDiff,
    createOnes: createOnes,
    createRange: createRange,
    createReshape: createReshape,
    createResize: createResize,
    createRotate: createRotate,
    createRotationMatrix: createRotationMatrix,
    createRow: createRow,
    createSize: createSize,
    createSqueeze: createSqueeze,
    createSubset: createSubset,
    createTranspose: createTranspose,
    createCtranspose: createCtranspose,
    createZeros: createZeros,
    createFft: createFft,
    createIfft: createIfft,
    createSolveODE: createSolveODE,
    createErf: createErf,
    createZeta: createZeta,
    createMode: createMode,
    createProd: createProd,
    createFormat: createFormat,
    createBin: createBin,
    createOct: createOct,
    createHex: createHex,
    createPrint: createPrint,
    createTo: createTo,
    createIsPrime: createIsPrime,
    createNumeric: createNumeric,
    createDivideScalar: createDivideScalar,
    createPow: createPow,
    createRound: createRound,
    createLog: createLog,
    createLog1p: createLog1p,
    createNthRoots: createNthRoots,
    createDotPow: createDotPow,
    createDotDivide: createDotDivide,
    createLsolve: createLsolve,
    createUsolve: createUsolve,
    createLsolveAll: createLsolveAll,
    createUsolveAll: createUsolveAll,
    createLeftShift: createLeftShift,
    createRightArithShift: createRightArithShift,
    createRightLogShift: createRightLogShift,
    createAnd: createAnd,
    createCompare: createCompare,
    createCompareNatural: createCompareNatural,
    createCompareText: createCompareText,
    createEqual: createEqual,
    createEqualText: createEqualText,
    createSmaller: createSmaller,
    createSmallerEq: createSmallerEq,
    createLarger: createLarger,
    createLargerEq: createLargerEq,
    createDeepEqual: createDeepEqual,
    createUnequal: createUnequal,
    createPartitionSelect: createPartitionSelect,
    createSort: createSort,
    createMax: createMax,
    createMin: createMin,
    createImmutableDenseMatrixClass: createImmutableDenseMatrixClass,
    createIndexClass: createIndexClass,
    createFibonacciHeapClass: createFibonacciHeapClass,
    createSpaClass: createSpaClass,
    createUnitClass: createUnitClass,
    createUnitFunction: createUnitFunction,
    createSparse: createSparse,
    createCreateUnit: createCreateUnit,
    createAcos: createAcos,
    createAcosh: createAcosh,
    createAcot: createAcot,
    createAcoth: createAcoth,
    createAcsc: createAcsc,
    createAcsch: createAcsch,
    createAsec: createAsec,
    createAsech: createAsech,
    createAsin: createAsin,
    createAsinh: createAsinh,
    createAtan: createAtan,
    createAtan2: createAtan2,
    createAtanh: createAtanh,
    createCos: createCos,
    createCosh: createCosh,
    createCot: createCot,
    createCoth: createCoth,
    createCsc: createCsc,
    createCsch: createCsch,
    createSec: createSec,
    createSech: createSech,
    createSin: createSin,
    createSinh: createSinh,
    createTan: createTan,
    createTanh: createTanh,
    createSetCartesian: createSetCartesian,
    createSetDifference: createSetDifference,
    createSetDistinct: createSetDistinct,
    createSetIntersect: createSetIntersect,
    createSetIsSubset: createSetIsSubset,
    createSetMultiplicity: createSetMultiplicity,
    createSetPowerset: createSetPowerset,
    createSetSize: createSetSize,
    createSetSymDifference: createSetSymDifference,
    createSetUnion: createSetUnion,
    createAdd: createAdd,
    createHypot: createHypot,
    createNorm: createNorm,
    createDot: createDot,
    createTrace: createTrace,
    createIndex: createIndex,
    createNode: createNode,
    createAccessorNode: createAccessorNode,
    createArrayNode: createArrayNode,
    createAssignmentNode: createAssignmentNode,
    createBlockNode: createBlockNode,
    createConditionalNode: createConditionalNode,
    createConstantNode: createConstantNode,
    createFunctionAssignmentNode: createFunctionAssignmentNode,
    createIndexNode: createIndexNode,
    createObjectNode: createObjectNode,
    createOperatorNode: createOperatorNode,
    createParenthesisNode: createParenthesisNode,
    createRangeNode: createRangeNode,
    createRelationalNode: createRelationalNode,
    createSymbolNode: createSymbolNode,
    createFunctionNode: createFunctionNode,
    createParse: createParse,
    createCompile: createCompile,
    createEvaluate: createEvaluate,
    createParserClass: createParserClass,
    createParser: createParser,
    createLup: createLup,
    createQr: createQr,
    createSlu: createSlu,
    createLusolve: createLusolve,
    createPolynomialRoot: createPolynomialRoot,
    createHelpClass: createHelpClass,
    createChainClass: createChainClass,
    createHelp: createHelp,
    createChain: createChain,
    createDet: createDet,
    createInv: createInv,
    createPinv: createPinv,
    createEigs: createEigs,
    createExpm: createExpm,
    createSqrtm: createSqrtm,
    createSylvester: createSylvester,
    createSchur: createSchur,
    createLyap: createLyap,
    createDivide: createDivide,
    createDistance: createDistance,
    createIntersect: createIntersect,
    createSum: createSum,
    createCumSum: createCumSum,
    createMean: createMean,
    createMedian: createMedian,
    createMad: createMad,
    createVariance: createVariance,
    createQuantileSeq: createQuantileSeq,
    createStd: createStd,
    createCorr: createCorr,
    createCombinations: createCombinations,
    createCombinationsWithRep: createCombinationsWithRep,
    createGamma: createGamma,
    createLgamma: createLgamma,
    createFactorial: createFactorial,
    createKldivergence: createKldivergence,
    createMultinomial: createMultinomial,
    createPermutations: createPermutations,
    createPickRandom: createPickRandom,
    createRandom: createRandom,
    createRandomInt: createRandomInt,
    createStirlingS2: createStirlingS2,
    createBellNumbers: createBellNumbers,
    createCatalan: createCatalan,
    createComposition: createComposition,
    createLeafCount: createLeafCount,
    createSimplify: createSimplify,
    createSimplifyConstant: createSimplifyConstant,
    createSimplifyCore: createSimplifyCore,
    createResolve: createResolve,
    createSymbolicEqual: createSymbolicEqual,
    createDerivative: createDerivative,
    createRationalize: createRationalize,
    createZpk2tf: createZpk2tf,
    createFreqz: createFreqz,
    createReviver: createReviver,
    createReplacer: createReplacer,
    createE: createE,
    createUppercaseE: createUppercaseE,
    createFalse: createFalse,
    createI: createI,
    createInfinity: createInfinity,
    createLN10: createLN10,
    createLN2: createLN2,
    createLOG10E: createLOG10E,
    createLOG2E: createLOG2E,
    createNaN: createNaN,
    createNull: createNull,
    createPhi: createPhi,
    createPi: createPi,
    createUppercasePi: createUppercasePi,
    createSQRT1_2: createSQRT1_2,
    createSQRT2: createSQRT2,
    createTau: createTau,
    createTrue: createTrue,
    createVersion: createVersion,
    createAtomicMass: createAtomicMass,
    createAvogadro: createAvogadro,
    createBohrMagneton: createBohrMagneton,
    createBohrRadius: createBohrRadius,
    createBoltzmann: createBoltzmann,
    createClassicalElectronRadius: createClassicalElectronRadius,
    createConductanceQuantum: createConductanceQuantum,
    createCoulomb: createCoulomb,
    createDeuteronMass: createDeuteronMass,
    createEfimovFactor: createEfimovFactor,
    createElectricConstant: createElectricConstant,
    createElectronMass: createElectronMass,
    createElementaryCharge: createElementaryCharge,
    createFaraday: createFaraday,
    createFermiCoupling: createFermiCoupling,
    createFineStructure: createFineStructure,
    createFirstRadiation: createFirstRadiation,
    createGasConstant: createGasConstant,
    createGravitationConstant: createGravitationConstant,
    createGravity: createGravity,
    createHartreeEnergy: createHartreeEnergy,
    createInverseConductanceQuantum: createInverseConductanceQuantum,
    createKlitzing: createKlitzing,
    createLoschmidt: createLoschmidt,
    createMagneticConstant: createMagneticConstant,
    createMagneticFluxQuantum: createMagneticFluxQuantum,
    createMolarMass: createMolarMass,
    createMolarMassC12: createMolarMassC12,
    createMolarPlanckConstant: createMolarPlanckConstant,
    createMolarVolume: createMolarVolume,
    createNeutronMass: createNeutronMass,
    createNuclearMagneton: createNuclearMagneton,
    createPlanckCharge: createPlanckCharge,
    createPlanckConstant: createPlanckConstant,
    createPlanckLength: createPlanckLength,
    createPlanckMass: createPlanckMass,
    createPlanckTemperature: createPlanckTemperature,
    createPlanckTime: createPlanckTime,
    createProtonMass: createProtonMass,
    createQuantumOfCirculation: createQuantumOfCirculation,
    createReducedPlanckConstant: createReducedPlanckConstant,
    createRydberg: createRydberg,
    createSackurTetrode: createSackurTetrode,
    createSecondRadiation: createSecondRadiation,
    createSpeedOfLight: createSpeedOfLight,
    createStefanBoltzmann: createStefanBoltzmann,
    createThomsonCrossSection: createThomsonCrossSection,
    createVacuumImpedance: createVacuumImpedance,
    createWeakMixingAngle: createWeakMixingAngle,
    createWienDisplacement: createWienDisplacement,
    createApplyTransform: createApplyTransform,
    createColumnTransform: createColumnTransform,
    createFilterTransform: createFilterTransform,
    createForEachTransform: createForEachTransform,
    createIndexTransform: createIndexTransform,
    createMapTransform: createMapTransform,
    createMaxTransform: createMaxTransform,
    createMeanTransform: createMeanTransform,
    createMinTransform: createMinTransform,
    createRangeTransform: createRangeTransform,
    createRowTransform: createRowTransform,
    createSubsetTransform: createSubsetTransform,
    createConcatTransform: createConcatTransform,
    createDiffTransform: createDiffTransform,
    createStdTransform: createStdTransform,
    createSumTransform: createSumTransform,
    createQuantileSeqTransform: createQuantileSeqTransform,
    createCumSumTransform: createCumSumTransform,
    createVarianceTransform: createVarianceTransform,
    createPrintTransform: createPrintTransform,
    createAndTransform: createAndTransform,
    createOrTransform: createOrTransform,
    createBitAndTransform: createBitAndTransform,
    createBitOrTransform: createBitOrTransform
});

// creating all factories here in a separate file is needed to get tree-shaking working
var all = allFactories;

var tinyEmitter = {exports: {}};

function E () {
  // Keep this empty so it's easier to inherit from
  // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)
}

E.prototype = {
  on: function (name, callback, ctx) {
    var e = this.e || (this.e = {});

    (e[name] || (e[name] = [])).push({
      fn: callback,
      ctx: ctx
    });

    return this;
  },

  once: function (name, callback, ctx) {
    var self = this;
    function listener () {
      self.off(name, listener);
      callback.apply(ctx, arguments);
    }
    listener._ = callback;
    return this.on(name, listener, ctx);
  },

  emit: function (name) {
    var data = [].slice.call(arguments, 1);
    var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
    var i = 0;
    var len = evtArr.length;

    for (i; i < len; i++) {
      evtArr[i].fn.apply(evtArr[i].ctx, data);
    }

    return this;
  },

  off: function (name, callback) {
    var e = this.e || (this.e = {});
    var evts = e[name];
    var liveEvents = [];

    if (evts && callback) {
      for (var i = 0, len = evts.length; i < len; i++) {
        if (evts[i].fn !== callback && evts[i].fn._ !== callback)
          liveEvents.push(evts[i]);
      }
    }

    // Remove event from queue to prevent memory leak
    // Suggested by https://github.com/lazd
    // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910

    (liveEvents.length)
      ? e[name] = liveEvents
      : delete e[name];

    return this;
  }
};

tinyEmitter.exports = E;
tinyEmitter.exports.TinyEmitter = E;

var Emitter = tinyEmitter.exports;

/**
 * Extend given object with emitter functions `on`, `off`, `once`, `emit`
 * @param {Object} obj
 * @return {Object} obj
 */
function mixin(obj) {
  // create event emitter
  var emitter = new Emitter();

  // bind methods to obj (we don't want to expose the emitter.e Array...)
  obj.on = emitter.on.bind(emitter);
  obj.off = emitter.off.bind(emitter);
  obj.once = emitter.once.bind(emitter);
  obj.emit = emitter.emit.bind(emitter);
  return obj;
}

function importFactory(typed, load, math, importedFactories) {
  /**
   * Import functions from an object or a module.
   *
   * This function is only available on a mathjs instance created using `create`.
   *
   * Syntax:
   *
   *    math.import(functions)
   *    math.import(functions, options)
   *
   * Where:
   *
   * - `functions: Object`
   *   An object with functions or factories to be imported.
   * - `options: Object` An object with import options. Available options:
   *   - `override: boolean`
   *     If true, existing functions will be overwritten. False by default.
   *   - `silent: boolean`
   *     If true, the function will not throw errors on duplicates or invalid
   *     types. False by default.
   *   - `wrap: boolean`
   *     If true, the functions will be wrapped in a wrapper function
   *     which converts data types like Matrix to primitive data types like Array.
   *     The wrapper is needed when extending math.js with libraries which do not
   *     support these data type. False by default.
   *
   * Examples:
   *
   *    import { create, all } from 'mathjs'
   *    import * as numbers from 'numbers'
   *
   *    // create a mathjs instance
   *    const math = create(all)
   *
   *    // define new functions and variables
   *    math.import({
   *      myvalue: 42,
   *      hello: function (name) {
   *        return 'hello, ' + name + '!'
   *      }
   *    })
   *
   *    // use the imported function and variable
   *    math.myvalue * 2               // 84
   *    math.hello('user')             // 'hello, user!'
   *
   *    // import the npm module 'numbers'
   *    // (must be installed first with `npm install numbers`)
   *    math.import(numbers, {wrap: true})
   *
   *    math.fibonacci(7) // returns 13
   *
   * @param {Object | Array} functions  Object with functions to be imported.
   * @param {Object} [options]          Import options.
   */
  function mathImport(functions, options) {
    var num = arguments.length;
    if (num !== 1 && num !== 2) {
      throw new ArgumentsError('import', num, 1, 2);
    }
    if (!options) {
      options = {};
    }
    function flattenImports(flatValues, value, name) {
      if (Array.isArray(value)) {
        value.forEach(item => flattenImports(flatValues, item));
      } else if (typeof value === 'object') {
        for (var _name in value) {
          if (hasOwnProperty(value, _name)) {
            flattenImports(flatValues, value[_name], _name);
          }
        }
      } else if (isFactory(value) || name !== undefined) {
        var flatName = isFactory(value) ? isTransformFunctionFactory(value) ? value.fn + '.transform' // TODO: this is ugly
        : value.fn : name;

        // we allow importing the same function twice if it points to the same implementation
        if (hasOwnProperty(flatValues, flatName) && flatValues[flatName] !== value && !options.silent) {
          throw new Error('Cannot import "' + flatName + '" twice');
        }
        flatValues[flatName] = value;
      } else {
        if (!options.silent) {
          throw new TypeError('Factory, Object, or Array expected');
        }
      }
    }
    var flatValues = {};
    flattenImports(flatValues, functions);
    for (var name in flatValues) {
      if (hasOwnProperty(flatValues, name)) {
        // console.log('import', name)
        var value = flatValues[name];
        if (isFactory(value)) {
          // we ignore name here and enforce the name of the factory
          // maybe at some point we do want to allow overriding it
          // in that case we can implement an option overrideFactoryNames: true
          _importFactory(value, options);
        } else if (isSupportedType(value)) {
          _import(name, value, options);
        } else {
          if (!options.silent) {
            throw new TypeError('Factory, Object, or Array expected');
          }
        }
      }
    }
  }

  /**
   * Add a property to the math namespace
   * @param {string} name
   * @param {*} value
   * @param {Object} options  See import for a description of the options
   * @private
   */
  function _import(name, value, options) {
    // TODO: refactor this function, it's to complicated and contains duplicate code
    if (options.wrap && typeof value === 'function') {
      // create a wrapper around the function
      value = _wrap(value);
    }

    // turn a plain function with a typed-function signature into a typed-function
    if (hasTypedFunctionSignature(value)) {
      value = typed(name, {
        [value.signature]: value
      });
    }
    if (typed.isTypedFunction(math[name]) && typed.isTypedFunction(value)) {
      if (options.override) {
        // give the typed function the right name
        value = typed(name, value.signatures);
      } else {
        // merge the existing and typed function
        value = typed(math[name], value);
      }
      math[name] = value;
      delete importedFactories[name];
      _importTransform(name, value);
      math.emit('import', name, function resolver() {
        return value;
      });
      return;
    }
    if (math[name] === undefined || options.override) {
      math[name] = value;
      delete importedFactories[name];
      _importTransform(name, value);
      math.emit('import', name, function resolver() {
        return value;
      });
      return;
    }
    if (!options.silent) {
      throw new Error('Cannot import "' + name + '": already exists');
    }
  }
  function _importTransform(name, value) {
    if (value && typeof value.transform === 'function') {
      math.expression.transform[name] = value.transform;
      if (allowedInExpressions(name)) {
        math.expression.mathWithTransform[name] = value.transform;
      }
    } else {
      // remove existing transform
      delete math.expression.transform[name];
      if (allowedInExpressions(name)) {
        math.expression.mathWithTransform[name] = value;
      }
    }
  }
  function _deleteTransform(name) {
    delete math.expression.transform[name];
    if (allowedInExpressions(name)) {
      math.expression.mathWithTransform[name] = math[name];
    } else {
      delete math.expression.mathWithTransform[name];
    }
  }

  /**
   * Create a wrapper a round an function which converts the arguments
   * to their primitive values (like convert a Matrix to Array)
   * @param {Function} fn
   * @return {Function} Returns the wrapped function
   * @private
   */
  function _wrap(fn) {
    var wrapper = function wrapper() {
      var args = [];
      for (var i = 0, len = arguments.length; i < len; i++) {
        var arg = arguments[i];
        args[i] = arg && arg.valueOf();
      }
      return fn.apply(math, args);
    };
    if (fn.transform) {
      wrapper.transform = fn.transform;
    }
    return wrapper;
  }

  /**
   * Import an instance of a factory into math.js
   * @param {function(scope: object)} factory
   * @param {Object} options  See import for a description of the options
   * @param {string} [name=factory.name] Optional custom name
   * @private
   */
  function _importFactory(factory, options) {
    var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : factory.fn;
    if (name.includes('.')) {
      throw new Error('Factory name should not contain a nested path. ' + 'Name: ' + JSON.stringify(name));
    }
    var namespace = isTransformFunctionFactory(factory) ? math.expression.transform : math;
    var existingTransform = (name in math.expression.transform);
    var existing = hasOwnProperty(namespace, name) ? namespace[name] : undefined;
    var resolver = function resolver() {
      // collect all dependencies, handle finding both functions and classes and other special cases
      var dependencies = {};
      factory.dependencies.map(stripOptionalNotation).forEach(dependency => {
        if (dependency.includes('.')) {
          throw new Error('Factory dependency should not contain a nested path. ' + 'Name: ' + JSON.stringify(dependency));
        }
        if (dependency === 'math') {
          dependencies.math = math;
        } else if (dependency === 'mathWithTransform') {
          dependencies.mathWithTransform = math.expression.mathWithTransform;
        } else if (dependency === 'classes') {
          // special case for json reviver
          dependencies.classes = math;
        } else {
          dependencies[dependency] = math[dependency];
        }
      });
      var instance = /* #__PURE__ */factory(dependencies);
      if (instance && typeof instance.transform === 'function') {
        throw new Error('Transforms cannot be attached to factory functions. ' + 'Please create a separate function for it with export const path = "expression.transform"');
      }
      if (existing === undefined || options.override) {
        return instance;
      }
      if (typed.isTypedFunction(existing) && typed.isTypedFunction(instance)) {
        // merge the existing and new typed function
        return typed(existing, instance);
      }
      if (options.silent) {
        // keep existing, ignore imported function
        return existing;
      } else {
        throw new Error('Cannot import "' + name + '": already exists');
      }
    };

    // TODO: add unit test with non-lazy factory
    if (!factory.meta || factory.meta.lazy !== false) {
      lazy(namespace, name, resolver);

      // FIXME: remove the `if (existing &&` condition again. Can we make sure subset is loaded before subset.transform? (Name collision, and no dependencies between the two)
      if (existing && existingTransform) {
        _deleteTransform(name);
      } else {
        if (isTransformFunctionFactory(factory) || factoryAllowedInExpressions(factory)) {
          lazy(math.expression.mathWithTransform, name, () => namespace[name]);
        }
      }
    } else {
      namespace[name] = resolver();

      // FIXME: remove the `if (existing &&` condition again. Can we make sure subset is loaded before subset.transform? (Name collision, and no dependencies between the two)
      if (existing && existingTransform) {
        _deleteTransform(name);
      } else {
        if (isTransformFunctionFactory(factory) || factoryAllowedInExpressions(factory)) {
          lazy(math.expression.mathWithTransform, name, () => namespace[name]);
        }
      }
    }

    // TODO: improve factories, store a list with imports instead which can be re-played
    importedFactories[name] = factory;
    math.emit('import', name, resolver);
  }

  /**
   * Check whether given object is a type which can be imported
   * @param {Function | number | string | boolean | null | Unit | Complex} object
   * @return {boolean}
   * @private
   */
  function isSupportedType(object) {
    return typeof object === 'function' || typeof object === 'number' || typeof object === 'string' || typeof object === 'boolean' || object === null || isUnit(object) || isComplex(object) || isBigNumber(object) || isFraction(object) || isMatrix(object) || Array.isArray(object);
  }
  function hasTypedFunctionSignature(fn) {
    return typeof fn === 'function' && typeof fn.signature === 'string';
  }
  function allowedInExpressions(name) {
    return !hasOwnProperty(unsafe, name);
  }
  function factoryAllowedInExpressions(factory) {
    return !factory.fn.includes('.') &&
    // FIXME: make checking on path redundant, check on meta data instead
    !hasOwnProperty(unsafe, factory.fn) && (!factory.meta || !factory.meta.isClass);
  }
  function isTransformFunctionFactory(factory) {
    return factory !== undefined && factory.meta !== undefined && factory.meta.isTransformFunction === true || false;
  }

  // namespaces and functions not available in the parser for safety reasons
  var unsafe = {
    expression: true,
    type: true,
    docs: true,
    error: true,
    json: true,
    chain: true // chain method not supported. Note that there is a unit chain too.
  };
  return mathImport;
}

/**
 * Create a mathjs instance from given factory functions and optionally config
 *
 * Usage:
 *
 *     const mathjs1 = create({ createAdd, createMultiply, ...})
 *     const config = { number: 'BigNumber' }
 *     const mathjs2 = create(all, config)
 *
 * @param {Object} [factories] An object with factory functions
 *                             The object can contain nested objects,
 *                             all nested objects will be flattened.
 * @param {Object} [config]    Available options:
 *                            {number} relTol
 *                              Minimum relative difference between two
 *                              compared values, used by all comparison functions.
 *                            {number} absTol
 *                              Minimum absolute difference between two
 *                              compared values, used by all comparison functions.
 *                            {string} matrix
 *                              A string 'Matrix' (default) or 'Array'.
 *                            {string} number
 *                              A string 'number' (default), 'BigNumber', or 'Fraction'
 *                            {number} precision
 *                              The number of significant digits for BigNumbers.
 *                              Not applicable for Numbers.
 *                            {boolean} predictable
 *                              Predictable output type of functions. When true,
 *                              output type depends only on the input types. When
 *                              false (default), output type can vary depending
 *                              on input values. For example `math.sqrt(-4)`
 *                              returns `complex('2i')` when predictable is false, and
 *                              returns `NaN` when true.
 *                            {string} randomSeed
 *                              Random seed for seeded pseudo random number generator.
 *                              Set to null to randomly seed.
 * @returns {Object} Returns a bare-bone math.js instance containing
 *                   functions:
 *                   - `import` to add new functions
 *                   - `config` to change configuration
 *                   - `on`, `off`, `once`, `emit` for events
 */
function create(factories, config) {
  var configInternal = _extends$1({}, DEFAULT_CONFIG, config);

  // simple test for ES5 support
  if (typeof Object.create !== 'function') {
    throw new Error('ES5 not supported by this JavaScript engine. ' + 'Please load the es5-shim and es5-sham library for compatibility.');
  }

  // create the mathjs instance
  var math = mixin({
    // only here for backward compatibility for legacy factory functions
    isNumber,
    isComplex,
    isBigNumber,
    isBigInt,
    isFraction,
    isUnit,
    isString,
    isArray,
    isMatrix,
    isCollection,
    isDenseMatrix,
    isSparseMatrix,
    isRange,
    isIndex,
    isBoolean,
    isResultSet,
    isHelp,
    isFunction,
    isDate,
    isRegExp,
    isObject,
    isNull,
    isUndefined,
    isAccessorNode,
    isArrayNode,
    isAssignmentNode,
    isBlockNode,
    isConditionalNode,
    isConstantNode,
    isFunctionAssignmentNode,
    isFunctionNode,
    isIndexNode,
    isNode,
    isObjectNode,
    isOperatorNode,
    isParenthesisNode,
    isRangeNode,
    isRelationalNode,
    isSymbolNode,
    isChain
  });

  // load config function and apply provided config
  math.config = configFactory(configInternal, math.emit);
  math.expression = {
    transform: {},
    mathWithTransform: {
      config: math.config
    }
  };

  // cached factories and instances used by function load
  var legacyFactories = [];
  var legacyInstances = [];

  /**
   * Load a function or data type from a factory.
   * If the function or data type already exists, the existing instance is
   * returned.
   * @param {Function} factory
   * @returns {*}
   */
  function load(factory) {
    if (isFactory(factory)) {
      return factory(math);
    }
    var firstProperty = factory[Object.keys(factory)[0]];
    if (isFactory(firstProperty)) {
      return firstProperty(math);
    }
    if (!isLegacyFactory(factory)) {
      console.warn('Factory object with properties `type`, `name`, and `factory` expected', factory);
      throw new Error('Factory object with properties `type`, `name`, and `factory` expected');
    }
    var index = legacyFactories.indexOf(factory);
    var instance;
    if (index === -1) {
      // doesn't yet exist
      if (factory.math === true) {
        // pass with math namespace
        instance = factory.factory(math.type, configInternal, load, math.typed, math);
      } else {
        instance = factory.factory(math.type, configInternal, load, math.typed);
      }

      // append to the cache
      legacyFactories.push(factory);
      legacyInstances.push(instance);
    } else {
      // already existing function, return the cached instance
      instance = legacyInstances[index];
    }
    return instance;
  }
  var importedFactories = {};

  // load the import function
  function lazyTyped() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    return math.typed.apply(math.typed, args);
  }
  lazyTyped.isTypedFunction = typedFunction.isTypedFunction;
  var internalImport = importFactory(lazyTyped, load, math, importedFactories);
  math.import = internalImport;

  // listen for changes in config, import all functions again when changed
  // TODO: move this listener into the import function?
  math.on('config', () => {
    Object.values(importedFactories).forEach(factory => {
      if (factory && factory.meta && factory.meta.recreateOnConfigChange) {
        // FIXME: only re-create when the current instance is the same as was initially created
        // FIXME: delete the functions/constants before importing them again?
        internalImport(factory, {
          override: true
        });
      }
    });
  });

  // the create function exposed on the mathjs instance is bound to
  // the factory functions passed before
  math.create = create.bind(null, factories);

  // export factory function
  math.factory = factory;

  // import the factory functions like createAdd as an array instead of object,
  // else they will get a different naming (`createAdd` instead of `add`).
  math.import(Object.values(deepFlatten(factories)));
  math.ArgumentsError = ArgumentsError;
  math.DimensionError = DimensionError;
  math.IndexError = IndexError;
  return math;
}

/** Calculate a unique SHA-256 hash for the given object */
function calculateHash(val) {
    return __awaiter(this, void 0, void 0, function* () {
        const data = new TextEncoder().encode(JSON.stringify(val));
        /* istanbul ignore if */
        if (typeof crypto !== "undefined") {
            const buffer = yield crypto.subtle.digest("SHA-256", data);
            const raw = Array.from(new Uint8Array(buffer));
            // Convery binary hash to hex
            const hash = raw.map((b) => b.toString(16).padStart(2, "0")).join("");
            return hash;
        }
        else {
            // Use node `crypto` module as fallback when browser subtle crypto does not exist,
            // this primarily exists to allow tests to generate hashes, and will not function if used in the browser context
            const { createHash } = yield Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('crypto')); });
            return createHash("sha256").update(data).digest("hex");
        }
    });
}
/** Unsafe cast method.
 *  Will transform the given type `F` into `T`,
 *      use only when you know this will be valid. */
function ucast(o) {
    return o;
}

var DegreeMode;
(function (DegreeMode) {
    DegreeMode["Radians"] = "RADIANS";
    DegreeMode["Degrees"] = "DEGREES";
})(DegreeMode || (DegreeMode = {}));
var LineStyle;
(function (LineStyle) {
    LineStyle["Solid"] = "SOLID";
    LineStyle["Dashed"] = "DASHED";
    LineStyle["Dotted"] = "DOTTED";
})(LineStyle || (LineStyle = {}));
var PointStyle;
(function (PointStyle) {
    PointStyle["Point"] = "POINT";
    PointStyle["Open"] = "OPEN";
    PointStyle["Cross"] = "CROSS";
})(PointStyle || (PointStyle = {}));
var ColorConstant;
(function (ColorConstant) {
    ColorConstant["Red"] = "#ff0000";
    ColorConstant["Green"] = "#00ff00";
    ColorConstant["Blue"] = "#0000ff";
    ColorConstant["Yellow"] = "#ffff00";
    ColorConstant["Magenta"] = "#ff00ff";
    ColorConstant["Cyan"] = "#00ffff";
    ColorConstant["Purple"] = "#6042a6";
    ColorConstant["Orange"] = "#ffa500";
    ColorConstant["Black"] = "#000000";
    ColorConstant["White"] = "#ffffff";
})(ColorConstant || (ColorConstant = {}));

const math = create(all, { number: "number" });
/** The maximum dimensions of a graph */
const MAX_SIZE = 99999;
const DEFAULT_GRAPH_SETTINGS = {
    width: 600,
    height: 400,
    left: -10,
    right: 10,
    bottom: -7,
    top: 7,
    grid: true,
    degreeMode: DegreeMode.Radians,
    hideAxisNumbers: false,
    xAxisLogarithmic: false,
    yAxisLogarithmic: false,
};
const DEFAULT_GRAPH_WIDTH = Math.abs(DEFAULT_GRAPH_SETTINGS.left) + Math.abs(DEFAULT_GRAPH_SETTINGS.right);
const DEFAULT_GRAPH_HEIGHT = Math.abs(DEFAULT_GRAPH_SETTINGS.bottom) + Math.abs(DEFAULT_GRAPH_SETTINGS.top);
function parseStringToEnum(obj, key) {
    const objKey = Object.keys(obj).find((k) => k.toUpperCase() === key.toUpperCase());
    return objKey ? obj[objKey] : null;
}
function parseColor(value) {
    // If the value is a valid hex colour
    if (value.startsWith("#")) {
        // Ensure the rest of the value is a valid alphanumeric string
        if (/^[0-9a-zA-Z]+$/.test(value.slice(1))) {
            return value;
        }
    }
    // If the value is a valid colour constant
    return parseStringToEnum(ColorConstant, value);
}
class Graph {
    constructor(equations, settings, potentialErrorHint) {
        this.equations = equations;
        this.potentialErrorHint = potentialErrorHint;
        // Adjust bounds (if needed)
        Graph.adjustBounds(settings);
        // Generate hash on the raw equation and setting data,
        //  this means that if we extend the settings with new fields pre-existing graphs will have the same hash
        this._hash = calculateHash({ equations, settings });
        // Apply defaults
        this.settings = Object.assign(Object.assign({}, DEFAULT_GRAPH_SETTINGS), settings);
        // Validate settings
        Graph.validateSettings(this.settings);
        // Apply color override
        if (this.settings.defaultColor) {
            this.equations = this.equations.map((equation) => {
                var _a;
                return (Object.assign({ color: (_a = equation.color) !== null && _a !== void 0 ? _a : this.settings.defaultColor }, equation));
            });
        }
    }
    static parse(source) {
        let potentialErrorHint;
        const split = source.split("---");
        if (split.length > 2) {
            throw new SyntaxError("Too many graph segments, there can only be a singular  '---'");
        }
        // Each (non-blank) line of the equation source contains an equation,
        //  this will always be the last segment
        const equations = split[split.length - 1]
            .split(/\r?\n/g)
            .filter((equation) => equation.trim() !== "")
            .map(Graph.parseEquation)
            .map((result) => {
            if (result.hint) {
                potentialErrorHint = result.hint;
            }
            return result.data;
        });
        // If there is more than one segment then the first one will contain the settings
        const settings = split.length > 1 ? Graph.parseSettings(split[0]) : {};
        return new Graph(equations, settings, potentialErrorHint);
    }
    hash() {
        return __awaiter(this, void 0, void 0, function* () {
            return this._hash;
        });
    }
    static validateSettings(settings) {
        // Check graph is within maximum size
        if ((settings.width && settings.width > MAX_SIZE) || (settings.height && settings.height > MAX_SIZE)) {
            throw new SyntaxError(`Graph size outside of accepted bounds (must be <${MAX_SIZE}x${MAX_SIZE})`);
        }
        // Ensure boundaries are correct
        if (settings.left >= settings.right) {
            throw new SyntaxError(`Right boundary (${settings.right}) must be greater than left boundary (${settings.left})`);
        }
        if (settings.bottom >= settings.top) {
            throw new SyntaxError(`
                Top boundary (${settings.top}) must be greater than bottom boundary (${settings.bottom})
            `);
        }
    }
    static parseEquation(eq) {
        var _a;
        let hint;
        const segments = eq
            .split("|")
            .map((segment) => segment.trim())
            .filter((segment) => segment !== "");
        // First segment is always the equation
        const equation = { equation: ucast(segments.shift()) };
        // The rest of the segments can either be the restriction, style, or color
        //  whilst we recommend putting the restriction first, we accept these in any order.
        for (const segment of segments) {
            const segmentUpperCase = segment.toUpperCase();
            // If this is a `hidden` tag
            if (segmentUpperCase === "HIDDEN") {
                equation.hidden = true;
                continue;
            }
            // If this is a valid `noline` tag
            if (segmentUpperCase === "NOLINE") {
                equation.line = false;
                continue;
            }
            // If this is a valid style constant
            const style = (_a = parseStringToEnum(LineStyle, segmentUpperCase)) !== null && _a !== void 0 ? _a : parseStringToEnum(PointStyle, segmentUpperCase);
            if (style) {
                if (!equation.style) {
                    equation.style = style;
                }
                else {
                    throw new SyntaxError(`Duplicate style identifiers detected: ${equation.style}, ${segment}`);
                }
                continue;
            }
            // If this is a valid color constant or hex code
            const color = parseColor(segment);
            if (color) {
                if (!equation.color) {
                    equation.color = color;
                }
                else {
                    throw new SyntaxError(`Duplicate color identifiers detected, each equation may only contain a single color code.`);
                }
                continue;
            }
            // If this is a valid label string
            if (segmentUpperCase.startsWith("LABEL:")) {
                const label = segment.split(":").slice(1).join(":").trim();
                if (equation.label === undefined) {
                    if (label === "") {
                        throw new SyntaxError(`Equation label must have a value`);
                    }
                    else {
                        equation.label = label;
                    }
                }
                else {
                    throw new SyntaxError(`Duplicate equation labels detected, each equation may only contain a single label.`);
                }
                continue;
            }
            // If this is a valid defult label string
            if (segmentUpperCase === "LABEL") {
                // If we pass an empty string as the label,
                //  Desmos will use the source equation of the point as the label
                equation.label = "";
                continue;
            }
            // If none of the above, assume it is a graph restriction
            if (segment.includes("\\")) {
                // If the restriction included a `\` (the LaTeX control character) then the user may have tried to use the LaTeX syntax in the graph restriction (e.g `\frac{1}{2}`)
                //  Desmos does not allow this but returns a fairly archaic error - "A piecewise expression must have at least one condition."
                const view = document.createElement("span");
                const pre = document.createElement("span");
                pre.innerHTML = "You may have tried to use the LaTeX syntax in the graph restriction (";
                const inner = document.createElement("code");
                inner.innerText = segment;
                const post = document.createElement("span");
                post.innerHTML =
                    "), please use some sort of an alternative (e.g <code>\\frac{1}{2}</code> => <code>1/2</code>) as this is not supported by Desmos.";
                view.appendChild(pre);
                view.appendChild(inner);
                view.appendChild(post);
                hint = { view };
            }
            if (!equation.restrictions) {
                equation.restrictions = [];
            }
            equation.restrictions.push(segment);
        }
        return { data: equation, hint };
    }
    static parseSettings(settings) {
        const graphSettings = {};
        // Settings may be separated by either a newline or semicolon
        settings
            .split(/[;\n]/g)
            .map((setting) => setting.trim())
            .filter((setting) => setting !== "")
            // Extract key-value pairs by splitting on the `=` in each property
            .map((setting) => setting.split("="))
            .forEach((setting) => {
            if (setting.length > 2) {
                throw new SyntaxError(`Too many segments, eaching setting must only contain a maximum of one '=' sign`);
            }
            const key = setting[0].trim();
            const value = setting.length > 1 ? setting[1].trim() : undefined;
            // Prevent duplicate keys
            if (key in graphSettings) {
                throw new SyntaxError(`Duplicate key '${key}' not allowed`);
            }
            const requiresValue = () => {
                if (value === undefined) {
                    throw new SyntaxError(`Field '${key}' must have a value`);
                }
            };
            switch (key) {
                // Boolean fields
                case "hideAxisNumbers":
                case "xAxisLogarithmic":
                case "yAxisLogarithmic":
                case "grid": {
                    if (!value) {
                        graphSettings[key] = true;
                    }
                    else {
                        const lower = value.toLowerCase();
                        if (lower !== "true" && lower !== "false") {
                            throw new SyntaxError(`Field '${key}' requres a boolean value 'true'/'false' (omit a value to default to 'true')`);
                        }
                        graphSettings[key] = value === "true" ? true : false;
                    }
                    break;
                }
                // String fields
                case "xAxisLabel":
                case "yAxisLabel": {
                    requiresValue();
                    graphSettings[key] = value;
                    break;
                }
                // Expression fields
                case "top":
                case "bottom":
                case "left":
                case "right":
                case "width":
                case "height": {
                    requiresValue();
                    // These fields can be simple math expressions (such as pi/2)
                    graphSettings[key] = math.evaluate(value);
                    break;
                }
                // DegreeMode field
                case "degreeMode": {
                    requiresValue();
                    const mode = parseStringToEnum(DegreeMode, value);
                    if (mode) {
                        graphSettings.degreeMode = mode;
                    }
                    else {
                        throw new SyntaxError(`Field 'degreeMode' must be either 'radians' or 'degrees'`);
                    }
                    break;
                }
                // Color field
                case "defaultColor": {
                    requiresValue();
                    const color = parseColor(value);
                    if (color) {
                        graphSettings.defaultColor = color;
                    }
                    else {
                        throw new SyntaxError(`Field 'defaultColor' must be either a valid hex code or one of: ${Object.keys(ColorConstant).join(", ")}`);
                    }
                    break;
                }
                default: {
                    throw new SyntaxError(`Unrecognised field: ${key}`);
                }
            }
        });
        return graphSettings;
    }
    /** Dynamically adjust graph boundary if the defaults would cause an invalid graph with the settings supplied by the user,
     *  this will not do anything if the adjustment is not required.
     */
    static adjustBounds(settings) {
        if (settings.left !== undefined &&
            settings.right === undefined &&
            settings.left >= DEFAULT_GRAPH_SETTINGS.right) {
            settings.right = settings.left + DEFAULT_GRAPH_WIDTH;
        }
        if (settings.left === undefined &&
            settings.right !== undefined &&
            settings.right <= DEFAULT_GRAPH_SETTINGS.left) {
            settings.left = settings.right - DEFAULT_GRAPH_WIDTH;
        }
        if (settings.bottom !== undefined &&
            settings.top === undefined &&
            settings.bottom >= DEFAULT_GRAPH_SETTINGS.top) {
            settings.top = settings.bottom + DEFAULT_GRAPH_HEIGHT;
        }
        if (settings.bottom === undefined &&
            settings.top !== undefined &&
            settings.top <= DEFAULT_GRAPH_SETTINGS.bottom) {
            settings.bottom = settings.top - DEFAULT_GRAPH_HEIGHT;
        }
        return settings;
    }
}

function renderError(err, el, extra) {
    const wrapper = document.createElement("div");
    const message = document.createElement("strong");
    message.innerText = "Desmos Graph Error: ";
    wrapper.appendChild(message);
    const ctx = document.createElement("span");
    ctx.innerText = err;
    wrapper.appendChild(ctx);
    if (extra) {
        const messageExtra = document.createElement("strong");
        messageExtra.innerHTML = "<br>Note: ";
        wrapper.appendChild(messageExtra);
        wrapper.appendChild(extra);
    }
    const container = document.createElement("div");
    container.style.padding = "20px";
    container.style.backgroundColor = "#f44336";
    container.style.color = "white";
    container.appendChild(wrapper);
    el.empty();
    el.appendChild(container);
}

var CacheLocation;
(function (CacheLocation) {
    CacheLocation["Memory"] = "Memory";
    CacheLocation["Filesystem"] = "Filesystem";
})(CacheLocation || (CacheLocation = {}));
const DEFAULT_SETTINGS_STATIC = {
    // debounce: 500,
    renderer: true,
    cache: {
        enabled: true,
        location: CacheLocation.Memory,
    },
};
/** Get the default settings for the given plugin. This simply uses `DEFAULT_SETTINGS_STATIC` and patches the version from the manifest. */
function DEFAULT_SETTINGS(plugin) {
    return Object.assign({ version: plugin.manifest.version }, DEFAULT_SETTINGS_STATIC);
}
/** Attempt to migrate the given settings object to the current structure */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function migrateSettings(plugin, settings) {
    if (!Object.prototype.hasOwnProperty.call(settings, "renderer")) {
        settings.renderer = DEFAULT_SETTINGS_STATIC.renderer;
    }
    return settings;
}
class SettingsTab extends obsidian.PluginSettingTab {
    constructor(app, plugin) {
        super(app, plugin);
        this.plugin = plugin;
    }
    display() {
        const { containerEl } = this;
        containerEl.empty();
        // new Setting(containerEl)
        //     .setName("Debounce Time (ms)")
        //     .setDesc(
        //         "How long to wait after a keypress to render the graph (set to 0 to disable, requires restart to take effect)"
        //     )
        //     .addText((text) =>
        //         text.setValue(this.plugin.settings.debounce.toString()).onChange(async (value) => {
        //             const val = parseInt(value);
        //             this.plugin.settings.debounce =
        //                 Number.isNaN(val) || val < 0 ? DEFAULT_SETTINGS_STATIC.debounce : val;
        //             await this.plugin.saveSettings();
        //         })
        //     );
        new obsidian.Setting(containerEl)
            .setName("Cache")
            .setDesc("Whether to cache the rendered graphs")
            .addToggle((toggle) => toggle.setValue(this.plugin.settings.cache.enabled).onChange((value) => __awaiter(this, void 0, void 0, function* () {
            this.plugin.settings.cache.enabled = value;
            yield this.plugin.saveSettings();
            // Reset the display so the new state can render
            this.display();
        })));
        if (this.plugin.settings.cache.enabled) {
            new obsidian.Setting(containerEl)
                .setName("Cache location")
                .setDesc("Set the location to cache rendered graphs (note that memory caching is not persistent)")
                .addDropdown((dropdown) => dropdown
                .addOption(CacheLocation.Memory, "Memory")
                .addOption(CacheLocation.Filesystem, "Filesystem")
                .setValue(this.plugin.settings.cache.location)
                .onChange((value) => __awaiter(this, void 0, void 0, function* () {
                this.plugin.settings.cache.location = value;
                if (this.plugin.settings.cache.location != CacheLocation.Filesystem) {
                    this.plugin.settings.renderer = true;
                }
                yield this.plugin.saveSettings();
                // Reset the display so the new state can render
                this.display();
            })));
            if (this.plugin.settings.cache.location === CacheLocation.Filesystem) {
                new obsidian.Setting(containerEl)
                    .setName("Cache Directory")
                    .setDesc(`The directory to save cached graphs in, relative to the vault root (technical note: the graphs will be saved as \`desmos-graph-<hash>.svg\` where the name is a SHA-256 hash of the graph source). Also note that a lot of junk will be saved to this folder, you have been warned.`)
                    .addText((text) => {
                    var _a;
                    text.setValue((_a = this.plugin.settings.cache.directory) !== null && _a !== void 0 ? _a : "").onChange((value) => __awaiter(this, void 0, void 0, function* () {
                        this.plugin.settings.cache.directory = value;
                        yield this.plugin.saveSettings();
                    }));
                });
                new obsidian.Setting(containerEl)
                    .setName("Renderer")
                    .setDesc("Whether to enable the graph renderer. Turning this off will prevent any new graphs from rendering, but will ensure all cached graphs are rendered instantly. If this is disabled, filesystem caching is recommended. This setting should be used for external exporting (such as to a website or pdf).")
                    .addToggle((toggle) => toggle.setValue(this.plugin.settings.renderer).onChange((value) => __awaiter(this, void 0, void 0, function* () {
                    this.plugin.settings.renderer = value;
                    yield this.plugin.saveSettings();
                    // Reset the display so the new state can render
                    this.display();
                })));
            }
        }
    }
}

/** Parse an SVG into a DOM element */
function parseSVG(svg) {
    return new DOMParser().parseFromString(svg, "image/svg+xml").documentElement;
}
class Renderer {
    constructor(plugin) {
        /** The set of graphs we are currently rendering, mapped by their hash */
        this.rendering = new Map();
        this.plugin = plugin;
        this.active = false;
    }
    activate() {
        if (!this.active) {
            window.addEventListener("message", this.handler.bind(this));
            this.active = true;
        }
    }
    deactivate() {
        if (this.active) {
            window.removeEventListener("message", this.handler.bind(this));
            this.active = false;
        }
    }
    render(graph, el) {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function* () {
            const plugin = this.plugin;
            const settings = plugin.settings;
            const equations = graph.equations;
            const graphSettings = graph.settings;
            const hash = yield graph.hash();
            let cacheFile;
            // If this graph is in the cache then fetch it
            if (settings.cache.enabled) {
                if (settings.cache.location === CacheLocation.Memory && hash in plugin.graphCache) {
                    const data = plugin.graphCache[hash];
                    el.appendChild(parseSVG(data));
                    return;
                }
                else if (settings.cache.location === CacheLocation.Filesystem && settings.cache.directory) {
                    const adapter = plugin.app.vault.adapter;
                    cacheFile = obsidian.normalizePath(`${settings.cache.directory}/desmos-graph-${hash}.svg`);
                    // If this graph is in the cache
                    if (yield adapter.exists(cacheFile)) {
                        const data = yield adapter.read(cacheFile);
                        el.appendChild(parseSVG(data));
                        return;
                    }
                }
            }
            if (!plugin.settings.renderer) {
                // If the renderer is disabled, throw an error
                throw new Error("Unable to render a new graph with the renderer disabled. Set the 'Renderer' option to true in the plugin config (requires filesystem caching) to allow rendering new graphs again. If you're trying to export, all graphs must be in the graph cache (meaning they must have been viewd before the renderer was disabled).");
            }
            // Parse equations into a series of Desmos expressions
            const expressions = [];
            for (const equation of equations) {
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                const expression = {
                    color: equation.color,
                    label: equation.label,
                    hidden: equation.hidden,
                    showLabel: equation.label !== undefined,
                    lines: equation.line,
                };
                if (equation.restrictions) {
                    const restriction = equation.restrictions
                        .map((restriction) => `{${restriction}}`
                        // Escape chars
                        .replaceAll("{", String.raw `\{`)
                        .replaceAll("}", String.raw `\}`)
                        .replaceAll("<=", String.raw `\leq `)
                        .replaceAll(">=", String.raw `\geq `)
                        .replaceAll("<", String.raw `\le `)
                        .replaceAll(">", String.raw `\ge `))
                        .join("");
                    expression.latex = `${equation.equation}${restriction}`;
                }
                else {
                    expression.latex = equation.equation;
                }
                if (equation.style) {
                    if (Object.values(LineStyle).includes(ucast(equation.style))) {
                        expression.lineStyle = equation.style;
                    }
                    else if (Object.values(PointStyle).includes(ucast(equation.style))) {
                        expression.pointStyle = equation.style;
                    }
                }
                // Calling JSON.stringify twice allows us to escape the strings as well,
                //  meaning we can embed it directly into the calculator to undo the first stringification without parsing
                expressions.push(`calculator.setExpression(JSON.parse(${JSON.stringify(JSON.stringify(expression))}));`);
            }
            // Because of the electron sandboxing we have to do this inside an iframe (and regardless this is safer)
            const htmlHead = `<script id="desmos-api">${yield plugin.tryCacheDesmosApi()}</script>`;
            const htmlBody = `
            <div id="calculator-${hash}" style="width: ${graphSettings.width}px; height: ${graphSettings.height}px;"></div>
            <script>
                const options = {
                    settingsMenu: false,
                    expressions: false,
                    lockViewPort: true,
                    zoomButtons: false,
                    trace: false,
                    xAxisNumbers: ${!graphSettings.hideAxisNumbers},
                    yAxisNumbers: ${!graphSettings.hideAxisNumbers},
                    showGrid: ${graphSettings.grid},
                    // Desmos takes a value of 'false' for radians and 'true' for degrees
                    degreeMode: ${graphSettings.degreeMode === DegreeMode.Degrees},
                };

                if (${graphSettings.xAxisLabel !== undefined}) {
                    options.xAxisLabel = "${JSON.stringify((_a = graphSettings.xAxisLabel) !== null && _a !== void 0 ? _a : "").slice(1, -1)}";
                }

                if (${graphSettings.yAxisLabel !== undefined}) {
                    options.yAxisLabel = "${JSON.stringify((_b = graphSettings.yAxisLabel) !== null && _b !== void 0 ? _b : "").slice(1, -1)}";
                }

                options.xAxisScale = "${graphSettings.xAxisLogarithmic ? "logarithmic" : "linear"}";
                options.yAxisScale = "${graphSettings.yAxisLogarithmic ? "logarithmic" : "linear"}";

                const calculator = Desmos.GraphingCalculator(document.getElementById("calculator-${hash}"), options);
                calculator.setMathBounds({
                    left: ${graphSettings.left},
                    right: ${graphSettings.right},
                    top: ${graphSettings.top},
                    bottom: ${graphSettings.bottom},
                });

                ${expressions.join("\n")}

                // Desmos returns an error if we try to observe the expressions without any defined
                if (${expressions.length > 0}) {
                    calculator.observe("expressionAnalysis", () => {
                        for (const id in calculator.expressionAnalysis) {
                            const analysis = calculator.expressionAnalysis[id];
                            if (analysis.isError) {
                                parent.postMessage({ t: "desmos-graph", d: "error", o: "${window.origin}", data: analysis.errorMessage, hash: "${hash}" }, "${window.origin}");
                            }
                        }
                    });
                }

                calculator.asyncScreenshot({ showLabels: true, format: "svg" }, (data) => {
                    document.body.innerHTML = "";
                    parent.postMessage({ t: "desmos-graph", d: "render", o: "${window.origin}", data, hash: "${hash}" }, "${window.origin}");
                });
            </script>
        `;
            const htmlSrc = `<html><head>${htmlHead}</head><body>${htmlBody}</body>`;
            const iframe = document.createElement("iframe");
            iframe.sandbox.add("allow-scripts"); // enable sandbox mode - this prevents any xss exploits from an untrusted source in the frame (and prevents it from accessing the parent)
            iframe.width = graphSettings.width.toString();
            iframe.height = graphSettings.height.toString();
            iframe.className = "desmos-graph";
            iframe.style.border = "none";
            iframe.scrolling = "no"; // fixme use a non-depreciated function
            iframe.srcdoc = htmlSrc;
            // iframe.style.display = "none"; // fixme hiding the iframe breaks the positioning
            el.appendChild(iframe);
            return new Promise((resolve) => this.rendering.set(hash, { graph, el, resolve, cacheFile }));
        });
    }
    handler(message) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            if (message.data.o === window.origin && message.data.t === "desmos-graph") {
                const state = this.rendering.get(message.data.hash);
                if (state) {
                    const { graph, el, resolve, cacheFile } = state;
                    el.empty();
                    if (message.data.d === "error") {
                        renderError(message.data.data, el, (_a = graph.potentialErrorHint) === null || _a === void 0 ? void 0 : _a.view);
                        resolve(); // let caller know we are done rendering
                    }
                    else if (message.data.d === "render") {
                        const { data } = message.data;
                        const node = parseSVG(data);
                        node.setAttribute("class", "desmos-graph");
                        el.appendChild(node);
                        resolve(); // let caller know we are done rendering
                        const plugin = this.plugin;
                        const settings = plugin.settings;
                        const hash = yield graph.hash();
                        if (settings.cache.enabled) {
                            if (settings.cache.location === CacheLocation.Memory) {
                                plugin.graphCache[hash] = data;
                            }
                            else if (settings.cache.location === CacheLocation.Filesystem) {
                                const adapter = plugin.app.vault.adapter;
                                if (cacheFile && settings.cache.directory) {
                                    if (yield adapter.exists(settings.cache.directory)) {
                                        yield adapter.write(cacheFile, data);
                                    }
                                    else {
                                        new obsidian.Notice(`desmos-graph: target cache directory '${settings.cache.directory}' does not exist, skipping cache`, 10000);
                                    }
                                }
                                else {
                                    new obsidian.Notice(`desmos-graph: filesystem caching enabled but no cache directory set, skipping cache`, 10000);
                                }
                            }
                        }
                    }
                    this.rendering.delete(message.data.hash);
                }
                else {
                    // do nothing if graph is not in render list (this should not happen)
                    console.warn(`Got graph not in render list, this is probably a bug - ${JSON.stringify(this.rendering)}`);
                }
            }
        });
    }
}

class Desmos extends obsidian.Plugin {
    constructor() {
        super(...arguments);
        /** Helper for in-memory graph caching */
        this.graphCache = {};
        /** A cache that stores the Desmos API */
        this.desmosApiCache = null;
    }
    onload() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.loadSettings();
            this.renderer = new Renderer(this);
            this.renderer.activate();
            this.addSettingTab(new SettingsTab(this.app, this));
            this.registerMarkdownCodeBlockProcessor("desmos-graph", (source, el) => __awaiter(this, void 0, void 0, function* () {
                try {
                    const graph = Graph.parse(source);
                    yield this.renderer.render(graph, el);
                }
                catch (err) {
                    if (err instanceof Error) {
                        renderError(err.message, el);
                    }
                    else if (typeof err === "string") {
                        renderError(err, el);
                    }
                    else {
                        renderError("Unexpected error - see console for debug log", el);
                        console.error(err);
                    }
                }
            }));
            this.tryCacheDesmosApi(); // note: we don't want to error here if this fails
        });
    }
    unload() {
        return __awaiter(this, void 0, void 0, function* () {
            this.renderer.deactivate();
        });
    }
    loadSettings() {
        return __awaiter(this, void 0, void 0, function* () {
            let settings = yield this.loadData();
            if (!settings) {
                settings = DEFAULT_SETTINGS(this);
            }
            if (settings.version !== this.manifest.version) {
                settings = migrateSettings(this, settings);
            }
            this.settings = settings;
        });
    }
    saveSettings() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.saveData(this.settings);
        });
    }
    tryCacheDesmosApi() {
        return __awaiter(this, void 0, void 0, function* () {
            const api_version = "v1.9"; // todo move this to the config
            const api = `https://www.desmos.com/api/${api_version}/calculator.js?apiKey=dcb31709b452b1cf9dc26972add0fda6`;
            if (obsidian.normalizePath == null) {
                // This means we are most likely in the testing environment;
                //   disable caching
                return yield (yield fetch(api)).text();
            }
            if (this.desmosApiCache != null) {
                return this.desmosApiCache;
            }
            const dir = obsidian.normalizePath(`.obsidian/plugins/${this.manifest.id}/vendor`);
            if (!(yield app.vault.adapter.exists(dir))) {
                yield app.vault.adapter.mkdir(dir);
            }
            // Return cached file if it exists
            const path = obsidian.normalizePath(`.obsidian/plugins/${this.manifest.id}/vendor/desmos.js`);
            if (yield app.vault.adapter.exists(path)) {
                this.desmosApiCache = yield app.vault.adapter.read(path);
                return this.desmosApiCache;
            }
            // Otherwise, download it
            try {
                this.desmosApiCache = yield (yield fetch(api)).text();
                yield app.vault.adapter.write(path, this.desmosApiCache);
                return this.desmosApiCache;
            }
            catch (err) {
                console.warn(err);
                throw new Error("Unable to locate or download the Desmos API. If you don't have an internet connection: try rendering a graph whilst connected. If you have an internet connection: you may be on an unsupported device, please open an issue at https://github.com/Nigecat/obsidian-desmos/");
            }
        });
    }
}

module.exports = Desmos;

/* nosourcemap */