Logo
⚠️ Unsaved
[M]:

Mathjs Cheatsheet: Quick Reference for Mathematical Functions

This cheatsheet provides a convenient reference for the most commonly used functions in math.js, a comprehensive mathematics library for JavaScript. Whether you're working on scientific computing, data analysis, engineering applications, or simply need to perform mathematical operations beyond what JavaScript natively offers, this reference will help you quickly find the right functions.

[1]:
// Install math.js
!npm install mathjs
$ npm install mathjs

added 9 packages in 3s

30 packages are looking for funding
  run `npm fund` for details
[2]:
// Import the library
const math = require('mathjs');

console.log('Math.js version:', math.version, '\n');
Math.js version: 14.3.1 
[M]:

1. Basic Arithmetic Operations

Quick reference for basic arithmetic operations in math.js.

[3]:
// Basic arithmetic functions
console.log('Basic arithmetic:\n');

console.log(`Addition: math.add(2, 3) = ${math.add(2, 3)}\n`);
console.log(`Subtraction: math.subtract(7, 3) = ${math.subtract(7, 3)}\n`);
console.log(`Multiplication: math.multiply(4, 5) = ${math.multiply(4, 5)}\n`);
console.log(`Division: math.divide(15, 3) = ${math.divide(15, 3)}\n`);
console.log(`Modulo: math.mod(8, 3) = ${math.mod(8, 3)}\n`);
console.log(`Power: math.pow(2, 8) = ${math.pow(2, 8)}\n`);
console.log(`Square root: math.sqrt(16) = ${math.sqrt(16)}\n`);
console.log(`Cube root: math.cbrt(27) = ${math.cbrt(27)}\n`);
console.log(`Absolute value: math.abs(-4.5) = ${math.abs(-4.5)}\n`);
Basic arithmetic:
Addition: math.add(2, 3) = 5
Subtraction: math.subtract(7, 3) = 4
Multiplication: math.multiply(4, 5) = 20
Division: math.divide(15, 3) = 5
Modulo: math.mod(8, 3) = 2
Power: math.pow(2, 8) = 256
Square root: math.sqrt(16) = 4
Cube root: math.cbrt(27) = 3
Absolute value: math.abs(-4.5) = 4.5
[4]:
// Rounding functions
console.log('Rounding functions:\n');

console.log(`Round: math.round(3.7) = ${math.round(3.7)}\n`);
console.log(`Floor: math.floor(3.7) = ${math.floor(3.7)}\n`);
console.log(`Ceiling: math.ceil(3.2) = ${math.ceil(3.2)}\n`);
console.log(`Fix (toward zero): math.fix(-3.7) = ${math.fix(-3.7)}\n`);

// Rounding with precision
console.log(`Round to 2 decimal places: math.round(3.14159, 2) = ${math.round(3.14159, 2)}\n`);
Rounding functions:
Round: math.round(3.7) = 4
Floor: math.floor(3.7) = 3
Ceiling: math.ceil(3.2) = 4
Fix (toward zero): math.fix(-3.7) = -3
Round to 2 decimal places: math.round(3.14159, 2) = 3.14
[5]:
// Using expressions for arithmetic
console.log('Evaluating expressions:\n');

console.log(`Simple expression: math.evaluate('2 + 3 * 4') = ${math.evaluate('2 + 3 * 4')}\n`);
console.log(`With variables: math.evaluate('x^2 + y', {x: 3, y: 4}) = ${math.evaluate('x^2 + y', {x: 3, y: 4})}\n`);
console.log(`With units: math.evaluate('5 cm + 2 inch') = ${math.evaluate('5 cm + 2 inch')}\n`);
Evaluating expressions:
Simple expression: math.evaluate('2 + 3 * 4') = 14
With variables: math.evaluate('x^2 + y', {x: 3, y: 4}) = 13
With units: math.evaluate('5 cm + 2 inch') = 10.08 cm
[M]:

2. Trigonometric Functions

Common trigonometric functions for angles in radians and degrees.

[6]:
// Basic trigonometric functions (radians)
console.log('Trigonometric functions (radians):\n');

console.log(`sin(π/2) = ${math.sin(math.pi/2)}\n`);
console.log(`cos(π) = ${math.cos(math.pi)}\n`);
console.log(`tan(π/4) = ${math.tan(math.pi/4)}\n`);

