命令行界面 (CLI) #

当通过 npm 全局安装 math.js 时,可以在命令行中使用其表达式解析器。要全局安装 math.js

$ npm install -g mathjs

通常,全局安装需要管理员权限(在命令前加上 sudo)。安装后,可以通过命令行使用 mathjs 应用程序

$ mathjs
> 12 / (2.3 + 0.7)
4
> 12.7 cm to inch
5 inch
> sin(45 deg) ^ 2
0.5
> 9 / 3 + 2i
3 + 2i
> det([-1, 2; 3, 1])
-7

命令行界面可用于打开提示符、执行脚本或管道输入/输出流

$ mathjs                                 # Open a command prompt
$ mathjs script.txt                      # Run a script file, output to console
$ mathjs script1.txt script2.txt         # Run two script files
$ mathjs script.txt > results.txt        # Run a script file, output to file
$ cat script.txt | mathjs                # Run input stream, output to console
$ cat script.txt | mathjs > results.txt  # Run input stream, output to file

您还可以使用 --tex--string 选项来从表达式创建 LaTeX 或清理表达式

$ mathjs --tex
> 1/2
\frac{1}{2}
$ mathjs --string
> (1+1+1)
(1 + 1 + 1)

要更改括号选项,请使用 --parenthesis= 标志

$ mathjs --string --parenthesis=auto
> (1+1+1)
1 + 1 + 1
$ mathjs --string --parenthesis=all
> (1+1+1)
(1 + 1) + 1

命令行调试 (REPL) #

该库还通过 bin/repl.js 提供了一个 REPL(Read Evaluate Print Loop),它在 Node.js 命令行环境中加载 mathjs。您可以直接启动它(./bin/repl.js)或通过 node 启动(node bin/repl.js)。

您可以使用 [ctrl]-[C] 或 [ctrl]-[D] 退出。

$ ./bin/repl.js 
> math.parse('1+1')
{ op: '+',
  fn: 'add',
  args: 
   [ { value: '1', valueType: 'number' },
     { value: '1', valueType: 'number' } ] }
> 
Fork me on GitHub