Up Previous Next Title Page Index Contents

5.8.6 Math evaluate

To evaluate a mathematical expression use the template:
math '1+3*2' evaluate
which outputs 7. The expression between math and evaluate keywords forms the evaluated expression. The rules for forming the expression are:
Numbers
The number format in the input stream is integer, float, or scientific format 3e10. Leading zeroes are allowed (e.g. 001), and float must have an integer part (e.g. 0.3 not .3).

Operations

The operations are + - * / and ^ for power, all binary, and unary plus and minus. Also // (division without remainder) and \\ (modulo).
Precedence
Precedence is as normal: parentheses, ^ / * - +.

math '5+4*3^2' evaluate

outputs 41, i.e. 5 + (4 * (3 ^ 2))

math '3^2*4+5' evaluate

outputs 41, i.e. ((3 ^ 2) * 4) + 5).

Precedence of unary minus and plus is higher than exponentiation:

-2^-2 = (-2)^(-2), not -(2^-2)
Associativity
Binary operators are left associative, except ^ which is right associative:

100/10/5 outputs 2, i.e. (100 / 10) / 5

3-4-5 outputs -6, i.e. (3 - 4) - 5

4^3^2 outputs 262144, i.e. 4 ^ (3 ^ 2)
Output formats
Integers (3, unbounded range)

Fractions (3/4, unbounded range and precision. If you want to turn this into a float, 0.75, use a float as part of the calculation, e.g. 3/4.0)

Floats (3.0 or, if the absolute value is larger than 1,000,000 or smaller than 0.001, in scientific format 1.0e-4. Precision is 8 or 9 digits. Range is plus and minus 1.0e38 (an error will be raised if the range is exceeded).


Up Previous Next Title Page Index Contents