To use the CortexJS Compute Engine, create a ComputeEngine instance, or if using a mathfield, use the default Compute Engine instance from the MathfieldElement class: ce = MathfieldElement.computeEngine.

Use the instance to create boxed expressions with ce.parse() and ce.box().

const ce = new ComputeEngine();
let expr = ce.parse("e^{i\\pi}");
console.log(expr.N().latex);
// ➔ "-1"

expr = ce.box(["Expand", ["Power", ["Add", "a", "b"], 2]]);
console.log(expr.evaluate().latex);
// ➔ "a^2 + 2ab + b^2"

Implements

Constructors

  • Construct a new ComputeEngine instance.

    Identifier tables define functions and symbols (in options.ids). If no table is provided the MathJSON Standard Library is used (ComputeEngine.getStandardLibrary())

    The LaTeX syntax dictionary is defined in options.latexDictionary.

    The order of the dictionaries matter: the definitions from the later ones override the definitions from earlier ones. The first dictionary should be the 'core' dictionary which include some basic definitions such as domains (Booleans, Numbers, etc...) that are used by later dictionaries.

    Parameters

    • Optionaloptions: {
          ids?: readonly Readonly<{
              [id: string]: IdentifierDefinition;
          }>[];
          numericMode?: NumericMode;
          numericPrecision?: number;
          tolerance?: number;
      }
      • Optionalids?: readonly Readonly<{
            [id: string]: IdentifierDefinition;
        }>[]
      • OptionalnumericMode?: NumericMode

        The default mode is "auto". Use "machine" to perform numeric calculations using 64-bit floats. Use "bignum" to perform calculations using arbitrary precision floating point numbers. Use "auto" or "complex" to allow calculations on complex numbers.

      • OptionalnumericPrecision?: number

        Specific how many digits of precision for the numeric calculations. Default is 100.

      • Optionaltolerance?: number

        If the absolute value of the difference of two numbers is less than tolerance, they are considered equal. Used by chop() as well.

    Returns ComputeEngine

Properties

_bignum: typeof Decimal
_BIGNUM_HALF: Decimal
_BIGNUM_NAN: Decimal
_BIGNUM_NEGATIVE_ONE: Decimal
_BIGNUM_ONE: Decimal
_BIGNUM_PI: Decimal
_BIGNUM_TWO: Decimal
_BIGNUM_ZERO: Decimal
Anything: BoxedDomain
Booleans: BoxedDomain
ComplexInfinity: BoxedExpression
context: null | RuntimeScope

The current scope.

A scope stores the definition of symbols and assumptions.

Scopes form a stack, and definitions in more recent scopes can obscure definitions from older scopes.

The ce.context property represents the current scope.

deadline?: number

Absolute time beyond which evaluation should not proceed.

NegativeInfinity: BoxedExpression
NegativeOne: BoxedExpression
Numbers: BoxedDomain
PositiveInfinity: BoxedExpression
strict: boolean

In strict mode (the default) the Compute Engine performs validation of domains and signature and may report errors.

When strict mode is off, results may be incorrect or generate JavaScript errors if the input is not valid.

Strings: BoxedDomain

Accessors

  • get assumptions(): ExpressionMapInterface<boolean>
  • Returns ExpressionMapInterface<boolean>

  • get costFunction(): ((expr: BoxedExpression) => number)
  • Returns ((expr: BoxedExpression) => number)

  • set costFunction(fn): void
  • Parameters

    Returns void

  • get iterationLimit(): number
  • Experimental

    Returns number

  • get jsonSerializationOptions(): Readonly<JsonSerializationOptions>
  • Options to control the serialization to MathJSON when using BoxedExpression.json.

    Returns Readonly<JsonSerializationOptions>

  • set jsonSerializationOptions(val): void
  • Returns void

  • get numericMode(): NumericMode
  • The numeric evaluation mode:

    Mode
    "auto" Use bignum or complex numbers.
    "machine" IEEE 754-2008, 64-bit floating point numbers: 52-bit mantissa, about 15 digits of precision
    "bignum" Arbitrary precision floating point numbers, as provided by the "decimal.js" library
    "complex" Complex number represented by two machine numbers, a real and an imaginary part, as provided by the "complex.js" library

    Returns NumericMode

  • set numericMode(f): void
  • The numeric evaluation mode:

    Mode
    "auto" Use bignum or complex numbers.
    "machine" IEEE 754-2008, 64-bit floating point numbers: 52-bit mantissa, about 15 digits of precision
    "bignum" Arbitrary precision floating point numbers, as provided by the "decimal.js" library
    "complex" Complex number represented by two machine numbers, a real and an imaginary part, as provided by the "complex.js" library

    Parameters

    Returns void

  • get precision(): number
  • The precision, or number of significant digits, of numeric calculations when the numeric mode is "auto" or "bignum".

    To make calculations using more digits, at the cost of expanded memory usage and slower computations, set the precision higher.

    If the numeric mode is not "auto" or "bignum", it is set to "auto".

    Trigonometric operations are accurate for precision up to 1,000.

    Returns number

  • set precision(p): void
  • Parameters

    • p: number | "machine"

    Returns void

  • get recursionLimit(): number
  • Experimental

    Returns number

  • get timeLimit(): number
  • Experimental

    Returns number

  • get tolerance(): number
  • Values smaller than the tolerance are considered to be zero for the purpose of comparison, i.e. if |b - a| <= tolerance, b is considered equal to a.

    Returns number

  • set tolerance(val): void
  • Parameters

    • val: number

    Returns void

