Introduction
Math.js is a comprehensive mathematics library for JavaScript and Node.js. It provides a flexible expression parser, support for symbolic computation, a large set of built-in functions, and data types like matrices, complex numbers, fractions, units, and big numbers. It works in browsers and Node.js alike.
What Math.js Does
- Parses and evaluates mathematical expressions as strings
- Supports matrices, complex numbers, fractions, and big numbers natively
- Provides 200+ built-in mathematical functions (algebra, statistics, trigonometry)
- Handles physical unit conversions (e.g., inches to cm, kg to lb)
- Offers both a functional and chained API for flexible usage
Architecture Overview
Math.js is built around a dependency-injection core that lets you create custom instances with only the functions you need, reducing bundle size. The expression parser tokenizes input strings into an AST, which is then compiled and evaluated. All data types implement a common interface so operations compose naturally across numbers, matrices, and units.
Self-Hosting & Configuration
- Install via npm, yarn, or load from a CDN in the browser
- Create a custom mathjs instance with
create(config)to limit included functions - Configure number precision, matrix type (dense vs sparse), and angle units
- Extend with custom functions using
math.import({ myFunc: ... }) - Works in Node.js, Deno, and all modern browsers without polyfills
Key Features
- Expression parser with variable scope and custom function definitions
- Arbitrary precision arithmetic via BigNumber support
- Comprehensive matrix operations including decomposition and solvers
- Physical unit system with automatic conversion and simplification
- TypeScript declarations included for full type safety
Comparison with Similar Tools
- NumPy (Python) — More mature for scientific computing but Python-only; Math.js brings similar concepts to JavaScript
- decimal.js — Focuses solely on arbitrary precision decimals; Math.js offers a full math toolkit
- D3.js — Oriented toward data visualization rather than general math computation
- stdlib — Broader numerical computing library but heavier and less expression-friendly
FAQ
Q: Can Math.js handle symbolic algebra? A: It supports expression simplification and derivative computation, but is not a full CAS like SymPy.
Q: How large is the bundle? A: The full library is around 180 KB minified. You can tree-shake or use custom builds to reduce this.
Q: Does it support LaTeX output? A: Yes, expression nodes can be serialized to LaTeX strings for rendering.
Q: Is it suitable for financial calculations? A: Yes, use BigNumber configuration to avoid floating-point rounding issues.