Calculate

Executes a given mathematical formula using the provided variables.

Syntax

number calculate(string $expression, object $variables)

Note: A variable can only be of type: number.

Parameters

$expression: The mathematical formula to calculate. Must be a string value. A list of available mathematical operators is provided below.
$variables: The variables or numbers to feed into the $expression formula. Must be an object containing keys and values for all variables used in $expression.

Example

{
    "inputVariables": {
        "a": 10,
        "b": 20
    }
}
{
    result: calculate('a+b', inputVariables)
}
{
    "result": 30.0
}

In this example, no sample data is needed as the data is defined the variables of the function. The $expression is defined to add the value of two variables “a” and “b”. The variables are defined to have values of 10 and 20 respectively, thus the sum of the variables is 30.

Notes

Available mathematical operators

These are the operators that can be used to construct the $expression to be calculated.

  • Addition: +
  • Subtraction: –
  • Multiplication: *
  • Division: /
  • Prioritisation: ( )
  • Modulo: %
  • Exponentiation: ^
  • Negation: !

Base functions

These base functions are also available and potentially helpful when using the calculate function.

FunctionArgumentsDescription
sinsin(a1)Sine
coscos(a1)Cosine
asinasin(a1)Arcsine
acosacos(a1)Arccosine
tantan(a1)Tangent
cotcot(a1)Cotangent
atanatan(a1)Arctangent
acotacot(a1)Arccotangent
logeloge(a1)Natural logarithm
log10log10(a1)Logarithm with base 10
lognlogn(a1, a2)Logarithm
sqrtsqrt(a1)Square root
ifif(a1, a2, a3)IF a1 IS true THEN a2 ELSE a3
maxmax(a1, …, a_n)Maximum
minmin(a1, …, a_n)Minimum
avgavg(a1, …, a_n)Average
medianmedian(a1, …, a_n)Median
roundround(a1)Round
randomrandom()Generate a random double value
between 0.0 and 1.0
Base functions

Decimal separator

Decimal separator is a dot, and not a comma as in some regions of the world. i.e. “5.8” rather than “5,8”.