Math.js使用笔记

最近的工作需要使用JS进行数学计算并精确到N位小数,众所周知JS自身的数学计算因为采用了 IEEE 754 标准,导致涉及小数的计算时存在丢失精度的情况。

于是从网上找了mathjs,一个专业的JS数学计算库来解决该问题,这里记录下mathjs的用法

1
2
3
4
5
6
/**
* math.js
*/
import { create, all } from 'mathjs'

Vue.prototype.$math = create(all, config)

1、直接使用方法

1
2
3
4
5
this.$math.round(math.e, 3)                // 2.718
this.$math.atan2(3, -3) / math.pi // 0.75
this.$math.log(10000, 10) // 4
this.$math.sqrt(-4) // 2i
this.$math.derivative('x^2 + x', 'x') // 2*x+1

2、使用表达式字符串

1
2
3
4
5
this.$math.evaluate('1.2 * (2 + 4.5)')     // 7.8
this.$math.evaluate('12.7 cm to inch') // 5 inch
this.$math.evaluate('sin(45 deg) ^ 2') // 0.5
this.$math.evaluate('9 / 3 + 2i') // 3 + 2i
this.$math.evaluate('det([-1, 2; 3, 1])') // -7

3、链式操作

1
2
3
4
this.$math.chain(3)
.add(4)
.multiply(2)
.done() // 14

常用方法:https://mathjs.org/docs/reference/functions.html
拓展阅读:JavaScript 浮点数之迷:0.1 + 0.2 为什么不等于 0.3?


评论区