In my project to build a SPICE program, I ran across a problem; I need to be able to perform complex math from strings. This has already been done a thousand times before but finding a free, good parser isn't easy. So I decided to do this myself. This article will explain briefly the process I'm using to parse a complex math string.
Basic Process
- First check the string for incorrect characters. This can be done while performing step 2
- Define every character in the string as a type (ie. 0=operator, 1=real number, 2=imaginary number, 3=left parenthesis, 4=right parenthesis). Define this into a separate string. The reason you do this is to take in different number types (real, imaginary, scientific notation, etc.)
- Next separate the string into tokens to be evaluated separately. The most open parenthesis should be it's own token. (ie. str = "2*2j+(20+2j)^12" will turn into tokens "@1*@2+@3^@4") This is only an example. I doubt i'll have a string like this.
- Evaluate each token by recursion through the same function until it outputs a complex number. (a custom class)
- With a complex number for the tokens you can then evaluate in precedent order of functions.
- Output complex number
That's the quick and easy of it. I have only completed steps 1 and 2 so far. The rest will hopefully be completed in the week. Hope this is helpful...
No comments:
Post a Comment