Evaluate Mathematical Function from String [closed

2019-01-13 13:57发布

Can you give me some ideas about how can I make a simple mathematical expression parser in C?

User enters a mathematical function in a string and from the string I want to create the function in C. eg. x + sin(2*x)

-> return x + sin(2x);

Thanks in advance.

标签: c parsing math
4条回答
【Aperson】
2楼-- · 2019-01-13 14:37

One way to do it is to use reverse polish notation for the expressions and a stack for the operands. Some quick pseudo-code:

if element is operand
     push in stack
else if element is operation
     pop last 2 elements
     perform operation
     push result in stack

Repeat till end of expression. Final result is the only element in stack.

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-13 14:42

You can parse the expression based "Shunting-Yard Algorithm" http://en.wikipedia.org/wiki/Shunting-yard_algorithm. You will need to extend to handle the function calls such as sin, cos etc...

查看更多
贼婆χ
4楼-- · 2019-01-13 14:47

This is not a simple thing to do at all, in face, it's a hard thing. You need a full grammar parser, combined with pre-defined constants/functions (sin, log, pi, etc).

If you have no extensive previous experience with C I would disrecommend doing this, but if you really want to do this look at recursive descent parsing which is arguably the easiest way to do this (without putting a burden on the user, like reverse polish notation).

Last but not least you say you want to create a C function from the user-generated input. This is almost always a wrong thing to do - generating code from user input, instead the easiest approach is pre-processing to create a intermediate representation that can be efficiently executed.

查看更多
Animai°情兽
5楼-- · 2019-01-13 14:50

Writing an expression parser and evaluator is one of the usual examples used when discussions parser writing techniques. For example you could look the documentation for flex/bison or lex/yacc. That will have examples of constructing parsers/expression evaluators.

查看更多
登录 后发表回答