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,453 lines (1,335 loc) 208 kB
import { Decimal } from 'decimal.js' declare const math: math.MathJsStatic export as namespace math export = math type NoLiteralType<T> = T extends number ? number : T extends string ? string : T extends boolean ? boolean : T declare namespace math { type MathNumericType = number | BigNumber | Fraction | Complex type MathArray = MathNumericType[] | MathNumericType[][] type MathCollection = MathArray | Matrix type MathType = MathNumericType | Unit | MathCollection type MathExpression = string | string[] | MathCollection // eslint-disable-next-line @typescript-eslint/no-explicit-any type FactoryFunction<T> = (scope: any) => T // FactoryFunctionMap can be nested; all nested objects will be flattened interface FactoryFunctionMap { // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: FactoryFunction<any> | FactoryFunctionMap } /** Available options for parse */ 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 */ 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 } interface AccessorNode extends MathNodeCommon { type: 'AccessorNode' isAccessorNode: true object: MathNode index: IndexNode name: string } interface AccessorNodeCtor { new (object: MathNode, index: IndexNode): AccessorNode } interface ArrayNode extends MathNodeCommon { type: 'ArrayNode' isArrayNode: true items: MathNode[] } interface ArrayNodeCtor { new (items: MathNode[]): ArrayNode } interface AssignmentNode extends MathNodeCommon { type: 'AssignmentNode' isAssignmentNode: true object: SymbolNode | AccessorNode index: IndexNode | null value: MathNode name: string } interface AssignmentNodeCtor { new (object: SymbolNode, value: MathNode): AssignmentNode new ( object: SymbolNode | AccessorNode, index: IndexNode, value: MathNode ): AssignmentNode } interface BlockNode extends MathNodeCommon { type: 'BlockNode' isBlockNode: true blocks: Array<{ node: MathNode; visible: boolean }> } interface BlockNodeCtor { new ( arr: Array<{ node: MathNode } | { node: MathNode; visible: boolean }> ): BlockNode } interface ConditionalNode extends MathNodeCommon { type: 'ConditionalNode' isConditionalNode: boolean condition: MathNode trueExpr: MathNode falseExpr: MathNode } interface ConditionalNodeCtor { new ( condition: MathNode, trueExpr: MathNode, falseExpr: MathNode ): ConditionalNode } interface ConstantNode extends MathNodeCommon { type: 'ConstantNode' isConstantNode: true // eslint-disable-next-line @typescript-eslint/no-explicit-any value: any } interface ConstantNodeCtor { new (constant: number): ConstantNode } interface FunctionAssignmentNode extends MathNodeCommon { type: 'FunctionAssignmentNode' isFunctionAssignmentNode: true name: string params: string[] expr: MathNode } interface FunctionAssignmentNodeCtor { new (name: string, params: string[], expr: MathNode): FunctionAssignmentNode } interface FunctionNode extends MathNodeCommon { type: 'FunctionNode' isFunctionNode: true fn: SymbolNode args: MathNode[] } interface FunctionNodeCtor { new (fn: MathNode | string, args: MathNode[]): FunctionNode } interface IndexNode extends MathNodeCommon { type: 'IndexNode' isIndexNode: true dimensions: MathNode[] dotNotation: boolean } interface IndexNodeCtor { new (dimensions: MathNode[]): IndexNode new (dimensions: MathNode[], dotNotation: boolean): IndexNode } interface ObjectNode extends MathNodeCommon { type: 'ObjectNode' isObjectNode: true properties: Record<string, MathNode> } interface ObjectNodeCtor { new (properties: Record<string, MathNode>): ObjectNode } interface OperatorNode extends MathNodeCommon { type: 'OperatorNode' isOperatorNode: true op: string fn: string args: MathNode[] implicit: boolean isUnary(): boolean isBinary(): boolean } interface OperatorNodeCtor { new ( op: string, fn: string, args: MathNode[], implicit?: boolean ): OperatorNode } interface ParenthesisNode extends MathNodeCommon { type: 'ParenthesisNode' isParenthesisNode: true content: MathNode } interface ParenthesisNodeCtor { new (content: MathNode): ParenthesisNode } interface RangeNode extends MathNodeCommon { type: 'RangeNode' isRangeNode: true start: MathNode end: MathNode step: MathNode | null } interface RangeNodeCtor { new (start: MathNode, end: MathNode, step?: MathNode): RangeNode } interface RelationalNode extends MathNodeCommon { type: 'RelationalNode' isRelationalNode: true conditionals: string[] params: MathNode[] } interface RelationalNodeCtor { new (conditionals: string[], params: MathNode[]): RelationalNode } interface SymbolNode extends MathNodeCommon { type: 'SymbolNode' isSymbolNode: true name: string } interface SymbolNodeCtor { new (name: string): SymbolNode } type MathNode = | AccessorNode | ArrayNode | AssignmentNode | BlockNode | ConditionalNode | ConstantNode | FunctionAssignmentNode | FunctionNode | IndexNode | ObjectNode | OperatorNode | ParenthesisNode | RangeNode | RelationalNode | SymbolNode type MathJsFunctionName = keyof MathJsStatic interface MathJsStatic extends FactoryDependencies { 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 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 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 /************************************************************************* * 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} epsilon Minimum relative * 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 | boolean | Fraction | null ): BigNumber bignumber<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 | MathCollection | null ): boolean | 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(value?: any): MathJsChain /** * 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?: Complex | 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, 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>, options?: CreateUnitOptions ): Unit /** * Create a fraction convert a value to a fraction. * @param args Arguments specifying the numerator and denominator of the * fraction * @returns Returns a fraction */ fraction(value: number | string | BigNumber | Fraction | object): Fraction fraction(values: MathArray): MathArray fraction(values: Matrix): Matrix /** * @param numerator Argument specifying the numerator of the fraction * @param denominator Argument specifying the denominator of the * fraction * @returns Returns a 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?: 'sparse' | 'dense'): 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, format?: 'sparse' | 'dense', dataType?: string ): Matrix /** * 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 | Fraction | boolean | MathCollection | Unit | null ): 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 /** * 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: MathType | null): string | 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: number | MathCollection | BigNumber, 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[] /** * 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 | MathExpression[] | Matrix, 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 | MathArray, b: Matrix | MathArray): Matrix | 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?: Matrix | MathArray): { L: MathCollection U: MathCollection P: number[] } /** * 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 | MathArray | number, b: Matrix | MathArray, order?: number, threshold?: number ): Matrix | MathArray /** * 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: Matrix | MathArray): { Q: MathCollection; R: MathCollection } 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 /** * 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, scope?: Record<string, any>): MathNode // eslint-disable-next-line @typescript-eslint/no-explicit-any resolve(node: MathNode[], scope?: Record<string, any>): MathNode[] /** * 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): object /** * 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 | MathArray, b: Matrix | MathArray): Matrix | 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(x: number): number abs(x: BigNumber): BigNumber abs(x: Fraction): Fraction abs(x: Complex): Complex abs(x: MathArray): MathArray abs(x: Matrix): Matrix abs(x: Unit): Unit /** * 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(x: MathType, y: MathType): MathType /** * Calculate the cubic root of a value. For matrices, the function is * evaluated element wise. * @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: number, allRoots?: boolean): number cbrt(x: BigNumber, allRoots?: boolean): BigNumber cbrt(x: Fraction, allRoots?: boolean): Fraction cbrt(x: Complex, allRoots?: boolean): Complex cbrt(x: MathArray, allRoots?: boolean): MathArray cbrt(x: Matrix, allRoots?: boolean): Matrix cbrt(x: Unit, allRoots?: boolean): Unit // 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 /** * 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 /** * 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 /** * 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 // 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(x: number): number cube(x: BigNumber): BigNumber cube(x: Fraction): Fraction cube(x: Complex): Complex cube(x: MathArray): MathArray cube(x: Matrix): Matrix cube(x: Unit): Unit /** * 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(x: MathType, y: MathType): MathType /** * 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(x: MathType, y: MathType): MathType /** * 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(x: MathType, y: MathType): MathType /** * 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(x: number): number exp(x: BigNumber): BigNumber exp(x: Complex): Complex exp(x: MathArray): MathArray exp(x: Matrix): Matrix /** * 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(x: number): number expm1(x: BigNumber): BigNumber expm1(x: Complex): Complex expm1(x: MathArray): MathArray expm1(x: Matrix): Matrix /** * 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(...args: number[]): number gcd(...args: BigNumber[]): BigNumber gcd(...args: Fraction[]): Fraction gcd(...args: MathArray[]): MathArray gcd(...args: Matrix[]): Matrix /** * 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. * @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(...args: number[]): number hypot(...args: BigNumber[]): BigNumber /** * 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(a: number, b: number): number lcm(a: BigNumber, b: BigNumber): BigNumber lcm(a: MathArray, b: MathArray): MathArray lcm(a: Matrix, b: Matrix): Matrix /** * Calculate the logarithm of a value. For matrices, the function is * evaluated element wise. * @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 | MathCollection>( 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(x: number): number log10(x: BigNumber): BigNumber log10(x: Complex): Complex log10(x: MathArray): MathArray log10(x: Matrix): Matrix /** * 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(x: number, base?: number | BigNumber | Complex): number log1p(x: BigNumber, base?: number | BigNumber | Complex): BigNumber log1p(x: Complex, base?: number | BigNumber | Complex): Complex log1p(x: MathArray, base?: number | BigNumber | Complex): MathArray log1p(x: Matrix, base?: number | BigNumber | Complex): Matrix /** * 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(x: number): number log2(x: BigNumber): BigNumber log2(x: Complex): Complex log2(x: MathArray): MathArray log2(x: Matrix): Matrix /** * 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 | Fraction | MathCollection>( x: T, y: number | BigNumber | 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 | MathArray>(x: T, y: MathType): T multiply(x: Unit, y: Unit): Unit multiply(x: number, y: number): number multiply(x: MathType, y: 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 | 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(x: number): number sign(x: BigNumber): BigNumber sign(x: Fraction): Fraction sign(x: Complex): Complex sign(x: MathArray): MathArray sign(x: Matrix): Matrix sign(x: Unit): Unit /** * Calculate the square root of a value. For matrices, the function is * evaluated element wise. * @param x Value for which to calculate the square root * @returns Returns the square root of x */ sqrt(x: number): number sqrt(x: BigNumber): BigNumber sqrt(x: Complex): Complex sqrt(x: MathArray): MathArray sqrt(x: Matrix): Matrix sqrt(x: Unit): Unit /** * Compute the square of a value, x * x. For matrices, the function is * evaluated element wise. * @param x Number for which to calculate the square * @returns Squared value */ square(x: number): number square(x: BigNumber): BigNumber square(x: Fraction): Fraction square(x: Complex): Complex square(x: MathArray): MathArray square(x: Matrix): Matrix square(x: Unit): Unit /** * 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(x: number): number unaryMinus(x: BigNumber): BigNumber unaryMinus(x: Fraction): Fraction unaryMinus(x: Complex): Complex unaryMinus(x: MathArray): MathArray unaryMinus(x: Matrix): Matrix unaryMinus(x: Unit): Unit /** * 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. * @param x Input value * @returns Returns the input value when numeric, converts to a number * when input is non-numeric. */ unaryPlus(x: number): number unaryPlus(x: BigNumber): BigNumber unaryPlus(x: Fraction): Fraction unaryPlus(x: string): string unaryPlus(x: Complex): Complex unaryPlus(x: MathArray): MathArray unaryPlus(x: Matrix): Matrix unaryPlus(x: Unit): Unit /** * Calculate the extended greatest common divisor for two values. See * http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm. * @param a An integer number * @param b An integer number * @returns Returns an array containing 3 integers [div, m, n] where div * = gcd(a, b) and a*m + b*n = div */ xgcd(a: number | BigNumber, b: number | BigNumber): MathArray /************************************************************************* * Bitwise functions ************************************************************************/ /** * Bitwise AND two values, x & y. For matrices, the function is * evaluated element wise. * @param x First value to and * @param y Second value to and * @returns AND of x and y */ bitAnd<T extends number | BigNumber | MathCollection>( x: T, y: number | BigNumber | MathCollection ): NoLiteralType<T> /** * Bitwise NOT value, ~x. For matrices, the function is evaluated * element wise. For units, the function is evaluated on the best prefix * base. * @param x Value to not * @returns NOT of x */ bitNot(x: number): number bitNot(x: BigNumber): BigNumber bitNot(x: MathArray): MathArray bitNot(x: Matrix): Matrix /** * 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. * @param x First value to or * @param y Second value to or * @returns OR of x and y */ bitOr(x: number, y: number): number bitOr(x: BigNumber, y: BigNumber): BigNumber bitOr(x: MathArray, y: MathArray): MathArray bitOr(x: Matrix, y: Matrix): Matrix /** * Bitwise XOR two values, x ^ y. For matrices, the function is * evaluated element wise. * @param x First value to xor * @param y Second value to xor * @returns XOR of x and y */ bitXor<T extends number | BigNumber | MathCollection>( x: T, y: number | BigNumber | MathCollection ): NoLiteralType<T> /** * 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. * @param x Value to be shifted * @param y Amount of shifts * @returns x shifted left y times */ leftShift<T extends number | BigNumber | MathCollection>( x: T, y: number | BigNumber ): NoLiteralType<T> /** * 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. * @param x Value to be shifted * @param y Amount of shifts * @returns x sign-filled shifted right y times */ rightArithShift<T extends number | BigNumber | MathCollection>( x: T, y: number | BigNumber ): NoLiteralType<T> /** * 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. * @param x Value to be shifted * @param y Amount of shifts * @returns x zero-filled shifted right y times */ rightLogShift<T extends number | MathCollection>( x: T, y: number ): NoLiteralType<T> /************************************************************************* * Combinatorics functions ************************************************************************/ /** * 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 * @param n Total number of objects in the set * @returns B(n) */ bellNumbers(n: number): number bellNumbers(n: BigNumber): BigNumber /** * The Catalan Numbers enumerate combinatorial structures of many * different types. catalan only takes integer arguments. The following * condition must be enforced: n >= 0 * @param n nth Catalan number * @returns Cn(n) */ catalan(n: number): number catalan(n: BigNumber): BigNumber /** * The composition counts of n into k parts. Composition only takes * integer arguments. The following condition must be enforced: k <= n. * @param n Total number of objects in the set * @param k Number of objects in the subset * @returns Returns the composition counts of n into k parts. */ composition<T extends number | BigNumber>( n: T, k: number | BigNumber ): NoLiteralType<T> /** * 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, then s(n,k) = * 1 * @param n Total number of objects in the set * @param k Number of objects in the subset * @returns S(n,k) */ stirlingS2<T extends number | BigNumber>( n: T, k: number | BigNumber ): NoLiteralType<T> /************************************************************************* * Complex functions ************************************************************************/ /** * 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. * @param x A complex number or array with complex numbers * @returns The argument of x */ arg(x: number | Complex): number arg(x: BigNumber | Complex): BigNumber arg(x: MathArray): MathArray arg(x: Matrix): Matrix /** * 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. * @param x A complex number or array with complex numbers * @returns The complex conjugate of x */ conj<T extends number | BigNumber | Complex | MathCollection>( x: T ): NoLiteralType<T> /** * Get the imaginary