Methods

  • Internal

    Same as assign(), but for internal use:

    • skips validity checks
    • does not auto-declare
    • if assigning to a function, must pass a JS function

    Parameters

    Returns ComputeEngine

  • Internal

    Parameters

    • Optionaloptions: {
          details?: boolean;
          maxDepth?: number;
      }
      • Optionaldetails?: boolean
      • OptionalmaxDepth?: number
    • Optionalscope: null | RuntimeScope
    • Optionaldepth: number

    Returns null | RuntimeScope

  • Internal

    Parameters

    Returns void

  • Internal

    Parameters

    Returns void

  • Shortcut for this.fn("Add"...).

    The result is canonical.

    Parameters

    Returns BoxedExpression

  • Return a list of all the assumptions that match a pattern.

     ce.assume(['Element', 'x', 'PositiveIntegers');
    ce.ask(['Greater', 'x', '_val'])
    // -> [{'val': 0}]

    Parameters

    Returns BoxedSubstitution[]

  • Assign a value to an identifier in the current scope. Use undefined to reset the identifier to no value.

    The identifier should be a valid MathJSON identifier not a LaTeX string.

    The identifier can take the form "f(x, y") to create a function with two parameters, "x" and "y".

    If the id was not previously declared, an automatic declaration is done. The domain of the identifier is inferred from the value. To more precisely define the domain of the identifier, use ce.declare() instead, which allows you to specify the domain, value and other attributes of the identifier.

    Parameters

    Returns ComputeEngine

  • Parameters

    Returns ComputeEngine

  • Add an assumption.

    Note that the assumption is put into canonical form before being added.

    Parameters

    Returns AssumeResult

  • Create an arbitrary precision number.

    The return value is an object with methods to perform arithmetic operations:

    • toNumber(): convert to a JavaScript number with potential loss of precision

    • add()

    • sub()

    • neg() (unary minus)

    • mul()

    • div()

    • pow()

    • sqrt() (square root)

    • cbrt() (cube root)

    • exp() (e^x)

    • log()

    • ln() (natural logarithm)

    • mod()

    • abs()

    • ceil()

    • floor()

    • round()

    • equals()

    • gt()

    • gte()

    • lt()

    • lte()

    • cos()

    • sin()

    • tanh()

    • acos()

    • asin()

    • atan()

    • cosh()

    • sinh()

    • acosh()

    • asinh()

    • atanh()

    • isFinite()

    • isInteger()

    • isNaN()

    • isNegative()

    • isPositive()

    • isZero()

    • sign() (1, 0 or -1)

    Parameters

    Returns Decimal

  • Internal

    Type Parameters

    • T

    Parameters

    • cacheName: string
    • build: (() => T)
        • (): T
        • Returns T

    • purge: ((T: any) => undefined | T)
        • (T): undefined | T
        • Parameters

          • T: any

          Returns undefined | T

    Returns T

  • Internal

    Returns void

  • Replace a number that is close to 0 with the exact integer 0.

    How close to 0 the number has to be to be considered 0 is determined by tolerance.

    Parameters

    • n: number

    Returns number

  • Parameters

    Returns 0 | Decimal

  • Parameters

    Returns 0 | Complex

  • Create a complex number. The return value is an object with methods to perform arithmetic operations:

    • re (real part, as a JavaScript number)

    • im (imaginary part, as a JavaScript number)

    • add()

    • sub()

    • neg() (unary minus)

    • mul()

    • div()

    • pow()

    • sqrt() (square root)

    • exp() (e^x)

    • log()

    • ln() (natural logarithm)

    • mod()

    • abs()

    • ceil()

    • floor()

    • round()

    • arg() the angle of the complex number

    • inverse() the inverse of the complex number 1/z

    • conjugate() the conjugate of the complex number

    • equals()

    • cos()

    • sin()

    • tanh()

    • acos()

    • asin()

    • atan()

    • cosh()

    • sinh()

    • acosh()

    • asinh()

    • atanh()

    • isFinite()

    • isNaN()

    • isZero()

    • sign() (1, 0 or -1)

    Parameters

    Returns Complex

  • Internal

    Associate a new delookupSymbolfinition to a function in the current context.

    If a definition existed previously, it is replaced.

    For internal use. Use ce.declare() instead.

    Parameters

    Returns BoxedFunctionDefinition

  • Internal

    Associate a new definition to a symbol in the current context.

    If a definition existed previously, it is replaced.

    For internal use. Use ce.declare() instead.

    Parameters

    Returns BoxedSymbolDefinition

  • Return a canonical boxed domain.

    If the domain is invalid, may return an ["Error"] expression

    Parameters

    Returns BoxedDomain

  • Return a function expression.

    Note that the result may not be a function, or may have a different head than the one specified.

    For example: ce.fn("Rational", [ce.number(1), ce.number(2)])) ( \to ) ce.number([1,2])

    Parameters

    • head: string
    • ops: BoxedExpression[]
    • Optionaloptions: {
          canonical: boolean;
      }
      • canonical: boolean

    Returns BoxedExpression

  • Remove all assumptions about one or more symbols

    Parameters

    • symbol: undefined | string | string[]

    Returns void

  • Shortcut for this.fn("Divide", [1, expr])

    The result is canonical.

    Parameters

    Returns BoxedExpression

  • Parameters

    • a: unknown

    Returns a is Decimal

  • Parameters

    • a: unknown

    Returns a is Complex

  • Return the definition for a function matching this head.

    Start looking in the current context, than up the scope chain.

    This is a very rough lookup, since it doesn't account for the domain of the argument or the codomain. However, it is useful during parsing to differentiate between symbols that might represent a function application, e.g. f vs x.

    Parameters

    Returns undefined | BoxedFunctionDefinition

  • Return a matching symbol definition, starting with the current scope and going up the scope chain. Prioritize finding a match by wikidata, if provided.

    Parameters

    • symbol: string
    • Optionalwikidata: string
    • Optionalscope: RuntimeScope

    Returns undefined | BoxedSymbolDefinition

  • Shortcut for this.fn("Multiply"...)

    The result is canonical.

    Parameters

    Returns BoxedExpression

  • Shortcut for this.fn("Negate", [expr])

    The result is canonical.

    Parameters

    Returns BoxedExpression

  • This function tries to avoid creating a boxed number if num corresponds to a common value for which we have a shared instance (-1, 0, NaN, etc...)

    Parameters

    • value:
          | string
          | number
          | bigint
          | Decimal
          | Complex
          | MathJsonNumber
          | Rational
    • Optionaloptions: {
          canonical?: boolean;
          metadata?: Metadata;
      }
      • Optionalcanonical?: boolean
      • Optionalmetadata?: Metadata

    Returns BoxedExpression

  • Remove the most recent scope from the scope stack, and set its parent scope as current.

    Returns ComputeEngine

  • Create a new scope and add it to the top of the scope stack

    The scope argument can be used to specify custom precision, etc... for this scope

    Parameters

    Returns ComputeEngine

  • Parameters

    Returns Expression

  • Internal

    After the configuration of the engine has changed, clear the caches so that new values can be recalculated.

    This needs to happen for example when the numeric precision changes.

    Returns void

  • Internal

    Reset the value of any identifiers that have been assigned a value in the current scope.

    Returns void

  • Parameters

    Returns BoxedRuleSet

  • Serialize a BoxedExpression or a MathJSON expression to a LaTeX string

    Parameters

    Returns string

  • Internal

    Return false if the execution should stop.

    This can occur if:

    • an error has been signaled
    • the time limit or memory limit has been exceeded

    Returns boolean

  • Shortcut for this.fn("Sqrt"...)

    The result is canonical.

    Parameters

    Returns any

  • Parameters

    Returns BoxedExpression

  • Set the current scope, return the previous scope.

    Parameters

    Returns null | RuntimeScope

  • Return a boxed symbol

    Parameters

    • name: string
    • Optionaloptions: {
          canonical?: boolean;
          metadata?: Metadata;
      }
      • Optionalcanonical?: boolean
      • Optionalmetadata?: Metadata

    Returns BoxedExpression

  • Shortcut for this.fn("Tuple"...)

    The result is canonical.

    Parameters

    • elements: number[]
    • Optionalmetadata: Metadata

    Returns BoxedExpression

  • Parameters

    Returns BoxedExpression

  • Answer a query based on the current assumptions.

    Parameters

    Returns boolean

  • Parameters

    Returns readonly object[]

  • Return identifier tables suitable for the specified categories, or "all" for all categories ("arithmetic", "algebra", etc...).

    An identifier table defines how the symbols and function names in a MathJSON expression should be interpreted, i.e. how to evaluate and manipulate them.

    Parameters

    Returns readonly Readonly<{
        [id: string]: IdentifierDefinition;
    }>[]