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.
84
This document covers all arithmetic operations available in Math.js, including basic operations, advanced mathematical functions, and element-wise operations for arrays and matrices.
import {
add, subtract, multiply, divide, unaryMinus, unaryPlus,
pow, sqrt, cbrt, nthRoot, square, cube,
exp, expm1, log, log10, log2, log1p,
ceil, floor, round, fix,
abs, sign, mod,
gcd, lcm, xgcd, hypot, norm,
// Signal processing
fft, ifft, freqz, zpk2tf,
// Bitwise operations
bitAnd, bitOr, bitXor, bitNot, leftShift, rightArithShift, rightLogShift,
// Special functions
erf, zeta,
// Geometry
distance, intersect
} from 'mathjs'Adds two or more values. Supports variadic arguments and works with all numeric types.
add(x: MathType, y: MathType, ...rest: MathType[]): MathType{ .api }
// Basic usage
add(2, 3) // 5
add(2, 3, 4) // 9
// With different types
add(bignumber('0.1'), bignumber('0.2')) // BigNumber(0.3)
add(complex(2, 3), complex(1, 1)) // Complex(3, 4) = 3 + 4i
// With matrices
add([[1, 2], [3, 4]], [[5, 6], [7, 8]]) // [[6, 8], [10, 12]]
// With units (must be compatible)
add(unit('5 cm'), unit('3 cm')) // 8 cmSubtracts the second value from the first.
subtract(x: MathType, y: MathType): MathType{ .api }
subtract(5, 2) // 3
subtract(complex(3, 4), complex(1, 1)) // Complex(2, 3) = 2 + 3i
subtract([[5, 6], [7, 8]], [[1, 2], [3, 4]]) // [[4, 4], [4, 4]]Multiplies two or more values. For matrices, performs matrix multiplication.
multiply(x: MathType, y: MathType, ...rest: MathType[]): MathType{ .api }
multiply(3, 4) // 12
multiply(2, 3, 4) // 24
// Matrix multiplication
multiply([[1, 2], [3, 4]], [[5, 6], [7, 8]])
// [[19, 22], [43, 50]]
// Units
multiply(unit('5 m'), unit('3 m')) // 15 m^2Divides the first value by the second.
divide(x: MathType, y: MathType): MathType{ .api }
divide(6, 2) // 3
divide(1, 3) // 0.3333...
divide(bignumber('1'), bignumber('3')) // BigNumber(0.33333...)
// Matrix division (multiplication by inverse)
divide([[4, 2], [6, 4]], [[1, 0], [0, 1]]) // [[4, 2], [6, 4]]unaryMinus(x: MathType): MathType
unaryPlus(x: MathType): MathType{ .api }
unaryMinus(5) // -5
unaryMinus(complex(3, 4)) // Complex(-3, -4) = -3 - 4i
unaryPlus(-5) // -5 (identity operation)
unaryPlus('5') // 5 (type conversion)Raises the first argument to the power of the second.
pow(x: MathType, y: MathType): MathType{ .api }
pow(2, 3) // 8
pow(4, 0.5) // 2 (square root)
pow(complex(2, 0), 3) // Complex(8, 0) = 8 + 0i
// Matrix power
pow([[1, 1], [1, 0]], 10) // 10th Fibonacci matrixCalculates the square root of a value.
sqrt(x: MathType): MathType{ .api }
sqrt(16) // 4
sqrt(-1) // Complex(0, 1) = i
sqrt(bignumber('2')) // BigNumber(1.41421...)
// Element-wise for arrays
sqrt([1, 4, 9, 16]) // [1, 2, 3, 4]Calculates the cube root of a value.
cbrt(x: MathType): MathType{ .api }
cbrt(8) // 2
cbrt(-27) // -3
cbrt(complex(8, 0)) // Complex(2, 0)Calculates the nth root of a value.
nthRoot(x: MathType, n: MathType): MathType{ .api }
nthRoot(16, 4) // 2 (fourth root)
nthRoot(32, 5) // 2 (fifth root)
nthRoot(-8, 3) // -2Convenience functions for common powers.
square(x: MathType): MathType
cube(x: MathType): MathType{ .api }
square(5) // 25
cube(3) // 27
// Element-wise operations
square([1, 2, 3, 4]) // [1, 4, 9, 16]
cube([1, 2, 3]) // [1, 8, 27]exp(x: MathType): MathType
expm1(x: MathType): MathType // exp(x) - 1, more accurate for small x{ .api }
exp(1) // 2.71828... (e)
exp(0) // 1
exp(complex(0, pi)) // Complex(-1, 0) = -1 (Euler's formula)
expm1(1e-10) // More accurate than exp(1e-10) - 1log(x: MathType, base?: MathType): MathType
log10(x: MathType): MathType
log2(x: MathType): MathType
log1p(x: MathType): MathType // log(1 + x), more accurate for small x{ .api }
log(e) // 1 (natural logarithm)
log(100, 10) // 2 (base-10 logarithm)
log2(8) // 3
log10(1000) // 3
log1p(1e-10) // More accurate than log(1 + 1e-10)All rounding functions support precision parameter and units.
Rounds toward positive infinity.
ceil(x: MathType, n?: number, unit?: Unit): MathType{ .api }
ceil(3.2) // 4
ceil(-3.2) // -3
ceil(3.141592, 2) // 3.15 (2 decimal places)
ceil(unit('5.7 cm'), unit('1 mm')) // 57 mmRounds toward negative infinity.
floor(x: MathType, n?: number, unit?: Unit): MathType{ .api }
floor(3.7) // 3
floor(-3.2) // -4
floor(3.141592, 2) // 3.14Rounds to the nearest integer or specified precision.
round(x: MathType, n?: number, unit?: Unit): MathType{ .api }
round(3.7) // 4
round(3.2) // 3
round(3.141592, 3) // 3.142
round(unit('5.67 m'), unit('1 cm')) // 567 cmRounds toward zero (truncates).
fix(x: MathType, n?: number, unit?: Unit): MathType{ .api }
fix(3.7) // 3
fix(-3.7) // -3
fix(3.141592, 2) // 3.14For element-wise operations on matrices (as opposed to matrix algebra operations).
dotDivide(x: MathCollection, y: MathCollection): MathCollection{ .api }
dotDivide([[6, 8], [10, 12]], [[2, 4], [5, 3]])
// [[3, 2], [2, 4]]dotMultiply(x: MathCollection, y: MathCollection): MathCollection{ .api }
dotMultiply([[1, 2], [3, 4]], [[5, 6], [7, 8]])
// [[5, 12], [21, 32]]dotPow(x: MathCollection, y: MathCollection): MathCollection{ .api }
dotPow([[2, 3], [4, 5]], [[2, 2], [3, 2]])
// [[4, 9], [64, 25]]abs(x: MathType): MathType{ .api }
abs(-5) // 5
abs(complex(3, 4)) // 5 (magnitude)
abs([[-2, 3], [-4, 5]]) // [[2, 3], [4, 5]]sign(x: MathType): MathType{ .api }
sign(5) // 1
sign(-3) // -1
sign(0) // 0
sign(complex(3, 4)) // Complex(0.6, 0.8) (unit vector)mod(x: MathType, y: MathType): MathType{ .api }
mod(7, 3) // 1
mod(-7, 3) // 2 (always non-negative result)
mod(bignumber('17'), bignumber('5')) // BigNumber(2)gcd(...args: MathType[]): MathType{ .api }
gcd(12, 8) // 4
gcd(12, 8, 4) // 4
gcd([12, 8, 16]) // 4lcm(x: MathType, y: MathType): MathType{ .api }
lcm(12, 8) // 24
lcm(fraction(1, 3), fraction(1, 4)) // Fraction(1, 12)Returns the extended Euclidean algorithm result.
xgcd(a: MathType, b: MathType): { gcd: MathType, x: MathType, y: MathType }{ .api }
xgcd(12, 8)
// { gcd: 4, x: 1, y: -1 }
// Meaning: 12 * 1 + 8 * (-1) = 4Calculates the hypotenuse (Euclidean norm) of the arguments.
hypot(...args: MathType[]): MathType{ .api }
hypot(3, 4) // 5
hypot(1, 1, 1) // √3 ≈ 1.732
hypot([3, 4]) // 5norm(x: MathCollection, p?: number | 'fro'): MathType{ .api }
norm([3, 4]) // 5 (L2 norm by default)
norm([3, 4], 1) // 7 (L1 norm)
norm([3, 4], Infinity) // 4 (L∞ norm)
// Matrix norms
norm([[1, 2], [3, 4]]) // ~5.477 (Frobenius norm)
norm([[1, 2], [3, 4]], 'fro') // ~5.477 (explicit Frobenius)number(value?: MathType, valuelessUnit?: Unit | string): number{ .api }
number(fraction(1, 3)) // 0.3333...
number(bignumber('5.5')) // 5.5
number(unit('5 cm'), 'mm') // 50 (convert to mm, return number)Arithmetic operations can throw several types of errors:
import { DimensionError, ArgumentsError } from 'mathjs'
try {
add([[1, 2]], [[1, 2, 3]]) // Different matrix dimensions
} catch (error) {
if (error instanceof DimensionError) {
console.log('Matrix dimensions do not match')
}
}
try {
divide(1, 0) // Division by zero
} catch (error) {
// May return Infinity or throw depending on configuration
}number for general calculations (fastest)BigNumber only when precision is critical// Good: Keep same type throughout calculation
const a = bignumber('1.1')
const b = bignumber('2.2')
const result = add(a, b)
// Avoid: Mixed types cause conversions
const mixed = add(1.1, bignumber('2.2'))// Element-wise (faster for simple operations)
dotMultiply(A, B)
// Matrix multiplication (mathematical operation)
multiply(A, B)Math.js includes functions for digital signal processing and transform operations.
fft(arr: MathArray): MathArray
ifft(arr: MathArray): MathArray{ .api }
// FFT and inverse FFT
const signal = [1, 2, 3, 4]
const transformed = fft(signal)
const recovered = ifft(transformed) // Should recover original signal
// Complex signals
const complexSignal = [complex(1, 0), complex(2, 1), complex(1, -1)]
const fftResult = fft(complexSignal)freqz(b: MathArray, a: MathArray, w?: MathArray): { h: MathArray, w: MathArray }
zpk2tf(z: MathArray, p: MathArray, k?: MathType): { b: MathArray, a: MathArray }{ .api }
// Frequency response of a digital filter
const b = [1, 2, 1] // Numerator coefficients
const a = [1, -0.5, 0.25] // Denominator coefficients
const { h, w } = freqz(b, a)
// Zero-pole-gain to transfer function
const zeros = [-1, 1]
const poles = [0.5, -0.5]
const gain = 2
const { b: num, a: den } = zpk2tf(zeros, poles, gain)For integer bitwise operations (primarily for number and bigint types).
bitAnd(x: MathType, y: MathType): MathType
bitOr(x: MathType, y: MathType): MathType
bitXor(x: MathType, y: MathType): MathType
bitNot(x: MathType): MathType{ .api }
bitAnd(5, 3) // 1 (binary: 101 & 011 = 001)
bitOr(5, 3) // 7 (binary: 101 | 011 = 111)
bitXor(5, 3) // 6 (binary: 101 ^ 011 = 110)
bitNot(5) // -6 (two's complement)leftShift(x: MathType, y: MathType): MathType
rightArithShift(x: MathType, y: MathType): MathType
rightLogShift(x: MathType, y: MathType): MathType{ .api }
leftShift(5, 2) // 20 (5 << 2: 101 -> 10100)
rightArithShift(20, 2) // 5 (20 >> 2: arithmetic right shift)
rightLogShift(20, 2) // 5 (20 >>> 2: logical right shift)
// Negative number arithmetic vs logical shift difference
rightArithShift(-8, 2) // -2 (sign bit preserved)
rightLogShift(-8, 2) // Large positive number (zero-fill)Advanced mathematical functions beyond basic arithmetic.
erf(x: MathType): MathType{ .api }
erf(0) // 0
erf(1) // ~0.8427 (error function at 1)
erf(Infinity) // 1
// Complementary error function: erfc(x) = 1 - erf(x)
// Can be computed as: subtract(1, erf(x))zeta(s: MathType): MathType{ .api }
zeta(2) // π²/6 ≈ 1.6449 (Basel problem)
zeta(4) // π⁴/90 ≈ 1.0823
// zeta(1) // Undefined (pole)
zeta(0) // -1/2
zeta(-1) // -1/12 (analytic continuation)Basic geometric calculations.
distance(x: MathArray, y: MathArray): MathType{ .api }
distance([0, 0], [3, 4]) // 5 (Euclidean distance)
distance([1, 2, 3], [4, 6, 8]) // √(9 + 16 + 25) = √50 ≈ 7.07
// Works with any dimension
distance([0], [5]) // 5 (1D distance)intersect(w: MathArray, x: MathArray, y: MathArray, z: MathArray): MathArray{ .api }
// Intersection of two lines in 2D: line through w-x and line through y-z
const p1 = [0, 0]
const p2 = [2, 2]
const p3 = [0, 2]
const p4 = [2, 0]
const intersection = intersect(p1, p2, p3, p4) // [1, 1]All arithmetic functions are available in the chain interface:
chain(5)
.add(3) // 8
.multiply(2) // 16
.sqrt() // 4
.done() // 4import { e, pi, phi, tau, Infinity, NaN } from 'mathjs'
e // Euler's number ≈ 2.71828
pi // π ≈ 3.14159
phi // Golden ratio ≈ 1.618
tau // 2π ≈ 6.283
Infinity // Positive infinity
NaN // Not a NumberInstall with Tessl CLI
npx tessl i tessl/npm-mathjsdocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10