Skip to main content

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.

Available functions

  • abs(x): absolute value
  • acos(x): arc cosine
  • asin(x): arc sine
  • atan(x): arc tangent
  • cbrt(x): cubic root
  • ceil(x): nearest upper integer
  • cos(x): cosine
  • cosh(x): hyperbolic cosine
  • exp(x): euler's number raised to the power (e^x)
  • floor(x): nearest lower integer
  • log(x): logarithmus naturalis (base e)
  • log10(x): logarithm (base 10)
  • log2(x): logarithm (base 2)
  • max(a, b): maximum of a and b
  • min(a, b): minimum of a and b
  • pow(x, y): raises x to the power of y
  • sin(x): sine
  • sinh(x): hyperbolic sine
  • sqrt(x): square root
  • tan(x): tangent
  • tanh(x): hyperbolic tangent
  • signum(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"
}
}
[
2.081172163164957,
3.8940986599363123,
2.8142547265173614
]

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
}
}
[
113,
114,
109
]

Specification

JSON schema

{
"type": "object",
"properties": {
"expr": {
"type": "string"
}
},
"required": [
"expr"
]
}