// Inverse trigonometric functions
console.log(`asin(1) = ${math.asin(1)} radians = ${math.format(math.asin(1), {precision: 4})} radians\n`);
console.log(`acos(0) = ${math.acos(0)} radians = ${math.format(math.acos(0), {precision: 4})} radians\n`);
console.log(`atan(1) = ${math.atan(1)} radians = ${math.format(math.atan(1), {precision: 4})} radians\n`);
Trigonometric functions (radians):
sin(π/2) = 1
cos(π) = -1
tan(π/4) = 0.9999999999999999
asin(1) = 1.5707963267948966 radians = 1.571 radians
acos(0) = 1.5707963267948966 radians = 1.571 radians
atan(1) = 0.7853981633974483 radians = 0.7854 radians
[7]:
// Trigonometric functions with degrees
console.log('Trigonometric functions (degrees):\n');

// Convert degree to radian for computation
console.log(`sin(90°) = ${math.sin(math.unit(90, 'deg'))}\n`);
console.log(`cos(180°) = ${math.cos(math.unit(180, 'deg'))}\n`);
console.log(`tan(45°) = ${math.tan(math.unit(45, 'deg'))}\n`);

// Alternative: using math.evaluate
console.log(`sin(90 deg) = ${math.evaluate('sin(90 deg)')}\n`);
console.log(`cos(180 deg) = ${math.evaluate('cos(180 deg)')}\n`);
console.log(`tan(45 deg) = ${math.evaluate('tan(45 deg)')}\n`);
Trigonometric functions (degrees):
sin(90°) = 1
cos(180°) = -1
tan(45°) = 0.9999999999999999
sin(90 deg) = 1
cos(180 deg) = -1
tan(45 deg) = 0.9999999999999999
[8]:
// Hyperbolic functions
console.log('Hyperbolic functions:\n');

console.log(`sinh(1) = ${math.sinh(1)}\n`);
console.log(`cosh(1) = ${math.cosh(1)}\n`);
console.log(`tanh(1) = ${math.tanh(1)}\n`);

// Inverse hyperbolic functions
console.log(`asinh(1) = ${math.asinh(1)}\n`);
console.log(`acosh(2) = ${math.acosh(2)}\n`);
console.log(`atanh(0.5) = ${math.atanh(0.5)}\n`);
Hyperbolic functions:
sinh(1) = 1.1752011936438014
cosh(1) = 1.5430806348152437
tanh(1) = 0.7615941559557649
asinh(1) = 0.881373587019543
acosh(2) = 1.3169578969248166
atanh(0.5) = 0.5493061443340548
[M]:

3. Exponential and Logarithmic Functions

Quick reference for exponential and logarithmic operations.

[9]:
// Exponential and logarithmic functions
console.log('Exponential and logarithmic functions:\n');

console.log(`Exponential (e^x): math.exp(2) = ${math.exp(2)}\n`);
console.log(`Natural logarithm: math.log(10) = ${math.log(10)}\n`);
console.log(`Base-10 logarithm: math.log10(100) = ${math.log10(100)}\n`);
console.log(`Base-2 logarithm: math.log2(8) = ${math.log2(8)}\n`);

// Custom base logarithm
console.log(`Logarithm base 3: math.log(27, 3) = ${math.log(27, 3)}\n`);

// Constants e and pi
console.log(`Value of e = ${math.e}\n`);
console.log(`Value of π = ${math.pi}\n`);
console.log(`Natural log of e = ${math.log(math.e)}\n`);
Exponential and logarithmic functions:
Exponential (e^x): math.exp(2) = 7.38905609893065
Natural logarithm: math.log(10) = 2.302585092994046
Base-10 logarithm: math.log10(100) = 2
Base-2 logarithm: math.log2(8) = 3
Logarithm base 3: math.log(27, 3) = 3.0000000000000004
Value of e = 2.718281828459045
Value of π = 3.141592653589793
Natural log of e = 1
[M]:

4. Matrix and Vector Operations

Essential matrix and vector operations for linear algebra applications.

[10]:
// Creating matrices and vectors
console.log('Creating matrices and vectors:\n');

// Create a matrix
const matrix1 = math.matrix([[1, 2], [3, 4]]);
console.log(`Matrix 1:\n${matrix1.toString()}\n`);

// Create a vector
const vector1 = math.matrix([5, 6]);
console.log(`Vector 1: ${vector1.toString()}\n`);

// Create special matrices
const identity3 = math.identity(3);
console.log(`3x3 Identity matrix:\n${identity3.toString()}\n`);

