Math functions
math
Commentary
added in 0.7.3
Evaluates an infix mathematical string expression. This is handy if you have a long formula and don't want to write out nested ShadowTraffic function calls. You can access variables directly by name.
In other words, you can write this:
{
"_gen": "math",
"expr": "(2 + 4) * 3"
}
Instead of this:
{
"_gen": "multiply",
"args": [
{
3,
{
"_gen": "add",
"args": [
2, 4
]
}
}
]
}
Expressions are parsed and compiled ahead of time, meaning performance should be similar to using the rest of ShadowTraffic's math functions directly.
An expression may contain the names of local identifiers to isolate variable usage. 1
Available functions
abs(x)
: absolute valueacos(x)
: arc cosineasin(x)
: arc sineatan(x)
: arc tangentcbrt(x)
: cubic rootceil(x)
: nearest upper integercos(x)
: cosinecosh(x)
: hyperbolic cosineexp(x)
: euler's number raised to the power (e^x)floor(x)
: nearest lower integerlog(x)
: logarithmus naturalis (base e)log10(x)
: logarithm (base 10)log2(x)
: logarithm (base 2)max(a, b)
: maximum ofa
andb
min(a, b)
: minimum ofa
andb
pow(x, y)
: raisesx
to the power ofy
sin(x)
: sinesinh(x)
: hyperbolic sinesqrt(x)
: square roottan(x)
: tangenttanh(x)
: hyperbolic tangentsignum(x)
: signum function
Examples
Calculating constants
Use expr
to supply a math expression. Use any of the available functions listed above with arbitrary nesting.
{
"_gen": "math",
"expr": "2 + (log(4) * cos(10))"
}
[
0.8367998706650697
]
Using variables
Reference variables by their name. In this example the values a
and b
from the vars
section. Only numerically-typed variables are available for use. Non-numeric variables can't be referenced.
{
"topic": "sandbox",
"vars": {
"a": {
"_gen": "uniformDistribution",
"bounds": [
5,
10
]
},
"b": {
"_gen": "uniformDistribution",
"bounds": [
2,
3
]
}
},
"value": {
"_gen": "math",
"expr": "a / b"
}
}
[
3.6154520911368606,
2.2044545904003754,
2.0709688375302355
]
Returning integers
By default, math
will return floating point numbers. You can trim them down, even down to integers, using the decimals
function modifier.
{
"topic": "sandbox",
"vars": {
"a": {
"_gen": "normalDistribution",
"mean": 20,
"sd": 3
},
"b": {
"_gen": "uniformDistribution",
"bounds": [
5,
6
]
}
},
"value": {
"_gen": "math",
"expr": "a * b",
"decimals": 0
}
}
[
106,
57,
121
]
Referring to local names
Use names
to make a map of identifiers to expressions. These identifiers can be used inside of expr
and are generally useful for destructuring an object to put specific values into a string.
{
"topic": "sandbox",
"vars": {
"a": {
"b": {
"_gen": "normalDistribution",
"mean": 4,
"sd": 2
}
}
},
"value": {
"_gen": "math",
"expr": "c * 2",
"names": {
"c": {
"_gen": "var",
"var": "a",
"path": [
"b"
]
}
}
}
}
[
11.050660417976568,
6.039723154354938,
10.516769175350397
]
Specification
JSON schema
{
"type": "object",
"properties": {
"expr": {
"type": "string"
},
"names": {
"type": "object"
}
},
"required": [
"expr"
]
}