Skip to content

Commit 301d61d

Browse files
authored
Merge pull request #51 from gingrspacecadet/patch-1
Implement math functions in expression evaluator
2 parents e2db89f + ebde8d8 commit 301d61d

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

cogs/counting.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
)
1414
import ast
1515
import operator
16+
import math
1617
import asyncio
1718
import time
1819
from typing import Optional
@@ -273,6 +274,36 @@ def safe_eval(self, expr):
273274
ast.USub: operator.neg
274275
}
275276

277+
constants = {
278+
"e": math.e,
279+
"pi": math.pi,
280+
"tau": math.tau,
281+
}
282+
283+
functions = {
284+
"log": math.log,
285+
"log10": math.log10,
286+
"sqrt": math.sqrt,
287+
"factorial": math.factorial,
288+
"ceil": math.ceil,
289+
"floor": math.floor,
290+
"trunc": math.trunc,
291+
"sin": math.sin,
292+
"cos": math.cos,
293+
"tan": math.tan,
294+
"asin": math.asin,
295+
"acos": math.acos
296+
"atan": math.atan,
297+
"degrees": math.degrees,
298+
"radians": math.radians,
299+
"sinh": math.sinh,
300+
"cosh": math.cosh,
301+
"tanh": math.tanh,
302+
"asinh": math.asinh,
303+
"acosh": math.acosh,
304+
"atanh": math.atanh,
305+
}
306+
276307
def eval_node(node):
277308
if isinstance(node, ast.Constant):
278309
if isinstance(node.value, (int, float)):
@@ -291,6 +322,16 @@ def eval_node(node):
291322
op = type(node.op)
292323
if op in operators:
293324
return operators[op](eval_node(node.operand))
325+
elif isinstance(node, ast.Call):
326+
if isinstance(node.func, ast.Name):
327+
if node.func.id in functions:
328+
args = [eval_node(a) for a in node.args]
329+
return functions[node.func.id](*args)
330+
331+
elif isinstance(node, ast.Name):
332+
if node.id in constants:
333+
return constants[node.id]
334+
raise TypeError(f"Unknown identifier {node.id}")
294335
raise TypeError("Unsupported type")
295336

296337
try:

0 commit comments

Comments
 (0)