Expression Evaluator


Abstract:

This Program uses the transformation from infix notation to postfix notation to evaluate most of the mathematical expressions. it , it support most operators (+,-,*,/,%,^), functions from 0 to any number of parameters and also a user defined function by using delegate, also it support variables in the expression, it will generate a symbol table that can be updated at run time. Also this program demonstrate the use of DataGrid as normal Grid without any database connection.

Details:

All the code necessary for transform infix expression to postfix expression and evaluate the postfix expression is encapsulated in the "Function" class, also this class support variable which mean you can write expression like "num1 + num2", it automatic will generate the symbol table for it, and initialize all variable to zero by default.

The first member function that must be  called in the Function class is "Parse", which take the expression string as parameter and transfrom it to an a "ArrayList" of Symbol, and store it in the member variable "m_equation", the Symbol is a structure the contain information about any symbol which is the smallest element in any equation, it contain the following information:

m_name: the name of the symbol which may be ("num1", "+","cos","(","7",...etc).
m_type: the type of this symbol which is defined in the enumerator Type which may be (variable, value, operator, comma,...etc).
m_value: the value of that symbol valid only if it is variable or value. 

After that you must call the member function "Infix2Postfix", which transform the infix notation stored in m_equation to postfix notation and store it in m_postfix member variable, if the expression contain any variable, you can call the Variables property to get the symbol table as ArrayList of Symbol structure, this array will contains all variable type symbol only, after changing the value of any variable just call the "Variables" property again and put on it the updated symbol table, this property is both get and set.

After that you can call the member function "EvaluatePostfix" to evaluate the expression, the result will be stored as double in m_result member variable, which can be accessed by the property member "Result".

Also this Class have a number of defined function that can be used directly in any expression, this function are case sensitive and must be all small, the following are the built in function:

cos() 

Take a single parameter a raduis angle and return the "cos" of it.

sin()

Take a single parameter a raduis angle and return the "sin" of it.

tan()

Take a single parameter a raduis angle and return the "tan" of it.

cosh()

Take a single parameter a raduis angle and return the "cosh" of it.

sinh()

Take a single parameter a raduis angle and return the "sinh" of it.

tanh()

Take a single parameter a raduis angle and return the "tanh" of it.

ln()

Take a single parameter a number and return the "ln" of it, which is the logarithm of base "e".

log()

Take a single parameter a number and return the "log" of it, which is the logarithm of base "10".

logn()

Take a two parameters, the first is a number that we want to compute the logarithm of it, the second parameter is the base of the logarithm.

sqrt()

Take a single parameter number, and return the square root of it.

abs()

Take a single parameter number, and return absolute value of it.

acos()

Take a single parameter number, and return the "arc cos" of it.

asin()

Take a single parameter number, and return the "arc sin" of it.

atan()

Take a single parameter number, and return the "arc tan" of it.

exp()

Take a single parameter number, and return the exponention of it.

Also you can define your own functions, those functions can contain from zero to any number of parameters, to define your own functions, you must define a delegate function of the following type "EvaluateFunctionDelegate" this type is define in Function.cs, then call the "DefaultFunctionEvaluation" property member to set your delegate function, all the functions that you have defined in the delegate function, will be added to the built in function.

Also the variable "pi" is internally recognized as 3.14159265358979,and the variable "e" is internally recognized as 2.71828182845905, if any error happen whatever the error type, the Error property will return true and the Description of  the Error will be returned by the ErrorDescription property member.

Here some examples of how to use the Function class:           

