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

FunctionCallDescription
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)Base 10 logarithm
lognlogn(a1, a2)Logarithm of a1 in base a2
sqrtsqrt(a1)Square root
ifif(a1, a2, a3)If a1 is true, a2, otherwise a3
maxmax(a1, a2, ..., a_n)Maximum argument
minmin(a1, a2, ..., a_n)Minimum argument
avgavg(a1, a2, ..., a_n)Average of the arguments
medianmedian(a1, a2, ..., a_n)Median of the arguments
roundround(a1)Round, higher at .5
randomrandom()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.