How to use the parser function from mathjs

Find comprehensive JavaScript mathjs.parser code examples handpicked from public code repositorys.

2
3
4
5
6
7
8
9
10
// $ npm install mathjs
//

var mathjs = require('mathjs');
var integrate = require('../');
var parser = mathjs.parser();

parser.eval('f(x) = cos(1/x)/x');
var value = integrate(parser.get('f'), 0.01, 1, 0.001);
fork icon3
star icon23
watch icon10

+ 13 other calls in file

144
145
146
147
148
149
150
151
152
153
const node = math.parse('sqrt(x/x+1)')
node.toString() // returns 'sqrt((x / x) + 1)'
node.toTex() // returns '\sqrt{ {\frac{x}{x} }+{1} }'

// parser
const parser = math.parser()
// evaluate
parser.evaluate('sqrt(3^2 + 4^2)') // 5
// evaluate function
parser.evaluate('f(x, y) = x^y') // f(x, y)
fork icon0
star icon3
watch icon0

+ 6 other calls in file

10
11
12
13
14
15
16
17
18
19
20
// `include the math.js library
const math = require('mathjs')


class MathTool {
  constructor () {
    this.parser = math.parser()
    this.angleMode = 'deg'
    this.precision = 10
    this._initCustomFunction()
  }
fork icon2
star icon1
watch icon2

456
457
458
459
460
461
462
463
464
465
// remove backslash with whitespace
tmpData = tmpData.replace(/\\ /g, ' ')
tmpData = tmpData.replace(/\\frac{(\S+)}{(\S+)}/, '$1/$2')
// convert scientific notation
tmpData = tmpData.replace(/\\cdot/g, '*')
tmpData = tmpData.replace(/\^{\s*(\S+)\s*}/, '^($1)') // fix for math.parser()

var parsedToValUnit = this.constructor.parseToValueUnit(tmpData)

if (parsedToValUnit && parsedToValUnit[0]) {
fork icon0
star icon0
watch icon1

+ 91 other calls in file

99
100
101
102
103
104
105
106
107
108
```js
// load math.js
var math = require('mathjs');

// create a parser
var parser = math.parser();

// evaluate expressions
var a = parser.eval('sqrt(3^2 + 4^2)'); // a = 5
var b = parser.eval('sqrt(-4)');        // b = 2i
fork icon0
star icon0
watch icon2

+ 47 other calls in file