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.
Function | Arguments | Description |
---|---|---|
sin | sin(a1) | Sine |
cos | cos(a1) | Cosine |
asin | asin(a1) | Arcsine |
acos | acos(a1) | Arccosine |
tan | tan(a1) | Tangent |
cot | cot(a1) | Cotangent |
atan | atan(a1) | Arctangent |
acot | acot(a1) | Arccotangent |
loge | loge(a1) | Natural logarithm |
log10 | log10(a1) | Logarithm with base 10 |
logn | logn(a1, a2) | Logarithm |
sqrt | sqrt(a1) | Square root |
if | if(a1, a2, a3) | IF a1 IS true THEN a2 ELSE a3 |
max | max(a1, …, a_n) | Maximum |
min | min(a1, …, a_n) | Minimum |
avg | avg(a1, …, a_n) | Average |
median | median(a1, …, a_n) | Median |
round | round(a1) | Round |
random | random() | Generate a random double value between 0.0 and 1.0 |
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”.