const zeros2x3 = math.zeros(2, 3);
console.log(`2x3 Zero matrix:\n${zeros2x3.toString()}\n`);

const ones2x2 = math.ones(2, 2);
console.log(`2x2 Ones matrix:\n${ones2x2.toString()}\n`);
Creating matrices and vectors:
Matrix 1:
[[1, 2], [3, 4]]
Vector 1: [5, 6]
3x3 Identity matrix:
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
2x3 Zero matrix:
[[0, 0, 0], [0, 0, 0]]
2x2 Ones matrix:
[[1, 1], [1, 1]]
[11]:
// Basic matrix operations
console.log('Basic matrix operations:\n');

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

// Addition and subtraction
console.log(`A + B:\n${math.add(A, B).toString()}\n`);
console.log(`A - B:\n${math.subtract(A, B).toString()}\n`);

// Matrix multiplication
console.log(`A * B (matrix product):\n${math.multiply(A, B).toString()}\n`);

// Element-wise multiplication
console.log(`A .* B (element-wise):\n${math.dotMultiply(A, B).toString()}\n`);

// Matrix power
console.log(`A^2:\n${math.pow(A, 2).toString()}\n`);

// Transpose
console.log(`Transpose of A:\n${math.transpose(A).toString()}\n`);
Basic matrix operations:
A + B:
[[6, 8], [10, 12]]
A - B:
[[-4, -4], [-4, -4]]
A * B (matrix product):
[[19, 22], [43, 50]]
A .* B (element-wise):
[[5, 12], [21, 32]]
A^2:
[[7, 10], [15, 22]]
Transpose of A:
[[1, 3], [2, 4]]
[12]:
// Matrix decompositions and advanced operations
console.log('Advanced matrix operations:\n');

const M = math.matrix([[9, 3, 2], [3, 8, 4], [2, 4, 7]]);

// Determinant
console.log(`Determinant of M: ${math.det(M)}\n`);

// Inverse
console.log(`Inverse of M:\n${math.inv(M).toString()}\n`);

// Eigenvalues and eigenvectors
const eigs = math.eigs(M);
console.log(`Eigenvalues: ${math.format(eigs.values, {precision: 3})}\n`);

// Solving linear systems: Ax = b
const A2 = math.matrix([[3, 2], [5, 2]]);
const b = math.matrix([8, 10]);
const x = math.lusolve(A2, b);
console.log(`Solution to Ax = b: ${x.toString()}\n`);
Advanced matrix operations:
Determinant of M: 313
Inverse of M:
[[0.12779552715654952, -0.04153354632587859, -0.012779552715654952], [-0.04153354632587859, 0.18849840255591055, -0.09584664536741215], [-0.012779552715654952, -0.09584664536741214, 0.2012779552715655]]
Eigenvalues: [3.41, 6.53, 14.1]
Solution to Ax = b: [[1], [2.5]]
[M]:

5. Statistics Functions

Quick reference for statistical functions and probability.

[13]:
// Basic statistics
console.log('Basic statistics functions:\n');

const data = [2, 4, 6, 8, 10, 12];

console.log(`Data: [${data}]\n`);
console.log(`Mean: ${math.mean(data)}\n`);
console.log(`Median: ${math.median(data)}\n`);
console.log(`Mode: ${math.mode(data)}\n`);
console.log(`Standard deviation: ${math.std(data)}\n`);
console.log(`Variance: ${math.variance(data)}\n`);
console.log(`Min: ${math.min(data)}\n`);
console.log(`Max: ${math.max(data)}\n`);
console.log(`Sum: ${math.sum(data)}\n`);
console.log(`Product: ${math.prod(data)}\n`);
Basic statistics functions:
Data: [2,4,6,8,10,12]
Mean: 7
Median: 7
Mode: 2,4,6,8,10,12
Standard deviation: 3.7416573867739413
Variance: 14
Min: 2
Max: 12
Sum: 42
Product: 46080
[26]:
// Percentiles and quantiles
console.log('Percentiles and correlation:\n');

// Quantiles
console.log(`25th percentile: ${math.quantileSeq(data, 0.25)}\n`);
console.log(`50th percentile (median): ${math.quantileSeq(data, 0.5)}\n`);
console.log(`75th percentile: ${math.quantileSeq(data, 0.75)}\n`);
console.log(`IQR: ${math.subtract(
math.quantileSeq(data, 0.75),
math.quantileSeq(data, 0.25)
)}\n`);
Percentiles and correlation:
25th percentile: 4.5
50th percentile (median): 7
75th percentile: 9.5
IQR: 5
[15]:
// Probability functions
console.log('Probability functions:\n');

