This is a basic math parser that can parse mathematical expressions.
Parses a variety of mathematical expressions, including:
-
Integers
(0, 1, 5, -7)
, Floats(3.14159, 2.7, 0.5)
-
Basic arithmetic operations
(+, -, \*, /, \*\*, //, %)
-
Constants
PI, TAU, NAN, E, INF
-
Comparison operators
(==, !=, <, >, <=, >=)
-
Parentheses for grouping
-
Mathematical functions
(sin, cos, tan, abs, sqrt, log, fact, gcd, lcm, xor, int, float, min, max)
First, install it with:
pip install parsematic
Import the MathParser class:
from math_parser import MathParser
Create a MathParser instance:
parser = MathParser()
Use the parse() method to parse and evaluate an expression:
result = parser.parse("2 + 3 * (4 - 1)")
print(result) # Output: 11
Or, use it from the command line
python -m parsematic "2 + 3 * (4 - 1)"
Supported Operators:
- Arithmetic operators:
+, -, \_, / (true division), // (floor division), \*\* (exponentiation), % (modulo)
- Comparison operators:
==, !=, <, >, <=, >=
- Supported Functions
sin, cos, tan, abs, sqrt, log, fact (factorial), gcd (greatest common divisor), lcm (least common multiple), xor (bitwise exclusive or), int, float (type conversions), min, max
The parser will raise exceptions for invalid syntax or unsupported operations.
The parser currently does support constants or user-defined functions (although you have to modify MathFunc.funcs). (but not variables within the parser itself)
Pull requests are welcome!