Expression Engine
eval() takes an arithmetic expression as a string and works it out with
Decimal arithmetic. It is the same engine that drives the decimo CLI
calculator:
from decimo import eval
print(eval("100 + e * pi"))
# 108.53973422267356706546355086954657449503488853577
print(eval("sqrt(2) + 1/3", precision=30))
# 1.74754689570642838213502205754
The result is rounded to precision significant digits, 50 by default, with
rounding_mode, half-even by default:
print(eval("1/3", precision=20))
# 0.33333333333333333333
print(eval("1/3", precision=5, rounding_mode=ROUND_CEILING))
# 0.33334
What you can write
The operators are +, -, *, /, ^ (power), a unary minus or plus,
and parentheses. A unary minus binds looser than ^, as in Python: -2^2 is
-4. The constants are pi and e. The functions are sqrt, cbrt,
root(x, n), ln, log(x, base), log10, exp, sin, cos, tan, cot,
csc, and abs.
Names are case-sensitive: pi is the constant, PI is an unknown identifier.
(The CLI lower-cases each line before it reaches the engine, which is why PI
works there but not here.) Line breaks count as whitespace, so an expression
can span several lines:
print(eval("""
100 + 2 * 3
""")) # 106
Variables
Pass a Dict and the expression can refer to your own values. Any identifier
that is not a built-in constant or function is looked up there:
from std.collections import Dict
var vars = Dict[String, Decimal]()
vars["x"] = Decimal.from_string("10")
vars["y"] = Decimal.from_string("3")
print(eval("x^2 + y", variables=vars)) # 103
Errors
A syntax error, an unknown name, a division by zero, or a domain error raises, and the message says where in the expression it went wrong:
try:
_ = eval("1 / 0")
except e:
print(e) # Error at position 2: division by zero
The individual stages
eval() tokenizes, parses to reverse Polish notation, and evaluates. The three
stages are exported as well, in case you want to look at the tokens or the RPN
form:
from decimo.expression import tokenize, parse_to_rpn, evaluate_rpn
var rpn = parse_to_rpn(tokenize("1 + 2 * 3"))
print(evaluate_rpn(rpn^, precision=50)) # 7
evaluate() is an alias of eval().