// Combinations (n choose k)
console.log(`C(7,3) = ${math.combinations(7, 3)}\n`);

// Permutations
console.log(`P(7,3) = ${math.permutations(7, 3)}\n`);

// Factorial
console.log(`5! = ${math.factorial(5)}\n`);

// Gamma function (extension of factorial)
console.log(`Gamma(4.5) = ${math.gamma(4.5)}\n`);

// Random number (uniform distribution)
console.log(`Random number: ${math.random()}\n`);
console.log(`Random integer between 1 and 10: ${math.randomInt(1, 11)}\n`);
Probability functions:
C(7,3) = 35
P(7,3) = 210
5! = 120
Gamma(4.5) = 11.631728396567446
Random number: 0.5522813403776621
Random integer between 1 and 10: 2
[M]:

6. Working with Units

Quick reference for unit handling and conversions.

[16]:
// Creating and converting units
console.log('Working with units:\n');

// Create units
const length1 = math.unit(5, 'cm');
const length2 = math.unit('2 inch');
const mass = math.unit('35.5 kg');
const time = math.unit('45 min');
const temp = math.unit('22 degC');

// Display units
console.log(`Length 1: ${length1.toString()}\n`);
console.log(`Length 2: ${length2.toString()}\n`);
console.log(`Mass: ${mass.toString()}\n`);
console.log(`Time: ${time.toString()}\n`);
console.log(`Temperature: ${temp.toString()}\n`);
Working with units:
Length 1: 5 cm
Length 2: 2 inch
Mass: 35.5 kg
Time: 45 min
Temperature: 22 degC
[17]:
// Unit conversions
console.log('Unit conversions:\n');

// Convert units
console.log(`${length1.toString()} = ${length1.to('mm').toString()}\n`);
console.log(`${length2.toString()} = ${length2.to('cm').toString()}\n`);
console.log(`${mass.toString()} = ${mass.to('lb').toString()}\n`);
console.log(`${time.toString()} = ${time.to('s').toString()}\n`);
console.log(`${temp.toString()} = ${temp.to('degF').toString()}\n`);

// Convert using expression syntax
console.log(`10 m/s in km/h: ${math.evaluate('10 m/s to km/h')}\n`);
console.log(`100 kg * 9.8 m/s^2 in Newtons: ${math.evaluate('100 kg * 9.8 m/s^2 to N')}\n`);
Unit conversions:
5 cm = 50 mm
2 inch = 5.08 cm
35.5 kg = 78.26410307563154 lb
45 min = 2700 s
22 degC = 71.6 degF
10 m/s in km/h: 36 km / h
100 kg * 9.8 m/s^2 in Newtons: 980.0000000000001 N
[18]:
// Unit arithmetic
console.log('Arithmetic with units:\n');

// Add compatible units
const totalLength = math.add(length1, length2);
console.log(`${length1} + ${length2} = ${totalLength}\n`);

// Multiply units to get new units
const area = math.multiply(length1, length2);
console.log(`${length1} * ${length2} = ${area}\n`);
console.log(`${area} = ${area.to('cm2')}\n`);

// Speed calculation
const distance = math.unit('100 km');
const duration = math.unit('2 h');
const speed = math.divide(distance, duration);
console.log(`Speed: ${distance} / ${duration} = ${speed}\n`);

// Convert to different unit
console.log(`${speed} = ${speed.to('m/s')}\n`);
Arithmetic with units:
5 cm + 2 inch = 10.08 cm
5 cm * 2 inch = 2540.0000000000005 mm^2
2540.0000000000005 mm^2 = 25.4 cm2
Speed: 100 km / 2 h = 50 km / h
50 km / h = 13.88888888888889 m / s
[M]:

7. Working with Different Number Types

Quick reference for different number types in math.js: BigNumber, Fractions, and Complex numbers.

[27]:
// Working with BigNumber
console.log('Working with BigNumber:\n');

// Create BigNumbers
const big1 = math.bignumber(0.1);
const big2 = math.bignumber(0.2);

// Precise addition without floating point errors
console.log(`Regular JS: 0.1 + 0.2 = ${0.1 + 0.2}\n`); // Shows floating point error
console.log(`BigNumber: ${big1} + ${big2} = ${math.add(big1, big2)}\n`);

