Evaluating math formula from string

 

My question is very simple.

Imagine we have the following string:

string formula = "pow((1 + 3) * 0.7482, 0.5)";

Is it possible to calculate that formula which will be provided during run time as a string?

The result should be:

1.7299710980244727

Thanks!

 

You cannot evaluate strings in MQL. In other languages it's called eval(string) where the string may contain math or even commands. Unless you want to write a parser, which is a lot of work, you are limited to simple number conversions like StringToDouble().

If you want to write a parser, I suggest to use a set of simple commands similar to assembler. A command set could look like this: "c1=1; c2=3; c3=0.7482; c4=0.5; set c1; sum c2; mul c3; pow c4" where all operations are done with an internal accumulator, "set" assigns to it, and ci is any constant. Should be easy to parse. Or even simpler, "set 1; sum 3; mul 0.7482; pow 0.5". Just an idea. :D

 
cyberglassed: Is it possible to calculate that formula which will be provided during run time as a string?

Of course.

  1. You have to parse the string into tokens.
  2. Identify and priority the tokens.
  3. Convert numeric tokens to numbers.
  4. Execute the tokens correctly and get the result.
It is the final project to Compilers 101. Take the course and do the month long code.
 
cyberglassed:

My question is very simple.

Imagine we have the following string:

Is it possible to calculate that formula which will be provided during run time as a string?

The result should be:

Thanks!

try this out
https://www.mql5.com/en/code/303
Reason: