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]:
$ npm install mathjs

added 9 packages in 3s

30 packages are looking for funding
  run `npm fund` for details
[2]:
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 operations:
Addition: 5
Subtraction: 4
Multiplication: 22
Division: 5
Complex expression (2 + 3) * 4 / 2 = 10
[4]:
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]:
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]:
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]:
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:
Matrix 1:
[[1, 2, 3], [4, 5, 6]]
Vector 1:
[7, 8, 9]
Matrix dimensions: 2 x 3
Is matrix? DenseMatrix
[9]:
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:
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]:
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:
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 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]:
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]:
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]:
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:
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