mirror of
https://github.com/josdejong/mathjs.git
synced 2026-01-25 15:07:57 +00:00
75 lines
2.0 KiB
Markdown
75 lines
2.0 KiB
Markdown
---
|
|
layout: default
|
|
---
|
|
|
|
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
|
|
|
|
<h1 id="function-parser">Function parser <a href="#function-parser" title="Permalink">#</a></h1>
|
|
|
|
Create a `math.Parser` object that keeps a context of variables and their values, allowing the evaluation of expressions in that context.
|
|
|
|
|
|
<h2 id="syntax">Syntax <a href="#syntax" title="Permalink">#</a></h2>
|
|
|
|
```js
|
|
math.parser()
|
|
```
|
|
|
|
<h3 id="parameters">Parameters <a href="#parameters" title="Permalink">#</a></h3>
|
|
|
|
Parameter | Type | Description
|
|
--------- | ---- | -----------
|
|
|
|
|
|
<h3 id="returns">Returns <a href="#returns" title="Permalink">#</a></h3>
|
|
|
|
Type | Description
|
|
---- | -----------
|
|
Parser | Parser
|
|
|
|
|
|
<h3 id="throws">Throws <a href="#throws" title="Permalink">#</a></h3>
|
|
|
|
Type | Description
|
|
---- | -----------
|
|
|
|
|
|
<h2 id="examples">Examples <a href="#examples" title="Permalink">#</a></h2>
|
|
|
|
```js
|
|
const parser = new math.parser()
|
|
|
|
// evaluate expressions
|
|
const a = parser.evaluate('sqrt(3^2 + 4^2)') // 5
|
|
const b = parser.evaluate('sqrt(-4)') // 2i
|
|
const c = parser.evaluate('2 inch in cm') // 5.08 cm
|
|
const d = parser.evaluate('cos(45 deg)') // 0.7071067811865476
|
|
|
|
// define variables and functions
|
|
parser.evaluate('x = 7 / 2') // 3.5
|
|
parser.evaluate('x + 3') // 6.5
|
|
parser.evaluate('f(x, y) = x^y') // f(x, y)
|
|
parser.evaluate('f(2, 3)') // 8
|
|
|
|
// get and set variables and functions
|
|
const x = parser.get('x') // 3.5
|
|
const f = parser.get('f') // function
|
|
const g = f(3, 2) // 9
|
|
parser.set('h', 500)
|
|
const i = parser.evaluate('h / 2') // 250
|
|
parser.set('hello', function (name) {
|
|
return 'hello, ' + name + '!'
|
|
})
|
|
parser.evaluate('hello("user")') // "hello, user!"
|
|
|
|
// clear defined functions and variables
|
|
parser.clear()
|
|
```
|
|
|
|
|
|
<h2 id="see-also">See also <a href="#see-also" title="Permalink">#</a></h2>
|
|
|
|
[evaluate](evaluate.html),
|
|
[compile](compile.html),
|
|
[parse](parse.html)
|