or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

arithmetic.mddata-types.mdexpressions.mdindex.mdmatrices.mdprobability.mdstatistics.mdtrigonometry.mdunits.md
tile.json

tessl/npm-mathjs

Math.js is an extensive math library for JavaScript and Node.js featuring a flexible expression parser, symbolic computation, and support for numbers, big numbers, complex numbers, fractions, units, and matrices.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/mathjs@14.6.x

To install, run

npx @tessl/cli install tessl/npm-mathjs@14.6.0

index.mddocs/

Math.js

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 different data types like numbers, big numbers, complex numbers, fractions, units, and matrices.

Package Information

npm install mathjs
  • Package: mathjs
  • Version: 14.6.0+
  • License: Apache-2.0
  • Repository: josdejong/mathjs
  • Documentation: mathjs.org

Core Imports

Math.js supports multiple import patterns depending on your needs:

Full Import (All Functions)

import { create, all } from 'mathjs'
const math = create(all)

// Or with CommonJS
const { create, all } = require('mathjs')
const math = create(all)

Selective Imports (Tree-shakeable)

import { 
  create, 
  addDependencies, 
  subtractDependencies,
  multiplyDependencies,
  evaluateDependencies 
} from 'mathjs'

const math = create({
  addDependencies,
  subtractDependencies, 
  multiplyDependencies,
  evaluateDependencies
})

Direct Function Imports

import { add, subtract, multiply, divide, evaluate, parse } from 'mathjs'

// Use functions directly
const result = add(2, 3) // 5

Number-Only Build (Smaller Bundle)

import { create, all } from 'mathjs/number'
const math = create(all)

Basic Usage

Simple Calculations

import { evaluate, add, multiply, sqrt } from 'mathjs'

// Expression evaluation
evaluate('sqrt(3^2 + 4^2)') // 5

// Direct function calls
add(2, 3) // 5
multiply(4, 5) // 20
sqrt(16) // 4

Working with Different Data Types

import { create, all, BigNumber, Complex, Unit, Matrix } from 'mathjs'
const math = create(all)

// BigNumber for high precision
const big = math.bignumber('1.2345678901234567890')

// Complex numbers
const complex = math.complex(2, 3) // 2 + 3i

// Units with automatic conversion  
const distance = math.unit('5 km')
math.to(distance, 'mile') // ~3.1 mile

// Matrices
const matrix = math.matrix([[1, 2], [3, 4]])
math.det(matrix) // -2

Chaining Operations

import { chain } from 'mathjs'

chain(3)
  .add(4)
  .multiply(2)
  .done() // 14

Architecture

Math.js uses a unique factory-based architecture that provides several key benefits:

Factory System

import { create, addDependencies, multiplyDependencies } from 'mathjs'

// Create custom math instance with only needed functions
const math = create({
  addDependencies,
  multiplyDependencies
})

Configuration Options

import { create, all } from 'mathjs'

const math = create(all, {
  number: 'BigNumber',     // Use BigNumber as default number type
  precision: 64,           // Number of significant digits
  epsilon: 1e-60,         // Minimum relative difference
  matrix: 'Matrix',       // Default matrix type
  randomSeed: 'random'    // Random number generator seed
})

Type System

Math.js supports multiple number representations:

  • number: JavaScript's built-in number type
  • BigNumber: Arbitrary precision decimal numbers (via decimal.js)
  • bigint: JavaScript BigInt for large integers
  • Fraction: Exact fraction representation (via fraction.js)
  • Complex: Complex number support with real and imaginary parts

Core Capabilities

Expression Parser and Evaluation

Parse and evaluate mathematical expressions with full JavaScript syntax support.

import { evaluate, parse, compile } from 'mathjs'

// Direct evaluation
evaluate('2 + 3 * 4') // 14
evaluate('sqrt(3^2 + 4^2)') // 5

// Parse to AST then evaluate
const node = parse('2 + 3 * x')
node.evaluate({ x: 4 }) // 14

// Compile for performance
const compiled = compile('a * x^2 + b * x + c')
compiled.evaluate({ a: 1, b: -2, c: 1, x: 3 }) // 4

Key Functions:

  • evaluate(expr: string, scope?: object): any { .api }
  • parse(expr: string, options?: ParseOptions): MathNode { .api }
  • compile(expr: string | MathNode): EvalFunction { .api }

See: Expression Parser Documentation

Arithmetic Operations

Comprehensive set of arithmetic functions supporting all data types.

import { add, subtract, multiply, divide, pow, sqrt } from 'mathjs'

// Basic operations work with any numeric type
add(2, 3) // 5
add('2', '3') // Error: strings not supported directly
add(math.bignumber('2'), math.bignumber('3')) // BigNumber(5)

// Advanced operations  
pow(2, 8) // 256
sqrt(16) // 4

Key Functions:

  • add(x: MathType, y: MathType, ...rest: MathType[]): MathType { .api }
  • subtract(x: MathType, y: MathType): MathType { .api }
  • multiply(x: MathType, y: MathType, ...rest: MathType[]): MathType { .api }
  • divide(x: MathType, y: MathType): MathType { .api }
  • pow(x: MathType, y: MathType): MathType { .api }
  • sqrt(x: MathType): MathType { .api }

See: Arithmetic Operations Documentation

Trigonometric Functions

Complete set of trigonometric, hyperbolic, and inverse functions.

import { sin, cos, tan, asin, sinh, pi } from 'mathjs'

sin(pi / 2) // 1
cos(0) // 1
tan(pi / 4) // 1
asin(0.5) // π/6
sinh(0) // 0

Key Functions:

  • sin(x: MathType): MathType { .api }
  • cos(x: MathType): MathType { .api }
  • tan(x: MathType): MathType { .api }
  • asin(x: MathType): MathType { .api }
  • sinh(x: MathType): MathType { .api }

See: Trigonometry Documentation

Matrix Operations and Linear Algebra

Powerful matrix operations with support for dense and sparse matrices.

import { matrix, multiply, det, inv, eigs } from 'mathjs'

const A = matrix([[1, 2], [3, 4]])
const B = matrix([[5, 6], [7, 8]])

multiply(A, B) // Matrix multiplication
det(A) // -2
inv(A) // Matrix inverse
eigs(A) // Eigenvalues and eigenvectors

Key Functions:

  • matrix(data: MathArray | Matrix, format?: 'dense' | 'sparse', dataType?: string): Matrix { .api }
  • det(x: MathCollection): MathType { .api }
  • inv(x: MathCollection): MathCollection { .api }
  • eigs(x: MathCollection, options?: { precision?: number | BigNumber, eigenvectors?: boolean }): { values: MathCollection, eigenvectors?: Array<{value: MathType, vector: MathCollection}> } { .api }

See: Matrix Operations Documentation

Statistical Functions

Statistical analysis functions for data processing.

import { mean, std, median, max, min } from 'mathjs'

const data = [1, 2, 3, 4, 5]
mean(data) // 3
std(data) // ~1.58
median(data) // 3
max(data) // 5
min(data) // 1

Key Functions:

  • mean(...values: MathType[]): MathType { .api }
  • std(values: MathCollection, normalization?: 'uncorrected' | 'biased' | 'unbiased'): MathType { .api }
  • median(...values: MathType[]): MathType { .api }

See: Statistics Documentation

Probability and Combinatorics

Functions for probability calculations and combinatorial operations.

import { combinations, factorial, gamma, random } from 'mathjs'

combinations(10, 3) // 120
factorial(5) // 120
gamma(0.5) // √π
random() // Random number between 0 and 1

Key Functions:

  • combinations(n: MathType, k: MathType): MathType { .api }
  • factorial(n: MathType): MathType { .api }
  • gamma(n: MathType): MathType { .api }

See: Probability Documentation

Unit System and Conversions

Comprehensive unit system with automatic conversions between compatible units.

import { unit, to, createUnit } from 'mathjs'

// Create units
const distance = unit('5 km')
const time = unit('30 minutes')

// Convert between units
to(distance, 'mile') // ~3.1 mile
to(time, 'hour') // 0.5 hour

// Create custom units
createUnit('byte')
createUnit('kilobyte', '1024 byte')

Key Functions:

  • unit(value?: string | number, unit?: string): Unit { .api }
  • to(value: Unit, unit: string | Unit): Unit { .api }
  • createUnit(name: string, definition?: string | Unit | UnitDefinition, options?: CreateUnitOptions): Unit { .api }

See: Units and Conversions Documentation

Data Types and Type System

Math.js provides rich data type support with automatic type conversion and custom type creation.

import { bignumber, complex, fraction, matrix, string, number } from 'mathjs'

// Type constructors
const big = bignumber('1.23456789012345678901234567890')
const comp = complex(2, 3) // 2 + 3i  
const frac = fraction(1, 3) // 1/3
const mat = matrix([[1, 2], [3, 4]])

// Type conversions
number(frac) // 0.3333...
string(comp) // '2 + 3i'

Key Functions:

  • bignumber(value?: MathType): BigNumber { .api }
  • complex(re: MathType, im?: MathType): Complex { .api }
  • fraction(numerator: MathType, denominator?: MathType): Fraction { .api }
  • number(value?: MathType, valuelessUnit?: Unit | string): number { .api }

See: Data Types Documentation

Constants

Math.js provides mathematical and physical constants:

Mathematical Constants

import { pi, e, i, phi, tau } from 'mathjs'

pi    // π ≈ 3.14159
e     // Euler's number ≈ 2.71828  
i     // Imaginary unit
phi   // Golden ratio ≈ 1.618
tau   // 2π ≈ 6.283

Physical Constants

import { speedOfLight, planckConstant, avogadro } from 'mathjs'

speedOfLight     // Speed of light in vacuum
planckConstant   // Planck constant
avogadro         // Avogadro's number

Type Definitions

Core Types

type MathNumericType = number | BigNumber | bigint | Fraction | Complex
type MathScalarType = MathNumericType | Unit  
type MathArray<T = MathNumericType> = T[] | Array<MathArray<T>>
type MathCollection<T = MathNumericType> = MathArray<T> | Matrix<T>
type MathType = MathScalarType | MathCollection
type MathExpression = string | string[] | MathCollection

Configuration Types

interface ConfigOptions {
  epsilon?: number
  matrix?: 'Matrix' | 'Array'
  number?: 'number' | 'BigNumber' | 'bigint' | 'Fraction'
  precision?: number
  predictable?: boolean
  randomSeed?: string | null
  relTol?: number
  absTol?: number
}

Function Types

type FactoryFunction<T> = (scope: MathScope) => T
type EvalFunction = (scope?: MathScope) => any
type ParseOptions = {
  nodes?: Record<string, MathNode>
}

Error Handling

Math.js provides specific error types for different failure scenarios:

import { 
  ArgumentsError, 
  DimensionError, 
  IndexError 
} from 'mathjs'

try {
  evaluate('1/0') // May throw various errors
} catch (error) {
  if (error instanceof ArgumentsError) {
    // Invalid function arguments
  } else if (error instanceof DimensionError) {
    // Matrix dimension mismatch  
  } else if (error instanceof IndexError) {
    // Invalid array/matrix index
  }
}

Performance Considerations

Tree Shaking

Use selective imports to reduce bundle size:

// Good: Only imports needed functions
import { add, multiply } from 'mathjs'

// Avoid: Imports entire library
import * as math from 'mathjs'

Compilation for Repeated Evaluation

import { compile } from 'mathjs'

// Compile once, evaluate many times
const expr = compile('a * x^2 + b * x + c')
const results = inputs.map(input => expr.evaluate(input))

Number-Only Build

For applications that only need basic number operations:

import { create, all } from 'mathjs/number'
const math = create(all) // Smaller bundle, number-only operations