calculate
Compute a mathematical formula
Definition
number calculate(string $expression, object $variables)
Computes a given mathematical formula using the provided variables.
Parameters
string $expression
A string representing a mathematical formula to be calculated. Consists of variables, named by the users, as well as operators and base functions.
Operators
- Addition:
+
- Subtraction:
–
- Multiplication:
*
- Division:
/
- Modulo:
%
- Exponentiation:
^
- Negation:
!
- Equality:
==
- Less than:
<
- Greater than:
>
- Less or equal to:
<=
- Greater or equal to:
>=
- Inequality:
!=
- Parentheses:
()
Base functions
Function | Call | 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) | Base 10 logarithm |
logn | logn(a1, a2) | Logarithm of a1 in base a2 |
sqrt | sqrt(a1) | Square root |
if | if(a1, a2, a3) | If a1 is true, a2, otherwise a3 |
max | max(a1, a2, ..., a_n) | Maximum argument |
min | min(a1, a2, ..., a_n) | Minimum argument |
avg | avg(a1, a2, ..., a_n) | Average of the arguments |
median | median(a1, a2, ..., a_n) | Median of the arguments |
round | round(a1) | Round, higher at .5 |
random | random() | Random float between 0 and 1 |
object $variables
An object where the keys represent variable names, and the values represent the values to be inserted into the formula in place of their respective variables.
Returns
number
The result of the formula.
Examples
{
intSum: calculate('a+b', {"a": 10, "b": 20}),
numStringSum: calculate('a+b', {"a": '10', "b": '20'}),
floatSum: calculate('a+b', {"a": 10.5, "b": 20}),
intSubtract: calculate('a-b', {"a": 10, "b": 20}),
addMultiply: calculate('(a+b)\_10', {"a": 10, "b": 20}),
sin: calculate('sin(a)\_3', {"a": 45}),
noVariables: calculate('(10+20)/10', null),
logn: calculate('logn(4, 2)', `null`),
round: calculate('round(1.5)', `null`),
nullArg: calculate('a+b', null), // Error
objArg: calculate('a+b', {}), // Error
stringSum: calculate('10+b', {"b": 'aSimpleString'}) // Error
}
{
"intSum": 30.0,
"numStringSum": 30.0,
"floatSum": 30.5,
"intSubtract": -100,
"addMultiply": 300.0,
"sin": 2.552710573602355,
"noVariables": 3.0,
"logn": 2.0,
"round": 2.0
}
Remarks
The variables must be provided even if the formula doesn't depend on any variables, like random() or (1+2). Note that you can simply pass null
in this case as the variable. Returns "NaN" on mathematically invalid input, like a negative number as an argument to the log function. Only numbers and strings with number formatting are accepted as arguments.
Updated about 1 year ago