9

Answers in C, Python, C++ or Javascript would be very much appreciated. I've read a few books, done all the examples. Now I'd like to write a simple program. But, I already ran into the following roadblock:

My intention is to take an equation from the user and save it in a variable, For example:

-3*X+4 or pow(2,(sin(cos(x))/5))       >  [In valid C Math syntax]

And then calculate the given expression for a certain X-Value. Something like this:

printf("%g", UserFunction(3.2))   // Input 3.2 for X in User's Function and Print Result

Any ideas? For the life of me, I can't figure this out. Adding to my frustration, the solution is likely a very simply one. Thank you in advance.

user2388026
  • 135
  • 1
  • 5

3 Answers3

13

There isn't a simple way to do this in C but I think muParser may be useful to you, it is written in C++ but has C binding. ExprTk is also an option but looks like it is C++ only, on the plus side it looks much easier to get interesting results with.

Another option may be the Expression Evaluation which is part of Libav. It is in C and the eval.h header has some good descriptions of the interface.

Shafik Yaghmour
  • 143,425
  • 33
  • 399
  • 682
0

In compiled languages like C, C++, or Java there is no easy way to do this--you basically have to rewrite a whole compiler (or use an external library with an interpreter). This is only trivial in "scripting" languages like Python and Javascript, which have a function (often called "eval()") that evaluates expressions at runtime. This function is often dangerous, because it can also do things like call functions with side effects.

Lee Daniel Crocker
  • 12,296
  • 1
  • 24
  • 47
  • Thank you for your answer, Mr. Crocker. It looks like I'm in way over my head. My idea was to write a simple program to approximate an integral from a to b using Simpson's and Trapezoid rule. I would then solve the function for the appropriate x-values determined by the length and n, then multiply the answers by the appropriate coefficients, .... But it all depends on being able to calculate the user's function for a given X. So it seems I will have to use a simpler language. Thanks again. – user2388026 May 16 '13 at 02:16
  • Couldn't this be done by implementing a sudo try-catch in C, like described here http://stackoverflow.com/questions/10586003/try-catch-statements-in-c? – user3282276 Sep 29 '14 at 05:16
0

Ffmpeg/libav has a nice simple function evaluator you could use.

R.. GitHub STOP HELPING ICE
  • 195,354
  • 31
  • 331
  • 669