UNPKG

mathjs

Version:

Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with dif

1,550 lines (1,429 loc) 242 kB
import { Decimal } from 'decimal.js' import { Fraction } from 'fraction.js' export { Fraction } export as namespace math export type NoLiteralType<T> = T extends number ? number : T extends string ? string : T extends boolean ? boolean : T export type MathNumericType = number | BigNumber | bigint | Fraction | Complex export type MathScalarType = MathNumericType | Unit export type MathGeneric<T extends MathScalarType = MathNumericType> = T export type MathArray<T = MathGeneric> = T[] | Array<MathArray<T>> export type MathCollection<T = MathGeneric> = MathArray<T> | Matrix<T> export type MathType = MathScalarType | MathCollection export type MathExpression = string | string[] | MathCollection // add type for Matrix Callback Function and Matrix Storage Format export type MatrixStorageFormat = 'dense' | 'sparse' export type MatrixFromFunctionCallback<T extends MathScalarType> = ( index: number[] ) => T // eslint-disable-next-line @typescript-eslint/no-explicit-any export type FactoryFunction<T> = (scope: any) => T // FactoryFunctionMap can be nested; all nested objects will be flattened export interface FactoryFunctionMap { // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: FactoryFunction<any> | FactoryFunctionMap } /** Available options for parse */ export interface ParseOptions { /** a set of custom nodes */ nodes?: Record<string, MathNode> } /** * 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 */ export interface ParseFunction { /** * Parse an expression. Returns a node tree, which can be evaluated by * invoking node.evaluate(); * * @param expr Expression to be parsed * @param options Available options * @returns A node */ (expr: MathExpression, options?: ParseOptions): MathNode /** * Parse an expression. Returns a node tree, which can be evaluated by * invoking node.evaluate(); * * @param exprs Expressions to be parsed * @param options Available options * @returns An array of nodes */ (exprs: MathExpression[], options?: ParseOptions): MathNode[] /** * 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 c Current character in the expression * @param cPrev Previous character * @param cNext Next character */ isAlpha(c: string, cPrev: string, cNext: string): boolean /** * Test whether a character is a valid latin, greek, or letter-like character * * @param c */ isValidLatinOrGreek(c: string): boolean /** * 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 high * @param low */ isValidMathSymbol(high: string, low: string): boolean /** * Check whether given character c is a white space character: space, tab, or enter * * @param c * @param nestingLevel */ isWhitespace(c: string, nestingLevel: number): boolean /** * 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 c * @param cNext */ isDecimalMark(c: string, cNext: string): boolean /** * checks if the given char c is a digit or dot * * @param c a string with one character */ isDigitDot(c: string): boolean /** * checks if the given char c is a digit * * @param c a string with one character */ isDigit(c: string): boolean /** * checks if the given char c is a hex digit * * @param c a string with one character */ isHexDigit(c: string): boolean } export interface NodeCtor { new (): MathNode } export interface AccessorNode<TObject extends MathNode = MathNode> extends MathNode { type: 'AccessorNode' isAccessorNode: true object: TObject index: IndexNode name: string } export interface AccessorNodeCtor { new <TObject extends MathNode = MathNode>( object: TObject, index: IndexNode ): AccessorNode<TObject> } export interface ArrayNode<TItems extends MathNode[] = MathNode[]> extends MathNode { type: 'ArrayNode' isArrayNode: true items: [...TItems] } export interface ArrayNodeCtor { new <TItems extends MathNode[] = MathNode[]>( items: [...TItems] ): ArrayNode<TItems> } export interface AssignmentNode<TValue extends MathNode = MathNode> extends MathNode { type: 'AssignmentNode' isAssignmentNode: true object: SymbolNode | AccessorNode index: IndexNode | null value: TValue name: string } export interface AssignmentNodeCtor { new <TValue extends MathNode = MathNode>( object: SymbolNode, value: TValue ): AssignmentNode<TValue> new <TValue extends MathNode = MathNode>( object: SymbolNode | AccessorNode, index: IndexNode, value: TValue ): AssignmentNode<TValue> } export interface BlockNode<TNode extends MathNode = MathNode> extends MathNode { type: 'BlockNode' isBlockNode: true blocks: Array<{ node: TNode; visible: boolean }> } export interface BlockNodeCtor { new <TNode extends MathNode = MathNode>( arr: Array<{ node: TNode } | { node: TNode; visible: boolean }> ): BlockNode } export interface ConditionalNode< TCond extends MathNode = MathNode, TTrueNode extends MathNode = MathNode, TFalseNode extends MathNode = MathNode > extends MathNode { type: 'ConditionalNode' isConditionalNode: boolean condition: TCond trueExpr: TTrueNode falseExpr: TFalseNode } export interface ConditionalNodeCtor { new < TCond extends MathNode = MathNode, TTrueNode extends MathNode = MathNode, TFalseNode extends MathNode = MathNode >( condition: TCond, trueExpr: TTrueNode, falseExpr: TFalseNode ): ConditionalNode } export interface ConstantNode< TValue extends | string | number | boolean | null | undefined | bigint | BigNumber | Fraction = number > extends MathNode { type: 'ConstantNode' isConstantNode: true // eslint-disable-next-line @typescript-eslint/no-explicit-any value: TValue } export interface ConstantNodeCtor { new < TValue extends | string | number | boolean | null | undefined | bigint | BigNumber | Fraction = string >( value: TValue ): ConstantNode<TValue> } export interface FunctionAssignmentNode<TExpr extends MathNode = MathNode> extends MathNode { type: 'FunctionAssignmentNode' isFunctionAssignmentNode: true name: string params: string[] expr: TExpr } export interface FunctionAssignmentNodeCtor { new <TExpr extends MathNode = MathNode>( name: string, params: string[], expr: TExpr ): FunctionAssignmentNode<TExpr> } export interface FunctionNode< TFn = SymbolNode, TArgs extends MathNode[] = MathNode[] > extends MathNode { type: 'FunctionNode' isFunctionNode: true fn: TFn args: [...TArgs] } export interface FunctionNodeCtor { new <TFn = SymbolNode, TArgs extends MathNode[] = MathNode[]>( fn: TFn, args: [...TArgs] ): FunctionNode<TFn, TArgs> // eslint-disable-next-line @typescript-eslint/no-explicit-any onUndefinedFunction: (name: string) => any } export interface IndexNode<TDims extends MathNode[] = MathNode[]> extends MathNode { type: 'IndexNode' isIndexNode: true dimensions: [...TDims] dotNotation: boolean } export interface IndexNodeCtor { new <TDims extends MathNode[] = MathNode[]>(dimensions: [...TDims]): IndexNode new <TDims extends MathNode[] = MathNode[]>( dimensions: [...TDims], dotNotation: boolean ): IndexNode<TDims> } export interface ObjectNode< TProps extends Record<string, MathNode> = Record<string, MathNode> > extends MathNode { type: 'ObjectNode' isObjectNode: true properties: TProps } export interface ObjectNodeCtor { new <TProps extends Record<string, MathNode> = Record<string, MathNode>>( properties: TProps ): ObjectNode<TProps> } export type OperatorNodeMap = { xor: 'xor' and: 'and' or: 'or' bitOr: '|' bitXor: '^|' bitAnd: '&' equal: '==' unequal: '!=' smaller: '<' larger: '>' smallerEq: '<=' largerEq: '>=' leftShift: '<<' rightArithShift: '>>' rightLogShift: '>>>' to: 'to' add: '+' subtract: '-' multiply: '*' divide: '/' dotMultiply: '.*' dotDivide: './' mod: 'mod' unaryPlus: '+' unaryMinus: '-' bitNot: '~' not: 'not' pow: '^' dotPow: '.^' factorial: '!' } export type OperatorNodeOp = OperatorNodeMap[keyof OperatorNodeMap] export type OperatorNodeFn = keyof OperatorNodeMap export interface OperatorNode< TOp extends OperatorNodeMap[TFn] = never, TFn extends OperatorNodeFn = never, TArgs extends MathNode[] = MathNode[] > extends MathNode { type: 'OperatorNode' isOperatorNode: true op: TOp fn: TFn args: [...TArgs] implicit: boolean isUnary(): boolean isBinary(): boolean } export interface OperatorNodeCtor extends MathNode { new < TOp extends OperatorNodeMap[TFn], TFn extends OperatorNodeFn, TArgs extends MathNode[] >( op: TOp, fn: TFn, args: [...TArgs], implicit?: boolean ): OperatorNode<TOp, TFn, TArgs> } export interface ParenthesisNode<TContent extends MathNode = MathNode> extends MathNode { type: 'ParenthesisNode' isParenthesisNode: true content: TContent } export interface ParenthesisNodeCtor { new <TContent extends MathNode>(content: TContent): ParenthesisNode<TContent> } export interface RangeNode< TStart extends MathNode = MathNode, TEnd extends MathNode = MathNode, TStep extends MathNode = MathNode > extends MathNode { type: 'RangeNode' isRangeNode: true start: TStart end: TEnd step: TStep | null } export interface RangeNodeCtor { new < TStart extends MathNode = MathNode, TEnd extends MathNode = MathNode, TStep extends MathNode = MathNode >( start: TStart, end: TEnd, step?: TStep ): RangeNode<TStart, TEnd, TStep> } export interface RelationalNode<TParams extends MathNode[] = MathNode[]> extends MathNode { type: 'RelationalNode' isRelationalNode: true conditionals: string[] params: [...TParams] } export interface RelationalNodeCtor { new <TParams extends MathNode[] = MathNode[]>( conditionals: string[], params: [...TParams] ): RelationalNode<TParams> } export interface SymbolNode extends MathNode { type: 'SymbolNode' isSymbolNode: true name: string } export interface SymbolNodeCtor { new (name: string): SymbolNode // eslint-disable-next-line @typescript-eslint/no-explicit-any onUndefinedSymbol: (name: string) => any } /** * @deprecated since version 11.3. Prefer `MathNode` instead */ export type MathNodeCommon = MathNode export type MathJsFunctionName = keyof MathJsInstance export interface LUDecomposition { L: MathCollection U: MathCollection p: number[] } export interface SLUDecomposition extends LUDecomposition { q: number[] } export interface QRDecomposition { Q: MathCollection R: MathCollection } export interface SchurDecomposition { U: MathCollection T: MathCollection } export interface FractionDefinition { a: number b: number } export interface MathJsInstance extends MathJsFactory { e: number pi: number i: number Infinity: number LN2: number LN10: number LOG2E: number LOG10E: number NaN: number phi: number SQRT1_2: number SQRT2: number tau: number // Class-like constructors Node: NodeCtor AccessorNode: AccessorNodeCtor ArrayNode: ArrayNodeCtor AssignmentNode: AssignmentNodeCtor BlockNode: BlockNodeCtor ConditionalNode: ConditionalNodeCtor ConstantNode: ConstantNodeCtor FunctionAssignmentNode: FunctionAssignmentNodeCtor FunctionNode: FunctionNodeCtor IndexNode: IndexNodeCtor ObjectNode: ObjectNodeCtor OperatorNode: OperatorNodeCtor ParenthesisNode: ParenthesisNodeCtor RangeNode: RangeNodeCtor RelationalNode: RelationalNodeCtor SymbolNode: SymbolNodeCtor Unit: UnitCtor Matrix: MatrixCtor /** * If null were to be included in this interface, it would be * auto-suggested as an import in VSCode. This causes issues because * `null` is not a valid label. * * @see https://github.com/josdejong/mathjs/issues/2019 */ // null: number; // eslint-disable-next-line @typescript-eslint/no-explicit-any uninitialized: any version: string expression: MathNode /** * Returns reviver function that can be used as reviver in JSON.parse function. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any reviver(): (key: any, value: any) => any /** * Returns replacer function that can be used as replacer in JSON.stringify function. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any replacer(): (key: any, value: any) => any /************************************************************************* * Core functions ************************************************************************/ /** * Set configuration options for math.js, and get current options. Will * emit a ‘config’ event, with arguments (curr, prev, changes). * @param 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’, 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. * @returns Returns the current configuration */ config: (options: ConfigOptions) => ConfigOptions /** * 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. * @param name Optional name for the typed-function * @param signatures Object with one or multiple function signatures * @returns The created typed-function. */ typed: ( name: string, // eslint-disable-next-line @typescript-eslint/no-explicit-any signatures: Record<string, (...args: any[]) => any> // eslint-disable-next-line @typescript-eslint/no-explicit-any ) => (...args: any[]) => any /************************************************************************* * Construction functions ************************************************************************/ /** * Create a BigNumber, which can store numbers with arbitrary precision. * When a matrix is provided, all elements will be converted to * BigNumber. * @param x Value for the big number, 0 by default. * @returns The created bignumber */ bignumber( x?: number | string | Fraction | BigNumber | bigint | Unit | boolean | null ): BigNumber bignumber<T extends MathCollection>(x: T): T /** * Create a bigint, which can store integers with arbitrary precision. * When a matrix is provided, all elements will be converted to * bigint. * @param x Value for the integer, 0 by default. * @returns The created bigint */ bigint( x?: number | string | Fraction | BigNumber | bigint | boolean | null ): bigint bigint<T extends MathCollection>(x: T): T /** * 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. * @param x A value of any type * @returns The boolean value */ boolean(x: string | number | boolean | null): boolean boolean(x: MathCollection): MathCollection /** * 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. * @param value A value of any type on which to start a chained * operation. * @returns The created chain */ // eslint-disable-next-line @typescript-eslint/no-explicit-any chain<TValue>(value?: TValue): MathJsChain<TValue> /** * Create a complex value or convert a value to a complex value. * @param args Arguments specifying the real and imaginary part of the * complex number * @returns Returns a complex value */ complex(arg?: MathNumericType | string | PolarCoordinates): Complex complex(arg?: MathCollection): MathCollection /** * @param re Argument specifying the real part of the complex number * @param im Argument specifying the imaginary part of the complex * number * @returns Returns a complex value */ complex(re: number, im: number): Complex /** * Create a user-defined unit and register it with the Unit type. * @param name The name of the new unit. Must be unique. Example: ‘knot’ * @param definition Definition of the unit in terms of existing units. * For example, ‘0.514444444 m / s’. * @param options (optional) An object containing any of the following * properties:</br>- prefixes {string} “none”, “short”, “long”, * “binary_short”, or “binary_long”. The default is “none”.</br>- * aliases {Array} Array of strings. Example: [‘knots’, ‘kt’, * ‘kts’]</br>- offset {Numeric} An offset to apply when converting from * the unit. For example, the offset for celsius is 273.15. Default is * 0. * @returns The new unit */ createUnit( name: string, definition?: string | UnitDefinition | Unit, options?: CreateUnitOptions ): Unit /** * Create a user-defined unit and register it with the Unit type. * @param units Definition of the unit * @param options * @returns The new unit */ createUnit( units: Record<string, string | UnitDefinition | Unit>, options?: CreateUnitOptions ): Unit /** * Create a fraction convert a value to a fraction. * @param value Arguments specifying the numerator and denominator of the * fraction * @returns Returns a fraction */ fraction( value: | number | string | BigNumber | bigint | Unit | Fraction | FractionDefinition ): Fraction fraction(values: MathCollection): MathCollection /** * @param numerator Argument specifying the numerator of the fraction * @param denominator Argument specifying the denominator of the * fraction * @returns Returns a fraction */ fraction(numerator: bigint, denominator: bigint): Fraction fraction(numerator: number, denominator: number): Fraction /** * 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. * @param ranges Zero or more ranges or numbers. * @returns Returns the created index */ // eslint-disable-next-line @typescript-eslint/no-explicit-any index(...ranges: any[]): Index /** * Create a Matrix. The function creates a new math.type.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'. * @param format The Matrix storage format * @returns The created Matrix */ matrix(format?: MatrixStorageFormat): Matrix /** * @param data A multi dimensional array * @param format The Matrix storage format * @param dataType The Matrix data type * @returns The created Matrix */ matrix( data: MathCollection | string[], format?: MatrixStorageFormat, dataType?: string ): Matrix matrix<T extends MathScalarType>( data: MathCollection<T>, format?: MatrixStorageFormat, dataType?: string ): Matrix<T> /** * 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. * @param value Value to be converted * @returns The created number */ number( value?: | string | number | BigNumber | bigint | Fraction | boolean | Unit | null ): number number(value?: MathCollection): number | MathCollection /** * @param value Value to be converted * @param valuelessUnit A valueless unit, used to convert a unit to a * number * @returns The created number */ number(unit: Unit, valuelessUnit: Unit | string): number /** * Convert a numeric input to a specific numeric type: number, BigNumber, bigint, or Fraction. * @param value The value to be converted * @param outputType The desired numeric output type */ numeric( value: string | number | BigNumber | bigint | Fraction, outputType: 'number' ): number numeric( value: string | number | BigNumber | bigint | Fraction, outputType: 'BigNumber' ): BigNumber numeric( value: string | number | BigNumber | bigint | Fraction, outputType: 'bigint' ): bigint numeric( value: string | number | BigNumber | bigint | Fraction, outputType: 'Fraction' ): Fraction /** * Create a Sparse Matrix. The function creates a new math.type.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. * @param data A two dimensional array * @param dataType Sparse Matrix data type * @returns The created matrix */ sparse(data?: MathCollection, dataType?: string): Matrix /** * Split a unit in an array of units whose sum is equal to the original * unit. * @param unit A unit to be split * @param parts An array of strings or valueless units * @returns An array of units */ splitUnit(unit: Unit, parts: Unit[]): Unit[] /** * Create a string or convert any object into a string. Elements of * Arrays and Matrices are processed element wise. * @param value A value to convert to a string * @returns The created string */ string(value: MathNumericType | string | Unit | null): string string(value: MathCollection): MathCollection /** * Create a unit. Depending on the passed arguments, the function will * create and return a new math.type.Unit object. When a matrix is * provided, all elements will be converted to units. * @param unit The unit to be created * @returns The created unit */ unit(unit: string): Unit /** * @param unit The unit to be created * @returns The created unit */ unit(unit: Unit): Unit /** * @param value The value of the unit to be created * @param unit The unit to be created * @returns The created unit */ unit(value: MathNumericType, unit: string): Unit unit(value: MathCollection, unit: string): Unit[] /************************************************************************* * Expression functions ************************************************************************/ /** * Parse and compile an expression. Returns a an object with a function * evaluate([scope]) to evaluate the compiled expression. * @param expr The expression to be compiled * @returns An object with the compiled expression */ compile(expr: MathExpression): EvalFunction /** * @param exprs The expressions to be compiled * @returns An array of objects with the compiled expressions */ compile(exprs: MathExpression[]): EvalFunction[] // TODO properly type this /** * Evaluate an expression. * @param expr The expression to be evaluated * @param scope Scope to read/write variables * @returns The result of the expression */ evaluate( expr: MathExpression | Matrix, scope?: object // eslint-disable-next-line @typescript-eslint/no-explicit-any ): any evaluate( expr: MathExpression[], scope?: object // eslint-disable-next-line @typescript-eslint/no-explicit-any ): any[] /** * Retrieve help on a function or data type. Help files are retrieved * from the documentation in math.expression.docs. * @param search A function or function name for which to get help * @returns A help object */ // eslint-disable-next-line @typescript-eslint/no-explicit-any help(search: () => any): Help /** * Parse an expression. Returns a node tree, which can be evaluated by * invoking node.evaluate(); */ parse: ParseFunction /** * Create a parser. The function creates a new math.expression.Parser * object. * @returns A Parser object */ parser(): Parser /************************************************************************* * Algebra functions ************************************************************************/ /** * @param expr The expression to differentiate * @param variable The variable over which to differentiate * @param options There is one option available, simplify, which is true * by default. When false, output will not be simplified. * @returns The derivative of expr */ derivative( expr: MathNode | string, variable: MathNode | string, options?: { simplify: boolean } ): MathNode /** * Solves the linear equation system by forwards substitution. Matrix * must be a lower triangular matrix. * @param L A N x N matrix or array (L) * @param b A column vector with the b values * @returns A column vector with the linear system solution (x) */ lsolve(L: Matrix, b: MathCollection): Matrix lsolve(L: MathArray, b: MathCollection): MathArray /** * 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 * @param A A two dimensional matrix or array for which to get the LUP * decomposition. * @returns The lower triangular matrix, the upper triangular matrix and * the permutation matrix. */ lup(A?: MathCollection): LUDecomposition /** * Solves the linear system A * x = b where A is an [n x n] matrix and b * is a [n] column vector. * @param A Invertible Matrix or the Matrix LU decomposition * @param b Column Vector * @param order The Symbolic Ordering and Analysis order, see slu for * details. Matrix must be a SparseMatrix * @param threshold Partial pivoting threshold (1 for partial pivoting), * see slu for details. Matrix must be a SparseMatrix. * @returns Column vector with the solution to the linear system A * x = * b */ lusolve( A: Matrix, b: MathCollection, order?: number, threshold?: number ): Matrix lusolve( A: MathArray, b: MathCollection, order?: number, threshold?: number ): MathArray lusolve(A: LUDecomposition, b: MathCollection): Matrix /* Finds the roots of a polynomial of degree three or less. Coefficients are given constant first * followed by linear and higher powers in order; coefficients beyond the degree of the polynomial * need not be specified. * @param {number|Complex} constantCoeff * @param {number|Complex} linearCoeff * @param {number|Complex} quadraticCoeff * @param {number|Complex} cubicCoeff * @returns {Array<number|Complex>} array of roots of specified polynomial */ polynomialRoot( constantCoeff: number | Complex, linearCoeff: number | Complex, quadraticCoeff?: number | Complex, cubicCoeff?: number | Complex ): (number | Complex)[] /** * 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. * @param A A two dimensional matrix or array for which to get the QR * decomposition. * @returns Q: the orthogonal matrix and R: the upper triangular matrix */ qr(A: MathCollection): QRDecomposition rationalize( expr: MathNode | string, optional?: object | boolean, detailed?: false ): MathNode /** * 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. * @param expr The expression to check if is a polynomial expression * @param optional scope of expression or true for already evaluated * rational expression at input * @param detailed optional True if return an object, false if return * expression node (default) * @returns The rational polynomial of expr */ rationalize( expr: MathNode | string, optional?: object | boolean, detailed?: true ): { expression: MathNode | string variables: string[] coefficients: MathType[] } /** * Simplify an expression tree. * @param expr The expression to be simplified * @param [rules] (optional) 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. * @param [scope] (optional) Scope to variables * @param [options] (optional) An object with simplify options * @returns Returns the simplified form of expr */ simplify: Simplify simplifyConstant(expr: MathNode | string, options?: SimplifyOptions): MathNode simplifyCore(expr: MathNode | string, options?: SimplifyOptions): MathNode /** * 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. */ leafCount(expr: MathNode): number /** * Replaces variable nodes with their scoped values * @param node Tree to replace variable nodes in * @param scope Scope to read/write variables */ // eslint-disable-next-line @typescript-eslint/no-explicit-any resolve(node: MathNode | string, scope?: Record<string, any>): MathNode resolve( node: (MathNode | string)[], // eslint-disable-next-line @typescript-eslint/no-explicit-any scope?: Record<string, any> ): MathNode[] // eslint-disable-next-line @typescript-eslint/no-explicit-any resolve(node: Matrix, scope?: Record<string, any>): Matrix /** * 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 * @param A A two dimensional sparse matrix for which to get the LU * decomposition. * @param 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 analysis is performed on M = A' * A. Dense * columns from A' are dropped, A recreated from A'. This is appropriate * for LU factorization of non-symmetric matrices. 3 - Symbolic ordering * and analysis 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 threshold Partial pivoting threshold (1 for partial pivoting) * @returns The lower triangular matrix, the upper triangular matrix and * the permutation vectors. */ slu(A: Matrix, order: number, threshold: number): SLUDecomposition /** * Solves the linear equation system by backward substitution. Matrix * must be an upper triangular matrix. U * x = b * @param U A N x N matrix or array (U) * @param b A column vector with the b values * @returns A column vector with the linear system solution (x) */ usolve(U: Matrix, b: MathCollection): Matrix usolve(U: MathArray, b: MathCollection): MathArray /************************************************************************* * Arithmetic functions ************************************************************************/ /** * Calculate the absolute value of a number. For matrices, the function * is evaluated element wise. * @param x A number or matrix for which to get the absolute value * @returns Absolute value of x */ abs<T extends MathType>(x: T): T /** * Add two values, x + y. For matrices, the function is evaluated * element wise. * @param x First value to add * @param y Second value to add * @returns Sum of x and y */ add<T extends MathType>(x: T, y: T): T add<T extends MathType>(...values: T[]): T add(x: MathType, y: MathType): MathType add(...values: MathType[]): MathType /** * Calculate the cubic root of a value. * @param x Value for which to calculate the cubic root. * @param 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. * @returns Returns the cubic root of x */ cbrt(x: Complex, allRoots?: boolean): Complex cbrt<T extends number | BigNumber | Unit>(x: T): T // Rounding functions, grouped for similarity, even though it breaks // the alphabetic order among arithmetic functions. /** * 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. * @param x Number to be rounded * @param n Number of decimals Default value: 0. * @returns Rounded value */ ceil<T extends MathNumericType | MathCollection>( x: T, n?: number | BigNumber ): NoLiteralType<T> ceil<U extends MathCollection>(x: MathNumericType, n: U): U ceil<U extends MathCollection<Unit>>(x: U, unit: Unit): U ceil(x: Unit, unit: Unit): Unit ceil(x: Unit, n: number | BigNumber, unit: Unit): Unit ceil<U extends MathCollection<Unit>>( x: U, n: number | BigNumber, unit: Unit ): U /** * Round a value towards zero. For matrices, the function is evaluated * element wise. * @param x Number to be rounded * @param n Number of decimals Default value: 0. * @returns Rounded value */ fix<T extends MathNumericType | MathCollection>( x: T, n?: number | BigNumber ): NoLiteralType<T> fix<U extends MathCollection>(x: MathNumericType, n: U): U fix<U extends MathCollection<Unit>>(x: U, unit: Unit): U fix(x: Unit, unit: Unit): Unit fix(x: Unit, n: number | BigNumber, unit: Unit): Unit fix<U extends MathCollection<Unit>>( x: U, n: number | BigNumber, unit: Unit ): U /** * Round a value towards minus infinity. For matrices, the function is * evaluated element wise. * @param x Number to be rounded * @param n Number of decimals Default value: 0. * @returns Rounded value */ floor<T extends MathNumericType | MathCollection>( x: T, n?: number | BigNumber ): NoLiteralType<T> floor<U extends MathCollection>(x: MathNumericType, n: U): U floor<U extends MathCollection<Unit>>(x: U, unit: Unit): U floor(x: Unit, unit: Unit): Unit floor(x: Unit, n: number | BigNumber, unit: Unit): Unit floor<U extends MathCollection<Unit>>( x: U, n: number | BigNumber, unit: Unit ): U /** * Round a value towards the nearest integer. For matrices, the function * is evaluated element wise. * @param x Number to be rounded * @param n Number of decimals Default value: 0. * @returns Rounded value of x */ round<T extends MathNumericType | MathCollection>( x: T, n?: number | BigNumber ): NoLiteralType<T> round<U extends MathCollection>(x: MathNumericType, n: U): U round<U extends MathCollection<Unit>>(x: U, unit: Unit): U round(x: Unit, unit: Unit): Unit round(x: Unit, n: number | BigNumber, unit: Unit): Unit round<U extends MathCollection<Unit>>( x: U, n: number | BigNumber, unit: Unit ): U // End of group of rounding functions /** * Compute the cube of a value, x * x * x. For matrices, the function is * evaluated element wise. * @param x Number for which to calculate the cube * @returns Cube of x */ cube<T extends MathNumericType | Unit>(x: T): T /** * Divide two values, x / y. To divide matrices, x is multiplied with * the inverse of y: x * inv(y). * @param x Numerator * @param y Denominator * @returns Quotient, x / y */ divide(x: Unit, y: Unit): Unit | number divide(x: Unit, y: number): Unit divide(x: number, y: number): number divide(x: MathType, y: MathType): MathType /** * Divide two matrices element wise. The function accepts both matrices * and scalar values. * @param x Numerator * @param y Denominator * @returns Quotient, x ./ y */ dotDivide<T extends MathCollection>(x: T, y: MathType): T dotDivide<T extends MathCollection>(x: MathType, y: T): T dotDivide(x: Unit, y: MathType): Unit dotDivide(x: MathType, y: Unit): Unit dotDivide(x: MathNumericType, y: MathNumericType): MathNumericType /** * Multiply two matrices element wise. The function accepts both * matrices and scalar values. * @param x Left hand value * @param y Right hand value * @returns Multiplication of x and y */ dotMultiply<T extends MathCollection>(x: T, y: MathType): T dotMultiply<T extends MathCollection>(x: MathType, y: T): T dotMultiply(x: Unit, y: MathType): Unit dotMultiply(x: MathType, y: Unit): Unit dotMultiply(x: MathNumericType, y: MathNumericType): MathNumericType /** * Calculates the power of x to y element wise. * @param x The base * @param y The exponent * @returns The value of x to the power y */ dotPow<T extends MathType>(x: T, y: MathType): T /** * Calculate the exponent of a value. For matrices, the function is * evaluated element wise. * @param x A number or matrix to exponentiate * @returns Exponent of x */ exp<T extends number | BigNumber | Complex>(x: T): T /** * Calculate the value of subtracting 1 from the exponential value. For * matrices, the function is evaluated element wise. * @param x A number or matrix to apply expm1 * @returns Exponent of x */ expm1<T extends number | BigNumber | Complex>(x: T): T /** * Calculate the greatest common divisor for two or more values or * arrays. For matrices, the function is evaluated element wise. * @param args Two or more integer numbers * @returns The greatest common divisor */ gcd<T extends number | BigNumber | Fraction | MathCollection>(...args: T[]): T gcd<T extends number | BigNumber | Fraction | Matrix>(args: T[]): T /** * Calculate the hypotenuse of a list with values. The hypotenuse is * defined as: hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...) For * matrix input, the hypotenuse is calculated for all values in the * matrix. * @param 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. * @returns Returns the hypothenuse of the input values. */ hypot<T extends number | BigNumber>(...args: T[]): T hypot<T extends number | BigNumber>(args: T[]): T /** * Create a dense matrix from vectors as individual rows. If you pass column vectors, they will be transposed (but not conjugated!) * @param rows - a multi-dimensional number array or matrix */ matrixFromRows(...rows: Matrix[]): Matrix matrixFromRows<T extends MathScalarType>( ...rows: (T[] | [T][] | Matrix)[] ): T[][] /** * Create a dense matrix from vectors as individual columns. If you pass row vectors, they will be transposed (but not conjugated!) * @param cols - a multi-dimensional number array or matrix */ matrixFromColumns(...cols: Matrix[]): Matrix matrixFromColumns<T extends MathScalarType>( ...cols: (T[] | [T][] | Matrix)[] ): T[][] /** * 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. * @param size - the size of the matrix to be created * @param fn - Callback function invoked for every entry in the matrix * @param format - The Matrix storage format, either 'dense' or 'sparse' * @param datatype - Type of the values */ matrixFromFunction<T extends MathScalarType>( size: [number], fn: MatrixFromFunctionCallback<T> ): T[] matrixFromFunction<T extends MathScalarType>( size: [number, number], fn: MatrixFromFunctionCallback<T> ): T[][] matrixFromFunction<T extends MathScalarType>( size: number[], fn: MatrixFromFunctionCallback<T> ): MathArray<T> matrixFromFunction( size: Matrix<number>, fn: MatrixFromFunctionCallback<MathScalarType> ): Matrix matrixFromFunction( size: number[] | Matrix<number>, fn: MatrixFromFunctionCallback<MathScalarType>, format: MatrixStorageFormat, datatype?: string ): Matrix matrixFromFunction( size: number[] | Matrix<number>, format: MatrixStorageFormat, fn: MatrixFromFunctionCallback<MathScalarType>, datatype?: string ): Matrix /** * 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. * @param a An integer number * @param b An integer number * @returns The least common multiple */ lcm<T extends number | BigNumber | MathCollection>(a: T, b: T): T /** * Calculate the logarithm of a value. * @param x Value for which to calculate the logarithm. * @param base Optional base for the logarithm. If not provided, the * natural logarithm of x is calculated. Default value: e. * @returns Returns the logarithm of x */ log<T extends number | BigNumber | Complex>( x: T, base?: number | BigNumber | Complex ): NoLiteralType<T> /** * Calculate the 10-base of a value. This is the same as calculating * log(x, 10). For matrices, the function is evaluated element wise. * @param x Value for which to calculate the logarithm. * @returns Returns the 10-base logarithm of x */ log10<T extends number | BigNumber | Complex | MathCollection>(x: T): T /** * Calculate the logarithm of a value+1. For matrices, the function is * evaluated element wise. * @param x Value for which to calculate the logarithm. * @returns Returns the logarithm of x+1 */ log1p<T extends number | BigNumber | Complex | MathCollection>( x: T, base?: number | BigNumber | Complex ): T /** * Calculate the 2-base of a value. This is the same as calculating * log(x, 2). For matrices, the function is evaluated element wise. * @param x Value for which to calculate the logarithm. * @returns Returns the 2-base logarithm of x */ log2<T extends number | BigNumber | Complex | MathCollection>(x: T): T /** * 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 http://en.wikipedia.org/wiki/Modulo_operation. * @param x Dividend * @param y Divisor * @returns Returns the remainder of x divided by y */ mod<T extends number | BigNumber | bigint | Fraction | MathCollection>( x: T, y: number | BigNumber | bigint | Fraction | MathCollection ): NoLiteralType<T> /** * Multiply two values, x * y. The result is squeezed. For matrices, the * matrix product is calculated. * @param x The first value to multiply * @param y The second value to multiply * @returns Multiplication of x and y */ multiply<T extends Matrix>(x: T, y: MathType): Matrix multiply<T extends Matrix>(x: MathType, y: T): Matrix multiply<T extends MathArray>(x: T, y: T[]): T multiply<T extends MathArray>(x: T[], y: T): T multiply<T extends MathArray>(x: T[], y: T[]): T[] multiply<T extends MathArray>(x: T, y: T): MathScalarType multiply(x: Unit, y: Unit): Unit multiply(x: number, y: number): number multiply(x: MathType, y: MathType): MathType multiply<T extends MathType>(...values: T[]): T multiply(...values: MathType[]): MathType /** * Calculate the norm of a number, vector or matrix. The second * parameter p is optional. If not provided, it defaults to 2. * @param x Value for which to calculate the norm * @param p Vector space. Supported numbers include Infinity and * -Infinity. Supported strings are: 'inf', '-inf', and 'fro' (The * Frobenius norm) Default value: 2. * @returns the p-norm */ norm( x: number | BigNumber | Complex | MathCollection, p?: number | BigNumber | string ): number | BigNumber /** * 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. * @param a Value for which to calculate the nth root * @param root The root. Default value: 2. * @return The nth root of a */ nthRoot( a: number | BigNumber | MathCollection | Complex, root?: number | BigNumber ): number | Complex | MathCollection /** * Calculates the power of x to y, x ^ y. Matrix exponentiation is * supported for square matrices x, and positive integer exponents y. * @param x The base * @param y The exponent * @returns x to the power y */ pow(x: MathType, y: number | BigNumber | bigint | Complex): MathType /** * Compute the sign of a value. The sign of a value x is: 1 when x > 1 * -1 when x < 0 0 when x == 0 For matrices, the function is evaluated * element wise. * @param x The number for which to determine the sign * @returns The sign of x */ sign<T extends MathType>(x: T): T /** * Calculate the square root of a value. For matrices, use either * sqrtm for the matrix square root, or map(M, sqrt) to take the * square root element wise. * @param x Value for which to calculate the square root * @returns Returns the square root of x */ sqrt(x: number): number | Complex sqrt<T extends BigNumber | Complex | Unit>(x: T): T /** * Compute the square of a value, x * x. * @param x Number for which to calculate the square * @returns Squared value */ square<T extends MathNumericType | Unit>(x: T): T /** * Subtract two values, x - y. For matrices, the function is evaluated * element wise. * @param x Initial value * @param y Value to subtract from x * @returns Subtraction of x and y */ subtract<T extends MathType>(x: T, y: T): T subtract(x: MathType, y: MathType): MathType /** * 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. * @param x Number to be inverted * @returns Retursn the value with inverted sign */ unaryMinus<T extends MathType>(x: T): T /** * Unary plus operation. Boolean values