Math.js 是 JavaScript 生态里最强大、通用的数学计算库,核心解决原生 Math 功能弱、精度差、无表达式解析、不支持复数/矩阵/单位等痛点。
一、核心定位与优势
- 兼容浏览器 & Node.js,无外部依赖
- 支持:高精度数、复数、分数、单位、矩阵、符号计算
- 内置表达式解析器(字符串公式直接算)
- API 友好,兼容原生
Math用法
二、安装与引入
1. npm(推荐)
bash
npm install mathjs
javascript
// 全量引入
import { create, all } from 'mathjs'
const math = create(all)
// 或按需引入(更轻量)
import { add, sqrt, evaluate } from 'mathjs'
// 纯 number 轻量版(无复数/高精度,性能高)
import { add } from 'mathjs/number'
2. 浏览器 CDN
html
<script src="https://cdn.jsdelivr.net/npm/mathjs/lib/browser/math.js"></script>
<script>
console.log(math.add(2,3)) // 5
</script>
三、基础用法
1. 常用函数(对标原生 Math)
javascript
math.add(2, 3) // 5 加法
math.subtract(7, 3) // 4 减
math.multiply(2, 8) // 16 乘
math.divide(9, 3) // 3 除
math.pow(2, 10) // 1024
math.sqrt(-4) // 2i 复数支持
math.sin(math.pi / 2) // 1
math.log(1000, 10) // 3
math.round(math.e, 3) // 2.718
2. 表达式解析(最强特性)
javascript
math.evaluate('sqrt(3^2 + 4^2)') // 5
math.evaluate('1.2 * (2 + 4.5)') // 7.8
math.evaluate('12.7 cm to inch') // 5 inch(单位换算)
math.evaluate('sin(45 deg) ^ 2') // 0.5
math.evaluate('det([-1,2;3,1])') // -7(矩阵行列式)
3. 链式调用
javascript
math.chain(3)
.add(4) // 7
.multiply(2) // 14
.done() // 14
四、高级数据类型
1. 复数
javascript
const c1 = math.complex(2, 3) // 2 + 3i
const c2 = math.complex('1-2i')
math.add(c1, c2) // 3 + i
2. 分数(避免浮点误差)
javascript
const f1 = math.fraction(1, 3)
const f2 = math.fraction(1, 6)
math.add(f1, f2) // 1/2
3. 矩阵 / 线性代数
javascript
const A = math.matrix([[1,2],[3,4]])
math.det(A) // -2(行列式)
math.inv(A) // 逆矩阵
math.multiply(A, A) // 矩阵平方
4. 单位换算
javascript
math.evaluate('1 meter to inch') // 39.37...
math.evaluate('1 kg to lb') // 2.204...
5. 符号计算(求导、化简)
javascript
math.derivative('x^2 + x', 'x') // 2x + 1
math.simplify('x + x + x') // 3x
五、精度控制(BigNumber)
解决 JS 浮点数精度问题(如 0.1+0.2≠0.3):
javascript
const math = create(all, {
number: 'BigNumber' // 默认用高精度
})
math.add(0.1, 0.2) // 0.3(精确)
六、典型应用场景
- 前端计算器、公式编辑器
- 科学计算、数据可视化、图表
- 单位换算、几何/物理计算
- 低代码平台的动态公式引擎
- 教育类数学工具
七、与原生 Math 对比
| 特性 | 原生 JS Math | Math.js |
|---|---|---|
| 精度 | 双精度浮点 | BigNumber/高精度 |
| 数据类型 | 仅数字 | 复数、分数、矩阵、单位 |
| 表达式解析 | ❌ | ✅ 字符串直接解析 |
| 符号计算 | ❌ | ✅ 求导、化简 |
| 线性代数 | ❌ | ✅ 矩阵、行列式、逆矩阵 |
| 单位换算 | ❌ | ✅ 内置大量单位 |
八、快速上手示例(完整)
javascript
import { create, all } from 'mathjs'
const math = create(all)
// 1. 基础计算
console.log(math.evaluate('sqrt(3^2 + 4^2)')) // 5
// 2. 复数
console.log(math.sqrt(-4).toString()) // 2i
// 3. 矩阵
const m = math.matrix([[1,2],[3,4]])
console.log(math.det(m)) // -2
// 4. 符号求导
console.log(math.derivative('x^3', 'x').toString()) // 3x^2