Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating mathematical expressions

Tags:

c

parsing

I am looking for an algorithm that I can use to evaluate mathematical expressions. I've seen a few questions on SO that are simmilar but the answers are C#/Delphi or python specific. I need to write the algorithm in C :)

The problem I am trying to solve is given a user input like

3*(2*x + 1)/x

I can evaluate the expression for any value of x.

What algorithms are available to do this? If you would like to suggest a library that already does this, then I would prefer a C library

Thank you

like image 898
hhafez Avatar asked Jul 19 '09 23:07

hhafez


2 Answers

The algorithm you need here is the Shunting Yard Algorithm.

This allows you to convert an in-fix expression into Reverse Polish notation, which is quite simple to evaluate programatically.

The Shunting Yard Algorithm is quite involved, but my experiences is that you can code it up just as its written and it all works - you don't have to go to the trouble of analysing it.

like image 21
Andrew Shepherd Avatar answered Sep 18 '22 15:09

Andrew Shepherd


I asked Google for "recursive descent expression parser" (I don't blame you for not knowing what to look for) and found Parsing Expressions by Recursive Descent which provides an introduction to some useful parsing techniques.

Also, the Wikipedia article on Recursive descent parser includes a fairly complete example in C.

like image 56
Greg Hewgill Avatar answered Sep 21 '22 15:09

Greg Hewgill