CtrlK
BlogDocsLog inGet started
Tessl Logo

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.

84

1.47x
Overview
Eval results
Files

arithmetic.mddocs/

Arithmetic Operations

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

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'

Basic Arithmetic Operations

Addition

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 cm

Subtraction

Subtracts 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]]

Multiplication

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^2

Division

Divides 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]]

Unary Operations

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)

Power and Root Operations

Exponentiation

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 matrix

Square Root

Calculates 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]

Cube Root

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)

Nth Root

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) // -2

Square and Cube

Convenience 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]

Exponential and Logarithmic Functions

Exponential Functions

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) - 1

Logarithmic Functions

log(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)

Rounding Functions

All rounding functions support precision parameter and units.

Ceiling

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 mm

Floor

Rounds 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.14

Round

Rounds 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 cm

Fix

Rounds 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.14

Element-wise Matrix Operations

For element-wise operations on matrices (as opposed to matrix algebra operations).

Element-wise Division

dotDivide(x: MathCollection, y: MathCollection): MathCollection

{ .api }

dotDivide([[6, 8], [10, 12]], [[2, 4], [5, 3]]) 
// [[3, 2], [2, 4]]

Element-wise Multiplication

dotMultiply(x: MathCollection, y: MathCollection): MathCollection

{ .api }

dotMultiply([[1, 2], [3, 4]], [[5, 6], [7, 8]]) 
// [[5, 12], [21, 32]]

Element-wise Power

dotPow(x: MathCollection, y: MathCollection): MathCollection

{ .api }

dotPow([[2, 3], [4, 5]], [[2, 2], [3, 2]]) 
// [[4, 9], [64, 25]]

Advanced Arithmetic Functions

Absolute Value

abs(x: MathType): MathType

{ .api }

abs(-5) // 5
abs(complex(3, 4)) // 5 (magnitude)
abs([[-2, 3], [-4, 5]]) // [[2, 3], [4, 5]]

Sign Function

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)

Modulo Operation

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)

Greatest Common Divisor

gcd(...args: MathType[]): MathType

{ .api }

gcd(12, 8) // 4
gcd(12, 8, 4) // 4
gcd([12, 8, 16]) // 4

Least Common Multiple

lcm(x: MathType, y: MathType): MathType

{ .api }

lcm(12, 8) // 24
lcm(fraction(1, 3), fraction(1, 4)) // Fraction(1, 12)

Extended GCD

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) = 4

Hypotenuse

Calculates 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]) // 5

Vector/Matrix Norm

norm(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)

Type Conversion and Validation

Numeric Type Conversion

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)

Error Handling

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
}

Performance Tips

Use Appropriate Data Types

  • Use number for general calculations (fastest)
  • Use BigNumber only when precision is critical
  • Use typed arrays for large datasets

Avoid Unnecessary Conversions

// 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 vs Matrix Operations

// Element-wise (faster for simple operations)
dotMultiply(A, B)

// Matrix multiplication (mathematical operation)
multiply(A, B)

Signal Processing Functions

Math.js includes functions for digital signal processing and transform operations.

Fast Fourier Transform

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)

Frequency Response and Transfer Functions

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)

Bitwise Operations

For integer bitwise operations (primarily for number and bigint types).

Bitwise Logical Operations

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)

Bit Shift Operations

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)

Special Mathematical Functions

Advanced mathematical functions beyond basic arithmetic.

Error Function

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))

Riemann Zeta Function

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)

Geometry Functions

Basic geometric calculations.

Distance Calculation

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)

Line Intersection

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]

Chain Operations

All arithmetic functions are available in the chain interface:

chain(5)
  .add(3)      // 8
  .multiply(2) // 16
  .sqrt()      // 4
  .done()      // 4

Constants Related to Arithmetic

import { 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 Number

Install with Tessl CLI

npx tessl i tessl/npm-mathjs

docs

arithmetic.md

data-types.md

expressions.md

index.md

matrices.md

probability.md

statistics.md

trigonometry.md

units.md

tile.json