[No Extensions/OS] 🧮 Math Expression Parser with operations, brackets, and functions

🧮 Introduction

A project of mine that evaluates math expressions, with no extensions involved. It was surely one of the best I made as I learned a lot of fun algorithms on the way.

image

:white_check_mark: Whole numbers, decimals, constants (π, e), complex numbers (i)
:white_check_mark: Arithmetic operations/functions (addition, subtraction, multiplication, division, brackets, square root, n-th root, GCD, LCM)
:white_check_mark: Trigonometric functions (sin, cos, tan)
:white_check_mark: Rounding functions (round, ceil, floor)
:white_check_mark: List operations (min, max, mean, sum, product)


📚 Examples

image

Result: ±0.00001 (10^(-5))

image

image

image

image


🧩Blocks (754)


🧮 Complexities and notes

Time complexity: O(N)
Space complexity O(N)

This program has two catches:

  • The expression must be valid or the program may malfunction. For example, undefined functions will return 0.
  • Exponents must be surrounded in brackets, e.g. 2*5^6 2*(5^6), or else the expression will be treated as (2*5)^6. I'm still working on it, though this will raise the time complexity to O(N*E), with E being the number of exponent symbols.

📥Downloads

AIA:
MathParser.aia (22.0 KB)


All materials in this post are licensed under the CC BY-SA 4.0 International license. To credit the author, please include his name (Gordon Lu) and a link to the community post.

7 Likes

Stunning! :wink:

1 Like

That is very cool :wink: I love interpreters a lot, I had a lots of fun few years back (even now I do!) writing math interpreters, slowly introducing variables, functions etc, that turned into a whole language..

You'll definitely love this book if you give it some time: https://craftinginterpreters.com

It goes a little deep into how you should write interpreters, and a lot of concepts such as handling operator precedence (e.g. * and / should be parsed before + and -) etc.

3 Likes