Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
New MS SQL 2008 Available - DiscountASP.NET
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » General » Expression Evaluator

Expression Evaluator

This program uses the transformation from infix notation to postfix notation to evaluate most of the mathematical expressions.

Technologies: .NET 1.0/1.1,Visual C# .NET
Total downloads : 220
Total page views :  11560
Rating :
 3/5
This article has been rated :  1 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
FuncEvaluatorCode.zip
 
ArticleAd
Become a Sponsor



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;
}
 


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Emad Barsoum
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
FuncEvaluatorCode.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Negative numbers error on FunctionsAlejandro8/23/2007
When i try to evaluate exp(-x) or sin(-x) i receive the error: "Stack empty" do you know how to solve this? Thanks
Reply | Email | Delete | Modify | 
 
 
Re: Negative numbers error on FunctionsBlagovest11/15/2007
The evaluator implemented in this article is good only for educational purposes. It doesn't evaluate sin(-x) properly because it doesn't consider unary operators. For a really versatile and customizable infix evaluator check out http://dotscript.com/Products/ExpressionEvaluator
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved