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.
npx @tessl/cli install tessl/npm-mathjs@14.6.0Math.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.
npm install mathjsmathjsMath.js supports multiple import patterns depending on your needs:
import { create, all } from 'mathjs'
const math = create(all)
// Or with CommonJS
const { create, all } = require('mathjs')
const math = create(all)import {
create,
addDependencies,
subtractDependencies,
multiplyDependencies,
evaluateDependencies
} from 'mathjs'
const math = create({
addDependencies,
subtractDependencies,
multiplyDependencies,
evaluateDependencies
})import { add, subtract, multiply, divide, evaluate, parse } from 'mathjs'
// Use functions directly
const result = add(2, 3) // 5import { create, all } from 'mathjs/number'
const math = create(all)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) // 4import { 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) // -2import { chain } from 'mathjs'
chain(3)
.add(4)
.multiply(2)
.done() // 14Math.js uses a unique factory-based architecture that provides several key benefits:
import { create, addDependencies, multiplyDependencies } from 'mathjs'
// Create custom math instance with only needed functions
const math = create({
addDependencies,
multiplyDependencies
})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
})Math.js supports multiple number representations:
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 }) // 4Key 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
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) // 4Key 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
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) // 0Key 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
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 eigenvectorsKey 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 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) // 1Key Functions:
mean(...values: MathType[]): MathType { .api }std(values: MathCollection, normalization?: 'uncorrected' | 'biased' | 'unbiased'): MathType { .api }median(...values: MathType[]): MathType { .api }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 1Key Functions:
combinations(n: MathType, k: MathType): MathType { .api }factorial(n: MathType): MathType { .api }gamma(n: MathType): MathType { .api }See: Probability Documentation
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
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 }Math.js provides mathematical and physical 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.283import { speedOfLight, planckConstant, avogadro } from 'mathjs'
speedOfLight // Speed of light in vacuum
planckConstant // Planck constant
avogadro // Avogadro's numbertype 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[] | MathCollectioninterface ConfigOptions {
epsilon?: number
matrix?: 'Matrix' | 'Array'
number?: 'number' | 'BigNumber' | 'bigint' | 'Fraction'
precision?: number
predictable?: boolean
randomSeed?: string | null
relTol?: number
absTol?: number
}type FactoryFunction<T> = (scope: MathScope) => T
type EvalFunction = (scope?: MathScope) => any
type ParseOptions = {
nodes?: Record<string, MathNode>
}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
}
}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'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))For applications that only need basic number operations:
import { create, all } from 'mathjs/number'
const math = create(all) // Smaller bundle, number-only operations