Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best and shortest way to evaluate mathematical expressions

There are many algorithms to evaluate expressions, for example:

  1. By Recursive Descent
  2. Shunting-yard algorithm
  3. Reverse Polish notation

Is there any way to evaluate any mathematical expression using C# .net reflection or other modern .net technology?

like image 373
Arsen Mkrtchyan Avatar asked Sep 17 '09 10:09

Arsen Mkrtchyan


People also ask

How do you evaluate a mathematical expression?

To evaluate an algebraic expression, you have to substitute a number for each variable and perform the arithmetic operations. In the example above, the variable x is equal to 6 since 6 + 6 = 12. If we know the value of our variables, we can replace the variables with their values and then evaluate the expression.

What is an expression explain the evaluation of expression with example?

An expression is a sequence of operands and operators that reduces to a single value. For example, the expression, 10+5 reduces to the value of 15.

Which one is the basic method to evaluate an operator?

The evaluation operator (=) EQUAL SIGN is used to evaluate a variable, function, or expression numerically. The Boolean equal to operator (=) CTRL+EQUAL SIGN is used to evaluate the equality condition in a Boolean statement. It is also used for programming, solving, and in symbolic equations.


1 Answers

Further to Thomas's answer, it's actually possible to access the (deprecated) JScript libraries directly from C#, which means you can use the equivalent of JScript's eval function.

using Microsoft.JScript;        // needs a reference to Microsoft.JScript.dll
using Microsoft.JScript.Vsa;    // needs a reference to Microsoft.Vsa.dll

// ...

string expr = "7 + (5 * 4)";
Console.WriteLine(JScriptEval(expr));    // displays 27

// ...

public static double JScriptEval(string expr)
{
    // error checking etc removed for brevity
    return double.Parse(Eval.JScriptEvaluate(expr, _engine).ToString());
}

private static readonly VsaEngine _engine = VsaEngine.CreateEngine();
like image 154
LukeH Avatar answered Oct 03 '22 06:10

LukeH