Solving user-defined variable equation

Responses to C, Python, C ++ or Javascript would be greatly appreciated. I read several books, made all the examples. Now I would like to write a simple program. But I have already encountered the following obstacle:

I intend to accept the equation from the user and store it in a variable, For example:

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

And then compute the given expression for a specific X value. Something like this:

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

Any ideas? For life, I cannot understand this. Adding to my disappointment, the solution is probably very simple. Thank you in advance.

+8
c variables equation solver
source share
3 answers

There is no easy way to do this in C, but I think muParser may be useful to you, it is written in C ++, but it has a C binding. ExprTk is also an option, but it seems that it is only C ++, on the plus side it is much easier to get interesting results.

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

+11
source share

In compiled languages ​​such as C, C ++ or Java, there is no easy way to do this - you basically have to rewrite the entire compiler (or use an external library with an interpreter). This is just 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 perform functions such as call functions with side effects.

0
source share

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

0
source share

All Articles