How to use the parse function from mathjs

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

mathjs.parse is a method in the mathjs library that parses a mathematical expression string into a tree of nodes that represent the expression's structure.

9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
if(this.params.length) {
	pyquil += "\n";
	for(var i = 0; i < this.params.length; i++) {
		var globalParamName = this.params[i];

		var node = math.parse(globalParams[globalParamName]);
		var globalParamValue = node.toString({ handler: mathToStringHandler });

		pyquil += globalParamName + " = " + globalParamValue + "\n";
	}
fork icon43
star icon207
watch icon14

+ 3633 other calls in file

50
51
52
53
54
55
56
57
58
59
const visible = (text.match(INITIAL_OP_WITH_PARAGRAPH) || [])[1];
let paragraph = `<p>${sanitizeStyles(text)}</p>`;
if (visible) {
  // Parse AST for expression and check if outermost node/operation is of type "OperatorNode" (e.g. == >= != etc.)
  // Used to try to be smarter about whether a MathJS evaluation should be output or an if attribute
  const visibleTree = Math.parse(visible);
  if (visibleTree.type === 'OperatorNode') {
    text = text.replace('{{' + visible + '}}', '');
    paragraph = `<p if="${escapeXml(visible)}">${sanitizeStyles(text)}</p>`;
  }
fork icon25
star icon70
watch icon9

+ 9 other calls in file

How does mathjs.parse work?

mathjs.parse is a function in the Math.js library that takes a string as input and parses it into a Math.js expression tree, which can then be evaluated to obtain a numerical result or transformed in various ways. The parser recognizes a wide variety of mathematical expressions, including arithmetic operations, functions, variables, constants, matrices, and more.

23
24
25
26
27
28
29
30
31
32
33
34
  percent,
});


// const r = v => mathjs.rationalize(v);
// const a = mathjs.parse('4 x');
// const b = mathjs.parse('x 4');


const mo = (tree) => JSON.stringify(tree, null, '  ');
// // console.log('a:', mo(a));
// // console.log('b:', mo(b));
fork icon3
star icon4
watch icon0

+ 23 other calls in file

117
118
119
120
121
122
123
124
125
126
function equivalent(nodeA, nodeB) {
  return nodeA.toString() == nodeB.toString();
}

function parseExpression(expressionText) {
  return math.parse(expressionText); //.transform(compressExpression);
}

function compressExpression(node, path, parent) {
  return NODE.parenthesis.is(node) ? node.content : node;
fork icon1
star icon70
watch icon6

Ai Example

1
2
3
4
5
6
const math = require("mathjs");

const expression = "3 * x + 2";
const node = math.parse(expression);

console.log(node.toString());

In this example, we are parsing the mathematical expression "3 * x + 2" using mathjs.parse(), which returns an Abstract Syntax Tree (AST) representation of the expression. We then print out the AST using the toString() method.

15
16
17
18
19
20
21
22
23
  latex = latex.replace('=', '+') // Used to parse equations
  parsedMath = new AlgebraLatex().parseLatex(latex)
  parsedMath = parsedMath.toMath()
  console.log(parsedMath)

  parsedMath = math.parse(parsedMath)
} catch (e) {
  return []
}
fork icon12
star icon32
watch icon3

+ 3 other calls in file

139
140
141
142
143
144
145
146
147
148
// Parse
// ---

const basicParse = () => {
  // parse
  const node = math.parse('sqrt(x/x+1)')
  node.toString() // returns 'sqrt((x / x) + 1)'
  node.toTex() // returns '\sqrt{ {\frac{x}{x} }+{1} }'

  // parser
fork icon0
star icon3
watch icon1

+ 2 other calls in file

159
160
161
162
163
164
165
166
167
console.log("fitness", ind[3]);
console.log("phenotype", ind[1]);
var s = ind[1];
s = replaceAll(s, "x0", "x") // for human readers now
s = replaceAll(s, ".*", "*");
const node = math.parse(s);
console.log("latex", node.toTex());
console.log("simplified", math.simplify(s).toString())
   }
fork icon1
star icon0
watch icon0

+ 2 other calls in file

1
2
3
4
5
6
7
8
9
10
const stepThrough = require('./stepThrough');

function factorString(expressionString, debug=false) {
  let node;
  try {
    node = math.parse(expressionString);
  }
  catch (err) {
    return [];
  }
fork icon284
star icon0
watch icon66

13
14
15
16
17
18
19
20
21
22
const DERIVATIVE_H = 1e-15;
const SMALL_NUMBER = math.bignumber('1e-15');
const OPTIMIZATION_INTERMEDIATE_RATIO = 0.3819660112501051517954;

const compileFuncFromString = (func, variable) => {
    let temp = math.parse(func).compile();
    return x => {
        let scope = {};
        if (typeof variable === 'string')
            scope[variable] = x;
fork icon0
star icon0
watch icon5

+ 13 other calls in file

214
215
216
217
218
219
220
221
222
223
// provide a scope
var scope = {
    x: 3,
    a: 2
};
var node2 = math.parse('x^a', scope);
node2.eval(); // 9

// change a value in the scope and re-evaluate the node
scope.a = 3;
fork icon0
star icon0
watch icon2

+ 11 other calls in file

3
4
5
6
7
8
9
10
11
12
  number: 'BigNumber',
  precision: 64
})

const pvCode = math.parse('fv * e^-(r * t)').compile()
const pvdxCode = math.parse('-fv * t * e^-(r*t)').compile()
const pvmCode = math.parse('c*(1 + y/k)^-(k*t)').compile()
const couponPmtCode = math.parse('t * r / m * p').compile()
const newtRootCode = math.parse('x0 - y / dy').compile()
const stableCode = math.parse('abs(x1 - x0) <= theta').compile()
fork icon0
star icon0
watch icon1

+ 17 other calls in file

57
58
59
60
61
62
63
64
65
66
if (xInicial == "") {
  xInicial = sinValorInicial(funcion);
}
iteracion = 0;
xn = xInicial;
f = parse(funcion);
const simplified = simplify(f);
fPrima = parse(derivarFuncion(funcion));
const simplifiedPrima = simplify(fPrima);
bandera = true;
fork icon0
star icon0
watch icon0

+ 2 other calls in file

101
102
103
104
105
106
107
108
109
110
xu = 0;
bandera = true;
max = 0;
min = 0;
valorInicial = 0;
const f = parse(funcion);
const simplified = simplify(f);

while (bandera) {
  resultadoFuncion = simplified.evaluate({ x: valorInicial });
fork icon0
star icon0
watch icon0

33
34
35
36
37
38
39
40
41
42
texts[1] = texts[1].replace(/∓/g, '+');
text = '';
for(let i = 0; i < 2; i++)
{
    text += (i + 1) + ': ';
    const node = math.parse(texts[i]);
    const calculation = math.evaluate(node.toString());
    if(calculation == Infinity){text += '<a:FA_Sparkles:977507221166518322> **INFINITY** <a:FA_Sparkles:977507221166518322>';}
    else{text += calculation.toString();}
    text += '\n';
fork icon0
star icon0
watch icon1

+ 1215 other calls in file