开始使用 #
本指南描述了如何安装、加载和使用 math.js。
安装 #
Math.js 可以使用各种包管理器进行安装,例如 npm,或者直接从网站下载库:https://mathjs.cn/download.html。
通过 npm 安装,请运行
npm install mathjs
其他安装 math.js 的方法可在网站上找到。
加载 #
Math.js 可在 node.js 和浏览器中使用。必须加载并实例化该库。创建实例时,可以选择提供配置选项,具体请参阅配置。
ES 模块 #
加载您需要的函数并使用它们
import { sqrt } from 'mathjs'
console.log(sqrt(-4).toString()) // 2i
要使用所有函数的轻量级、纯数字实现
import { sqrt } from 'mathjs/number'
console.log(sqrt(4).toString()) // 2
console.log(sqrt(-4).toString()) // NaN
您可以创建一个允许配置和导入外部函数的 mathjs 实例,如下所示
import { create, all } from 'mathjs'
const config = { }
const math = create(all, config)
console.log(math.sqrt(-4).toString()) // 2i
如何优化捆绑包大小(使用 tree-shaking)已在自定义捆绑页面上进行了描述。
Node.js #
在 node.js 中加载 math.js(CommonJS 模块系统)
const { sqrt } = require('mathjs')
console.log(sqrt(-4).toString()) // 2i
浏览器 #
Math.js 可以作为常规 JavaScript 文件在浏览器中加载,加载后使用全局变量 math 来访问库。
<!DOCTYPE HTML>
<html>
<head>
<script src="math.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
console.log(math.sqrt(-4).toString()) // 2i
</script>
</body>
</html>
使用 #
Math.js 的使用方式类似于 JavaScript 内置的 Math 库。此外,math.js 可以解析表达式(请参阅表达式)并支持链式调用(请参阅链式调用)。
下面的示例代码展示了如何使用 math.js。更多示例可在示例部分找到。
// functions and constants
math.round(math.e, 3) // 2.718
math.atan2(3, -3) / math.pi // 0.75
math.log(10000, 10) // 4
math.sqrt(-4) // 2i
math.pow([[-1, 2], [3, 1]], 2) // [[7, 0], [0, 7]]
// expressions
math.evaluate('12 / (2.3 + 0.7)') // 4
math.evaluate('12.7 cm to inch') // 5 inch
math.evaluate('sin(45 deg) ^ 2') // 0.5
math.evaluate('9 / 3 + 2i') // 3 + 2i
math.evaluate('det([-1, 2; 3, 1])') // -7
// chained operations
math.chain(3)
.add(4)
.multiply(2)
.done() // 14
下一步 #
要了解更多关于 math.js 的信息,请查阅可用的文档和示例。