parsing of mathematical expressions

后端 未结 5 1472
春和景丽
春和景丽 2020-12-14 04:44

(in c90) (linux)

input:

sqrt(2 - sin(3*A/B)^2.5) + 0.5*(C*~(D) + 3.11 +B)
a
b   /*there are values for a,b,c,d */
c
d

input:

<
5条回答
  •  渐次进展
    2020-12-14 04:58

    Possibly the easiest thing to do is use an embedded language like Lua or Python, for both of which the interpreter is written in C. Unfortunately, if you go the Lua route you'll have to convert the binary operations to function calls, in which case it's likely easier to use Python. So I'll go down that path.

    If you just want to output the result to the console this is really easy and you won't even have to delve too deep in Python embedding. Since, then you only have to write a single line program in Python to output the value.

    Here is the Python code you could use:

    exec "import math;A=;B=;C=;D=;print ".replace("^", "**").replace("log","math.log").replace("ln", "math.log").replace("sin","math.sin").replace("sqrt", "math.sqrt").replace("cos","math.cos")
    

    Note the replaces are done in Python, since I'm quite sure it's easier to do this in Python and not C. Also note, that if you want to use xor('^') you'll have to remove .replace("^","**") and use ** for powering.

    I don't know enough C to be able to tell you how to generate this string in C, but after you have, you can use the following program to run it:

    #include 
    
    int main(int argc, char* argv[])
    {
      char* progstr = "...";
      Py_Initialize();
      PyRun_SimpleString(progstr);
      Py_Finalize();
      return 0;
    }
    

    You can look up more information about embedding Python in C here: Python Extension and Embedding Documentation

    If you need to use the result of the calculation in your program there are ways to read this value from Python, but you'll have to read up on them yourself.

提交回复
热议问题