使用 npm 安装:
npm install mathjs
使用 yarn 安装:
yarn add mathjs
通过 CDN 引入:
<script src="https://cdn.jsdelivr.net/npm/mathjs@latest/dist/math.min.js"></script>
const math = require('mathjs');
console.log(math.sqrt(16)); // 4
console.log(math.log(10000, 10)); // 4
const math = require('mathjs');
const a = math.matrix([[1, 2], [3, 4]]);
const b = math.matrix([[5, 6], [7, 8]]);
const c = math.add(a, b);
console.log(c.valueOf()); // [[6, 8], [10, 12]]
const math = require('mathjs');
const expr = '2 * (3 + 4)';
const result = math.evaluate(expr);
console.log(result); // 14
基本数学运算:
math.add(a, b)
:加法运算。math.subtract(a, b)
:减法运算。math.multiply(a, b)
:乘法运算。math.divide(a, b)
:除法运算。math.sqrt(x)
:平方根。代数运算:
math.factorial(n)
:阶乘。math.pow(x, y)
:幂运算。矩阵运算:
math.matrix(arr)
:创建矩阵。math.transpose(m)
:矩阵转置。math.det(m)
:计算矩阵的行列式。统计运算:
math.mean(arr)
:计算平均值。math.median(arr)
:计算中位数。math.std(arr)
:计算标准差。单位转换:
math.unit(value, unit)
:创建单位。math.to(value, unit)
:单位转换。大数运算:
math.bignumber(x)
:创建大数。math.format(value)
:格式化大数。可以在 Math.js 中定义自己的函数,以扩展库的功能:
const math = require('mathjs');
math.import({
myFunction: function (a, b) {
return a + b;
}
});
console.log(math.myFunction(2, 3)); // 5
Math.js 采用模块化设计,可以只加载需要的部分:
const { add, multiply } = require('mathjs');
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20