// Big calculations
const bigExp = math.pow(math.bignumber(10), 20);
console.log(`10^20 = ${bigExp}\n`);
Working with BigNumber:
Regular JS: 0.1 + 0.2 = 0.30000000000000004
BigNumber: 0.1 + 0.2 = 0.3
10^20 = 100000000000000000000
[20]:
// Working with fractions
console.log('Working with fractions:\n');

// Create fractions
const frac1 = math.fraction(1, 3);
const frac2 = math.fraction(2, 5);
const frac3 = math.fraction('2/7');

console.log(`Fraction 1: ${frac1.toString()}\n`);
console.log(`Fraction 2: ${frac2.toString()}\n`);
console.log(`Fraction 3: ${frac3.toString()}\n`);

// Arithmetic with fractions
console.log(`${frac1} + ${frac2} = ${math.add(frac1, frac2).toString()}\n`);
console.log(`${frac1} * ${frac3} = ${math.multiply(frac1, frac3).toString()}\n`);
console.log(`${frac2} / ${frac3} = ${math.divide(frac2, frac3).toString()}\n`);

// Convert decimal to fraction
console.log(`0.75 as fraction: ${math.fraction(0.75).toString()}\n`);
console.log(`0.33333 as fraction: ${math.fraction(0.33333).toString()}\n`);
Working with fractions:
Fraction 1: 0.(3)
Fraction 2: 0.4
Fraction 3: 0.(285714)
0.(3) + 0.4 = 0.7(3)
0.(3) * 0.(285714) = 0.(095238)
0.4 / 0.(285714) = 1.4
0.75 as fraction: 0.75
0.33333 as fraction: 0.33333
[21]:
// Working with complex numbers
console.log('Working with complex numbers:\n');

// Create complex numbers
const c1 = math.complex(2, 3); // 2 + 3i
const c2 = math.complex('4-2i'); // 4 - 2i

console.log(`Complex 1: ${c1.toString()}\n`);
console.log(`Complex 2: ${c2.toString()}\n`);

// Complex arithmetic
console.log(`${c1} + ${c2} = ${math.add(c1, c2).toString()}\n`);
console.log(`${c1} * ${c2} = ${math.multiply(c1, c2).toString()}\n`);

// Complex functions
console.log(`abs(${c1}) = ${math.abs(c1)}\n`); // Magnitude
console.log(`arg(${c1}) = ${math.arg(c1)} radians\n`); // Argument (phase)
console.log(`sqrt(-4) = ${math.sqrt(math.complex(-4)).toString()}\n`);

// Complex exponential
console.log(`e^(i*π) = ${math.exp(math.complex(0, math.pi)).toString()}\n`);
Working with complex numbers:
Complex 1: 2 + 3i
Complex 2: 4 - 2i
2 + 3i + 4 - 2i = 6 + i
2 + 3i * 4 - 2i = 14 + 8i
abs(2 + 3i) = 3.605551275463989
arg(2 + 3i) = 0.982793723247329 radians
sqrt(-4) = 2i
e^(i*π) = -1
[M]:

8. Expression Parsing and Evaluation

Quick reference for parsing and evaluating mathematical expressions.

[22]:
// Basic expression evaluation
console.log('Expression evaluation:\n');

// Simple expressions
console.log(`'2 + 3 * 4' = ${math.evaluate('2 + 3 * 4')}\n`);
console.log(`'sqrt(16) + 2^3' = ${math.evaluate('sqrt(16) + 2^3')}\n`);

// With variables
const scope = {
x: 3,
y: 4
};
console.log(`'x^2 + y^2' with x=3, y=4 = ${math.evaluate('x^2 + y^2', scope)}\n`);

// Updating variables
console.log(`'x = x + 1' with x=3 = ${math.evaluate('x = x + 1', scope)}\n`);
console.log(`After update, x = ${scope.x}\n`);

// Multi-line expressions
const result = math.evaluate([
'a = 5',
'b = 10 * a',
'c = a^2 + b',
'c / a'
]);
console.log(`Multi-line calculation result: ${result}\n`);
Expression evaluation:
'2 + 3 * 4' = 14
'sqrt(16) + 2^3' = 12
'x^2 + y^2' with x=3, y=4 = 25
'x = x + 1' with x=3 = 4
After update, x = 4
Multi-line calculation result: 5,50,75,15
[23]:
// Parsing and compiling expressions
console.log('Parsing and compiling expressions:\n');

// Parse expression
const expr = math.parse('x^2 + 2*x + 1');
console.log(`Expression: ${expr.toString()}\n`);

// Compile expression for faster evaluation
const compiledExpr = expr.compile();

// Evaluate for different values
console.log('Evaluating expression for different x values:\n');
for (let x = 0; x <= 5; x++) {
console.log(`x = ${x}, result = ${compiledExpr.evaluate({x: x})}\n`);
}

// Manipulate expression
const derivative = math.derivative(expr, 'x');
console.log(`Derivative: ${derivative.toString()}\n`);

// Simplify expression
const simplified = math.simplify(expr);
console.log(`Simplified: ${simplified.toString()}\n`);
Parsing and compiling expressions:
Expression: x ^ 2 + 2 * x + 1
Evaluating expression for different x values:
x = 0, result = 1
x = 1, result = 4
x = 2, result = 9
x = 3, result = 16
x = 4, result = 25
x = 5, result = 36
Derivative: 2 * (x + 1)
Simplified: x ^ 2 + 2 * x + 1
[M]:

10. Quick Reference Table

Summary of the most commonly used math.js functions.

Basic Arithmetic

FunctionDescriptionExample
add(x, y)Additionmath.add(2, 3) = 5
subtract(x, y)Subtractionmath.subtract(5, 2) = 3
multiply(x, y)Multiplicationmath.multiply(2, 3) = 6
divide(x, y)Divisionmath.divide(6, 2) = 3
pow(x, y)Powermath.pow(2, 3) = 8
sqrt(x)Square rootmath.sqrt(9) = 3
abs(x)Absolute valuemath.abs(-5) = 5

Trigonometry

FunctionDescriptionExample
sin(x)Sinemath.sin(math.pi/2) = 1
cos(x)Cosinemath.cos(0) = 1
tan(x)Tangentmath.tan(math.pi/4) = 1
asin(x)Arc sinemath.asin(1) = π/2
acos(x)Arc cosinemath.acos(1) = 0
atan(x)Arc tangentmath.atan(1) = π/4

Statistics

FunctionDescriptionExample
mean(array)Averagemath.mean([1,2,3]) = 2
median(array)Middle valuemath.median([1,2,3]) = 2
std(array)Standard deviationmath.std([2,4,6]) = 2
min(array)Minimum valuemath.min([4,2,7]) = 2
max(array)Maximum valuemath.max([4,2,7]) = 7
quantileSeq(array, prob)Quantilemath.quantileSeq([1,2,3,4], 0.5) = 2.5

Matrices

FunctionDescriptionExample
matrix()Create matrixmath.matrix([[1,2],[3,4]])
det(matrix)Determinantmath.det([[1,2],[3,4]]) = -2
inv(matrix)Inversemath.inv([[1,2],[3,4]])
transpose(matrix)Transposemath.transpose([[1,2],[3,4]])
subset(matrix, index)Extract subsetmath.subset(matrix, math.index(0, 1))

Special Functions

FunctionDescriptionExample
factorial(n)Factorialmath.factorial(5) = 120
gamma(n)Gamma functionmath.gamma(5) = 24
log(x, [base])Logarithmmath.log(1000, 10) = 3
random([min, max])Random numbermath.random(0, 10)
distance(x, y)Distancemath.distance([0,0], [3,4]) = 5
[M]:

Quick Tips and Common Patterns

Here are some common patterns and tips when working with math.js:

  1. Chain operations for cleaner code:

    math.chain(3)
      .add(4)
      .multiply(2)
      .done()  // Returns 14
    
  2. Selective importing for better performance:

    const { add, multiply, sin } = require('mathjs');
    
  3. Use compiled expressions for repeated evaluations:

    const expr = math.compile('x^2 + y');
    // Then use expr.evaluate({x: 3, y: 4}) multiple times
    
  4. Format output with precision control:

    math.format(math.pi, {precision: 4})  // Returns '3.142'
    
  5. Use the right number type for your application:

    • Regular JavaScript numbers for most calculations
    • BigNumber for high precision decimal arithmetic
    • Fractions for exact rational arithmetic
  6. Convert between types when needed:

    math.number(math.bignumber('0.1'))  // BigNumber to number
    math.fraction(0.25)                 // Number to fraction
    
  7. Handle expressions safely with try-catch:

    try {
      const result = math.evaluate(userInput);
    } catch (error) {
      console.log('Invalid expression');
    }
    
Sign in to save your work and access it from anywhere