//-- Example 1, Simple --
Function fn = new Function();
fn.Parse("1+2");
fn.Infix2Postfix();
fn.EvaluatePostfix();
double nResult = fn.Result;
//----------------------------------------------
//-- Example 2, How to use built in function --
Function fn = new Function();
fn.Parse("1+2*5-cos(pi)");
fn.Infix2Postfix();
fn.EvaluatePostfix();
double nResult = fn.Result;
//---------------------------------------------
//-- Example 3, How to use variable --
Function fn = new Function();
fn.Parse("x+2*y-cos(pi)");
fn.Infix2Postfix();
ArrayList var = fn.Variables;
foreach(Symbol sym in var)
{
if(sym..m_name == "x")
sym.m_value = 1;
else if(sym..m_name == "y")
sym.m_value = 5;
}
fn.Variables = var;
fn.EvaluatePostfix();
double nResult = fn.Result;
//-------------------------------------------------
//-- Example 4, How to use recursive function call --
Function fn = new Function();
fn.Parse("sin(cos(pi)*pi/2)");
fn.Infix2Postfix();
fn.EvaluatePostfix();
double nResult = fn.Result;
//-------------------------------------------------
The other part of the program is to demonstrate how to use the Function class, and also it
emonstrate how to use DataGrid as a normal Grid to show the symbol table without any
atabase connection, to use this program after compiling the program write any
athematic expression in the edit box then click parse, if the expression contain any variable, you can change the value of this variable in the DataGrid Control, after that click on Evaluate to see the result.
///
///This class Function use the transformation from infix notation to postfix notation to evalute most
///Mathematic expression, it support most operators (+,-,*,/,%,^), functions from 0 to any number of parameters
///and also a user defined function by using delegate, also it support variables in the expression, it will
///generate a symbol table that can be updated at run time.
///
using System;
using System.Collections;
namespace EB.Math
{
///
///
///
public enum Type{Variable,Value,Operator,Function,Result,Bracket,Comma,Error}
public struct Symbol
{
public string m_name;
public double m_value;
public Type m_type;
public override string ToString()
{
return m_name;
}
}
public delegate Symbol EvaluateFunctionDelegate(string name, params Object[] args);
public class Function
{
public double Result
{
get
{
return m_result;
}
}
public ArrayList Equation
{
get
{
return (ArrayList)m_equation.Clone();
}
}
public ArrayList Postfix
{
get
{
return (ArrayList)m_postfix.Clone();
}
}
public EvaluateFunctionDelegate DefaultFunctionEvaluation
{
set
{
m_defaultFunctionEvaluation = value;
}
}
public bool Error
{
get
{
return m_bError;
}
}
public string ErrorDescription
{
get
{
return m_sErrorDescription;
}
}
public ArrayList Variables
{
get
{
ArrayList var = new ArrayList();
foreach(Symbol sym in m_equation)
{
if((sym.m_type == Type.Variable) && (!var.Contains(sym)))
var.Add(sym);
}
return var;
}
set
{
foreach(Symbol sym in value)
{
for(int i=0;i0)
{
tpSym = (Symbol)tpStack.Pop();
while((tpSym.m_name != "(") && (tpSym.m_name != "[") && (tpSym.m_name != "{"))
{
m_postfix.Add(tpSym);
tpSym = (Symbol)tpStack.Pop();
}
}
}
else
{
if(tpStack.Count > 0)
{
tpSym = (Symbol)tpStack.Pop();
while((tpStack.Count != 0) && ((tpSym.m_type == Type.Operator) ||
(tpSym.m_type == Type.Function) || (tpSym.m_type == Type.Comma)) && (Precedence(tpSym) >= Precedence(sym)))
{
m_postfix.Add(tpSym);
tpSym = (Symbol)tpStack.Pop();
}
if(((tpSym.m_type == Type.Operator) || (tpSym.m_type == Type.Function) || (tpSym.m_type == Type.Comma)) && (Precedence(tpSym) >= Precedence(sym)))m_postfix.Add(tpSym);
else
tpStack.Push(tpSym);
}
tpStack.Push(sym);
}
}
while(tpStack.Count > 0)
{
tpSym = (Symbol)tpStack.Pop();
m_postfix.Add(tpSym);
}
}
public void EvaluatePostfix()
{
Symbol tpSym1, tpSym2, tpResult;
Stack tpStack = new Stack();
ArrayList fnParam = new ArrayList();
m_bError = false;
foreach(Symbol sym in m_postfix)
{
if((sym.m_type == Type.Value) || (sym.m_type == Type.Variable) ||(sym.m_type == Type.Result))
tpStack.Push(sym);
else if(sym.m_type == Type.Operator)
{
tpSym1 = (Symbol)tpStack.Pop();
tpSym2 = (Symbol)tpStack.Pop();
tpResult = Evaluate(tpSym2, sym, tpSym1);
if(tpResult.m_type == Type.Error)
{
m_bError = true;
m_sErrorDescription = tpResult.m_name;
return;
}
tpStack.Push(tpResult);
}
else if(sym.m_type == Type.Function)
{
fnParam.Clear();
tpSym1 = (Symbol)tpStack.Pop();
if((tpSym1.m_type == Type.Value) || (tpSym1.m_type == Type.Variable) || Sym1.m_type == Type.Result))
{
tpResult = EvaluateFunction(sym.m_name,tpSym1);
if(tpResult.m_type == Type.Error)
{
m_bError = true;
m_sErrorDescription = tpResult.m_name;
return;
}
tpStack.Push(tpResult);
}
else if(tpSym1.m_type == Type.Comma)
{
while(tpSym1.m_type == Type.Comma)
{
tpSym1 = (Symbol)tpStack.Pop();
fnParam.Add(tpSym1);
tpSym1 = (Symbol)tpStack.Pop();
}
fnParam.Add(tpSym1);
tpResult = EvaluateFunction(sym.m_name,fnParam.ToArray());
if(tpResult.m_type == Type.Error)
{
m_bError = true;
m_sErrorDescription = tpResult.m_name;
return;
}
tpStack.Push(tpResult);
}
else
{
tpStack.Push(tpSym1);
tpResult = EvaluateFunction(sym.m_name);
if(tpResult.m_type == Type.Error)
{
m_bError = true;
m_sErrorDescription = tpResult.m_name;
return;
}
tpStack.Push(tpResult);
}
}
}
if(tpStack.Count == 1)
{
tpResult = (Symbol)tpStack.Pop();
m_result = tpResult.m_value;
}
}
protected int Precedence(Symbol sym)
{
switch(sym.m_type)
{
case Type.Bracket:
return 5;
case Type.Function:
return 4;
case Type.Comma:
return 0;
}
switch(sym.m_name)
{
case "^":
return 3;
case "/":
case "*":
case "%":
return 2;
case "+":
case "-":
return 1;
}
return -1;
}
protected Symbol Evaluate(Symbol sym1, Symbol opr, Symbol sym2)
{
Symbol result;
result.m_name = sym1.m_name + opr.m_name + sym2.m_name;
result.m_type = Type.Result;
result.m_value = 0;
switch(opr.m_name)
{
case "^":
result.m_value = System.Math.Pow(sym1.m_value,sym2.m_value);
break;
case "/":
{
if(sym2.m_value > 0)
result.m_value = sym1.m_value / sym2.m_value;
else
{
result.m_name = "Divide by Zero.";
result.m_type = Type.Error;
}
break;
}
case "*":
result.m_value = sym1.m_value * sym2.m_value;
break;
case "%":
result.m_value = sym1.m_value % sym2.m_value;
break;
case "+":
result.m_value = sym1.m_value + sym2.m_value;
break;
case "-":
result.m_value = sym1.m_value - sym2.m_value;
break;
default:
result.m_type = Type.Error;
result.m_name = "Undefine operator: " + opr.m_name + ".";
break;
}
return result;
}
protected Symbol EvaluateFunction(string name, params Object[] args)
{
Symbol result;
result.m_name = "";
result.m_type = Type.Result;
result.m_value = 0;
switch(name)
{
case "cos":
if(args.Length == 1)
{
result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")";
result.m_value = System.Math.Cos(((Symbol)args[0]).m_value);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
case "sin":
if(args.Length == 1)
{
result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")";
result.m_value = System.Math.Sin(((Symbol)args[0]).m_value);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
case "tan":
if(args.Length == 1)
{
result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")";
result.m_value = System.Math.Tan(((Symbol)args[0]).m_value);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
case "cosh":
if(args.Length == 1)
{
result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")";
result.m_value = System.Math.Cosh(((Symbol)args[0]).m_value);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
case "sinh":
if(args.Length == 1)
{
result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")";
result.m_value = System.Math.Sinh(((Symbol)args[0]).m_value);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
case "tanh":
if(args.Length == 1)
{
result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")";
result.m_value = System.Math.Tanh(((Symbol)args[0]).m_value);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
case "log":
if(args.Length == 1)
{
result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")";
result.m_value = System.Math.Log10(((Symbol)args[0]).m_value);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
case "ln":
if(args.Length == 1)
{
result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")";
result.m_value = System.Math.Log(((Symbol)args[0]).m_value,2);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
case "logn":
if(args.Length == 2)
{
result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + "'" +
((Symbol)args[1]).m_value.ToString() + ")";
result.m_value = System.Math.Log(((Symbol)args[0]).m_value,((Symbol)args1]).m_value);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
case "sqrt":
if(args.Length == 1)
{
result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")";
result.m_value = System.Math.Sqrt(((Symbol)args[0]).m_value);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
case "abs":
if(args.Length == 1)
{
result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")";
result.m_value = System.Math.Abs(((Symbol)args[0]).m_value);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
case "acos":
if(args.Length == 1)
{

result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")";
result.m_value = System.Math.Acos(((Symbol)args[0]).m_value);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
case "asin":
if(args.Length == 1)
{
result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")";
result.m_value = System.Math.Asin(((Symbol)args[0]).m_value);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
case "atan":
if(args.Length == 1)
{
result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")";
result.m_value = System.Math.Atan(((Symbol)args[0]).m_value);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
case "exp":
if(args.Length == 1)
{
result.m_name = name + "(" + ((Symbol)args[0]).m_value.ToString() + ")";
result.m_value = System.Math.Exp(((Symbol)args[0]).m_value);
}
else
{
result.m_name = "Invalid number of parameters in: "+ name +".";
result.m_type = Type.Error;
}
break;
default:
if(m_defaultFunctionEvaluation != null)
result = m_defaultFunctionEvaluation(name,args);
else
{
result.m_name = "Function: "+ name +", not found.";
result.m_type = Type.Error;
}
break;
}
return result;
}
protected bool m_bError = false;
protected string m_sErrorDescription = "None";
protected double m_result = 0;
protected ArrayList m_equation = new ArrayList();
protected ArrayList m_postfix = new ArrayList();
protected EvaluateFunctionDelegate m_defaultFunctionEvaluation;
}
 


Similar Articles