Logo
⚠️ Unsaved
[M]:

Mathjs Fundamentals: Getting Started with Math Operations

Math.js is a powerful JavaScript library that extends the built-in Math capabilities with support for matrices, complex numbers, units, symbolic computation, and much more. Whether you're building a scientific calculator, data visualization tool, or need to perform mathematical operations in your web application, math.js provides the tools you need.

This notebook introduces the fundamental operations and features of math.js to get you started with mathematical computing in JavaScript.

[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 library loaded successfully\n');
Math.js library loaded successfully
[M]:

1. Basic Arithmetic Operations

Let's start with basic operations. Math.js provides functions for all standard math operations, offering more precision and features than JavaScript's built-in math operators.

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

console.log(`Addition: ${math.add(2, 3)}\n`);
console.log(`Subtraction: ${math.subtract(7, 3)}\n`);
console.log(`Multiplication: ${math.multiply(4, 5.5)}\n`);
console.log(`Division: ${math.divide(15, 3)}\n`);

// Handling more complex expressions
const result = math.evaluate('(2 + 3) * 4 / 2');
console.log(`Complex expression (2 + 3) * 4 / 2 = ${result}\n`);
Basic arithmetic operations:
Addition: 5
Subtraction: 4
Multiplication: 22
Division: 5
Complex expression (2 + 3) * 4 / 2 = 10
[4]:
// More advanced operations
console.log('Advanced operations:\n');

console.log(`Square root of 16: ${math.sqrt(16)}\n`);
console.log(`Power: 2^8 = ${math.pow(2, 8)}\n`);
console.log(`Exponential: e^2 = ${math.exp(2)}\n`);
console.log(`Logarithm (base 10) of 1000: ${math.log10(1000)}\n`);
console.log(`Natural logarithm of 10: ${math.log(10)}\n`);

// Trigonometric functions
console.log(`Sine of 90° (in radians): ${math.sin(math.pi/2)}\n`);
console.log(`Cosine of 0°: ${math.cos(0)}\n`);
console.log(`Tangent of 45° (in radians): ${math.tan(math.pi/4)}\n`);
Advanced operations:
Square root of 16: 4
Power: 2^8 = 256
Exponential: e^2 = 7.38905609893065
Logarithm (base 10) of 1000: 3
Natural logarithm of 10: 2.302585092994046
Sine of 90° (in radians): 1
Cosine of 0°: 1
Tangent of 45° (in radians): 0.9999999999999999
[M]:

2. Working with Different Number Types

One of math.js's strengths is its ability to work with various number types including fractions, complex numbers, and big numbers for arbitrary precision.

[5]:
// Fractions
console.log('Working with fractions:\n');

const frac1 = math.fraction(1, 3);
const frac2 = math.fraction(2, 5);

console.log(`Fraction 1: ${frac1.toString()}\n`);
console.log(`Fraction 2: ${frac2.toString()}\n`);
console.log(`Addition: ${math.add(frac1, frac2).toString()}\n`);
console.log(`Multiplication: ${math.multiply(frac1, frac2).toString()}\n`);

// Convert decimal to fraction
console.log(`0.75 as a fraction: ${math.fraction(0.75).toString()}\n`);
Working with fractions:
Fraction 1: 0.(3)
Fraction 2: 0.4
Addition: 0.7(3)
Multiplication: 0.1(3)
0.75 as a fraction: 0.75
[6]:
// Complex numbers
console.log('Working with complex numbers:\n');

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

console.log(`Complex number 1: ${c1.toString()}\n`);
console.log(`Complex number 2: ${c2.toString()}\n`);
console.log(`Addition: ${math.add(c1, c2).toString()}\n`);
console.log(`Multiplication: ${math.multiply(c1, c2).toString()}\n`);

// Calculate the absolute value (magnitude)
console.log(`Magnitude of ${c1.toString()}: ${math.abs(c1)}\n`);

// Using the i notation
const result = math.evaluate('(3 + 4i) * (1 - 2i)');
console.log(`(3 + 4i) * (1 - 2i) = ${result.toString()}\n`);
Working with complex numbers:
Complex number 1: 3 + 4i
Complex number 2: 1 - 2i
Addition: 4 + 2i
Multiplication: 11 - 2i
Magnitude of 3 + 4i: 5
(3 + 4i) * (1 - 2i) = 11 - 2i
[7]:
// Big numbers for arbitrary precision
console.log('Using big numbers for high precision:\n');

// Configure math.js to use big numbers
const config = {
number: 'BigNumber',
precision: 20 // Set the precision to 20 digits
};
const mathBig = math.create(math.all, config);

// Calculate pi with high precision
console.log(`Pi with high precision: ${mathBig.pi.toString()}\n`);

// Calculate a division that normally has rounding errors
const regularDivision = 1/3;
const bigDivision = mathBig.divide(1, 3);

console.log(`Regular JS division 1/3: ${regularDivision}\n`);
console.log(`BigNumber division 1/3: ${bigDivision.toString()}\n`);

// Restore default configuration
math.config({number: 'number'});
Error during execution: The global config is readonly. Please create a mathjs instance if you want to change the default configuration. Example: import { create, all } from 'mathjs'; const mathjs = create(all); mathjs.config({ number: 'BigNumber' }); Using big numbers for high precision: Pi with high precision: 3.1415926535897932385 Regular JS division 1/3: 0.3333333333333333 BigNumber division 1/3: 0.3333333333333333
[M]:

3. Matrix and Vector Operations

Math.js provides powerful tools for working with matrices and vectors, essential for linear algebra, machine learning, and data science applications.

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

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

// Create a vector
const vector1 = math.matrix([7, 8, 9]);
console.log('Vector 1:\n');
console.log(`${math.format(vector1, {precision: 2})}\n`);

// Matrix dimensions and size
console.log(`Matrix dimensions: ${math.size(matrix1).valueOf().join(' x ')}\n`);
console.log(`Is matrix? ${math.typeOf(matrix1)}\n`);
Creating matrices and vectors:
Matrix 1:
[[1, 2, 3], [4, 5, 6]]
Vector 1:
[7, 8, 9]
Matrix dimensions: 2 x 3
Is matrix? DenseMatrix
[9]:
// Matrix operations
console.log('Matrix operations:\n');

const matrix2 = math.matrix([[1, 2], [3, 4], [5, 6]]);
console.log('Matrix 2:\n');
console.log(`${math.format(matrix2, {precision: 2})}\n`);

// Matrix addition
const matrix3 = math.matrix([[1, 1, 1], [2, 2, 2]]);
const matrixSum = math.add(matrix1, matrix3);
console.log('Matrix sum (1 + 3):\n');
console.log(`${math.format(matrixSum, {precision: 2})}\n`);

// Matrix multiplication
const matrixProduct = math.multiply(matrix1, matrix2);
console.log('Matrix product (1 x 2):\n');
console.log(`${math.format(matrixProduct, {precision: 2})}\n`);

// Matrix transpose
const transposed = math.transpose(matrix1);
console.log('Transposed matrix 1:\n');
console.log(`${math.format(transposed, {precision: 2})}\n`);
Matrix operations:
Matrix 2:
[[1, 2], [3, 4], [5, 6]]
Matrix sum (1 + 3):
[[2, 3, 4], [6, 7, 8]]
Matrix product (1 x 2):
[[22, 28], [49, 64]]
Transposed matrix 1:
[[1, 4], [2, 5], [3, 6]]
[10]:
// Vector operations and linear algebra
console.log('Vector operations and linear algebra:\n');

const vec1 = math.matrix([1, 2, 3]);
const vec2 = math.matrix([4, 5, 6]);

// Vector addition
const vecSum = math.add(vec1, vec2);
console.log(`Vector sum: ${math.format(vecSum)}\n`);

// Dot product
const dotProduct = math.dot(vec1, vec2);
console.log(`Dot product: ${dotProduct}\n`);

// Cross product (for 3D vectors)
const crossProduct = math.cross(vec1, vec2);
console.log(`Cross product: ${math.format(crossProduct)}\n`);

// Calculate determinant of a square matrix
const squareMatrix = math.matrix([[1, 2], [3, 4]]);
const det = math.det(squareMatrix);
console.log(`Determinant: ${det}\n`);

// Solve a system of linear equations: Ax = b
const A = math.matrix([[1, 2], [3, 4]]);
const b = math.matrix([5, 11]);
const x = math.lusolve(A, b);
console.log('Solution to the system of equations:\n');
console.log(`${math.format(x)}\n`);
Vector operations and linear algebra:
Vector sum: [5, 7, 9]
Dot product: 32
Cross product: [-3, 6, -3]
Determinant: -2
Solution to the system of equations:
[[1], [2]]
[M]:

4. Working with Units

Math.js has built-in support for units and unit conversions, making it great for scientific and engineering applications.

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

// Create units
const distance = math.unit(5, 'km');
console.log(`Distance: ${distance.toString()}\n`);

const time = math.unit(1, 'hour');
console.log(`Time: ${time.toString()}\n`);

// Convert units
const distanceInMiles = math.to(distance, 'miles');
console.log(`Distance in miles: ${distanceInMiles.toString()}\n`);

const timeInMinutes = math.to(time, 'minutes');
console.log(`Time in minutes: ${timeInMinutes.toString()}\n`);

// Calculate speed
const speed = math.divide(distance, time);
console.log(`Speed: ${speed.toString()}\n`);

// Convert speed to different units
const speedInMPH = math.to(speed, 'mi/h');
console.log(`Speed in miles per hour: ${speedInMPH.toString()}\n`);
Working with units:
Distance: 5 km
Time: 1 hour
Distance in miles: 3.1068559611866697 miles
Time in minutes: 60 minutes
Speed: 5 km / hour
Speed in miles per hour: 3.1068559611866697 mi / h
[12]:
// More unit operations
console.log('More unit operations:\n');

// Temperature conversions
const temp = math.unit(25, 'celsius');
const tempF = math.to(temp, 'fahrenheit');
console.log(`${temp.toString()} = ${tempF.toString()}\n`);

// Volume conversions
const volume = math.unit(1, 'liter');
const volumeGal = math.to(volume, 'gallons');
console.log(`${volume.toString()} = ${volumeGal.toString()}\n`);

// Area calculations
const length = math.unit(10, 'm');
const width = math.unit(5, 'm');
const area = math.multiply(length, width);
console.log(`Area: ${area.toString()}\n`);

// Convert to different area units
const areaInSqFt = math.to(area, 'sqft');
console.log(`Area in square feet: ${areaInSqFt.toString()}\n`);
More unit operations:
25 celsius = 77 fahrenheit
1 liter = 0.2641720523581484 gallons
Area: 50 m^2
Area in square feet: 538.195520835486 sqft
[M]:

5. Symbolic Math and Expressions

Math.js supports symbolic math operations, allowing you to work with algebraic expressions and perform operations like differentiation and simplification.

[13]:
// Working with expressions and symbols
console.log('Working with symbolic expressions:\n');

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

// Compile the expression for faster repeated evaluation
const compiled = expr.compile();

// Evaluate for different values of x
let scope = {x: 2};
console.log(`When x = 2: ${compiled.evaluate(scope)}\n`);

scope = {x: -1};
console.log(`When x = -1: ${compiled.evaluate(scope)}\n`);

// Simplify an expression
const simplified = math.simplify('x^2 + 2*x*y + y^2');
console.log(`Simplified expression: ${simplified.toString()}\n`);
Working with symbolic expressions:
Expression: x ^ 2 + 2 * x + 1
When x = 2: 9
When x = -1: 0
Simplified expression: x ^ 2 + 2 * x * y + y ^ 2
[14]:
// Symbolic differentiation and substitution
console.log('Symbolic differentiation and substitution:\n');

// Differentiate an expression
const derivative = math.derivative('x^3 + x^2 + x + 1', 'x');
console.log(`Derivative of x^3 + x^2 + x + 1: ${derivative.toString()}\n`);

// Substitute values into expressions
const expr2 = math.parse('a*x^2 + b*x + c');
const substituted = expr2.substitute({a: 2, b: 3, c: 4});
console.log(`After substitution: ${substituted.toString()}\n`);

// Combining operations
const quadratic = math.parse('a*x^2 + b*x + c');
const deriv = math.derivative(quadratic, 'x');
console.log(`Derivative of a*x^2 + b*x + c: ${deriv.toString()}\n`);

// Substitute after differentiation
const derivWithValues = deriv.substitute({a: 1, b: -4});
console.log(`After substituting a=1, b=-4: ${derivWithValues.toString()}\n`);

// Evaluate the derivative at a specific point
const evaluated = derivWithValues.evaluate({x: 2});
console.log(`Evaluated at x=2: ${evaluated}\n`);
Error during execution: expr2.substitute is not a functionSymbolic differentiation and substitution: Derivative of x^3 + x^2 + x + 1: 3 * x ^ 2 + 2 * x + 1
[M]:

6. Practical Applications

Now let's look at some practical applications combining multiple math.js features.

[15]:
// Example 1: Solving a quadratic equation
console.log('Solving a quadratic equation (ax² + bx + c = 0):\n');

function solveQuadratic(a, b, c) {
// Calculate discriminant
const discriminant = math.subtract(
math.pow(b, 2),
math.multiply(4, a, c)
);
if (math.smaller(discriminant, 0)) {
// Complex roots
const realPart = math.divide(math.multiply(-1, b), math.multiply(2, a));
const imagPart = math.divide(
math.sqrt(math.multiply(-1, discriminant)),
math.multiply(2, a)
);
const root1 = math.complex(realPart, imagPart);
const root2 = math.complex(realPart, math.multiply(-1, imagPart));
return [root1, root2];
} else {
// Real roots
const root1 = math.divide(
math.add(math.multiply(-1, b), math.sqrt(discriminant)),
math.multiply(2, a)
);
const root2 = math.divide(
math.subtract(math.multiply(-1, b), math.sqrt(discriminant)),
math.multiply(2, a)
);
return [root1, root2];
}
Solving a quadratic equation (ax² + bx + c = 0):
Roots of x² + 2x + 5 = 0: -1 + 2i, -1 - 2i
Roots of x² - 5x + 6 = 0: 3, 2
[16]:
// Example 2: Basic statistics functions
console.log('Statistical calculations:\n');

const dataset = [12, 7, 14, 9, 11, 13, 8, 6, 15, 10];
console.log(`Dataset: ${dataset.join(', ')}\n`);

// Basic statistics
console.log(`Mean: ${math.mean(dataset)}\n`);
console.log(`Median: ${math.median(dataset)}\n`);
console.log(`Standard Deviation: ${math.std(dataset)}\n`);
console.log(`Variance: ${math.variance(dataset)}\n`);
console.log(`Min: ${math.min(dataset)}\n`);
console.log(`Max: ${math.max(dataset)}\n`);

// Calculate correlation between two datasets
const dataset2 = [21, 14, 24, 17, 20, 23, 16, 13, 25, 19];
console.log(`Dataset 2: ${dataset2.join(', ')}\n`);

const correlation = math.correlation(dataset, dataset2);
console.log(`Correlation coefficient: ${correlation}\n`);

// Calculate percentiles
console.log(`25th percentile: ${math.quantileSeq(dataset, 0.25)}\n`);
console.log(`75th percentile: ${math.quantileSeq(dataset, 0.75)}\n`);
console.log(`Interquartile range: ${math.subtract(
math.quantileSeq(dataset, 0.75),
math.quantileSeq(dataset, 0.25)
)}\n`);
Error during execution: math.correlation is not a functionStatistical calculations: Dataset: 12, 7, 14, 9, 11, 13, 8, 6, 15, 10 Mean: 10.5 Median: 10.5 Standard Deviation: 3.0276503540974917 Variance: 9.166666666666666 Min: 6 Max: 15 Dataset 2: 21, 14, 24, 17, 20, 23, 16, 13, 25, 19
[M]:

7. Performance Considerations and Best Practices

Let's wrap up with some performance tips and best practices for working with math.js.

[M]:

Best Practices

  1. Selective imports: For better performance, import only the functions you need.

    const { add, multiply } = require('mathjs');
    
  2. Compile expressions: If you're evaluating the same expression multiple times with different values, use .compile() for better performance.

  3. Use appropriate number types:

    • Regular JavaScript numbers for most calculations
    • BigNumber for high precision but slower calculations
    • Fractions for exact rational arithmetic
  4. Array vs. Matrix: Use regular arrays for simple operations and math.js matrices for more complex linear algebra operations.

  5. Chain operations: Use method chaining where possible for cleaner code.

  6. Reuse objects: Creating new objects for each calculation can be expensive; reuse when possible.

  7. Error handling: Always implement proper error handling, as mathematical operations can fail in unexpected ways.

[17]:
// Performance comparison example
console.log('Performance comparison:\n');

// Function to measure execution time
function measureTime(fn, name) {
const start = process.hrtime.bigint();
fn();
const end = process.hrtime.bigint();
const timeInMs = Number(end - start) / 1_000_000;
console.log(`${name}: ${timeInMs.toFixed(3)} ms\n`);
}

// Compare non-compiled vs. compiled expression evaluation
const iterations = 100000;
const expression = 'sin(x) * cos(x) / tan(x) + sqrt(x^2 + 1)';

measureTime(() => {
for (let i = 0; i < iterations; i++) {
math.evaluate(expression, { x: i / 1000 });
}
}, 'Non-compiled evaluation');

const compiledExpr = math.compile(expression);
measureTime(() => {
for (let i = 0; i < iterations; i++) {
compiledExpr.evaluate({ x: i / 1000 });
}
}, 'Compiled evaluation');
Performance comparison:
Non-compiled evaluation: 1365.255 ms
Compiled evaluation: 120.855 ms
[M]:

Conclusion

In this notebook, we've explored the fundamentals of the math.js library:

  • Basic arithmetic and advanced mathematical operations
  • Working with different number types (fractions, complex numbers, BigNumber)
  • Matrix and vector operations for linear algebra
  • Working with physical units and conversions
  • Symbolic math and expressions
  • Practical applications and performance considerations

Math.js provides an extensive set of tools for mathematical operations in JavaScript, making it suitable for a wide range of applications from simple calculations to complex scientific computing. Its ability to handle different number types, symbolic expressions, units, and matrices makes it one of the most versatile math libraries available for JavaScript.

For more information and advanced usage, check out the official documentation.

Sign in to save your work and access it from anywhere