EXPRESSION PARSER

  Try Graphing and Math Software  
  Description:
  Expression Parser is a general purpose utility that may be invoked with a Java program to evaluate mathematical expressions. Such a utility may come in handy when mathematical expressions are entered by program user at runtime that need evaluation. For example, say you are writing a graphing utility which will get input functions from users. To evaluate these functions, you require a parser that will check the grammar of the expression and evaluate it to a numerical answer.

An expression may be of the following forms:

  1. sin(x^2) + cos(pi)
  2. x^3 - 2*x*y + 5
  3. (x^2-4)/(x-2)
  4. 22 + 37 * 2.0 / 5
  5. etc etc

Whether you are writing a console application, an applet or JSP; our utility will make your job easier. 

 
     
  Installation:  
1. Download the following two file.

2. Check to see if a folder titled classes exists under jre subfolder found under the location where Java Development Kit  is installed.

Under Windows XP, the jre folder may have the following path C:\j2sdk1.4.0\jre

If the classes folder already exists under jre, simply copy the two files in it, otherwise create a folder titled classes below jre and copy the two files in it.

3. Download the Test.java and Test.class files and store them in folder called test at root such as c:\test

4. You need to make sure CLASSPATH variable is pointing to the classes and test folders..

To do this under MS Windows, click on Start Menu > Control Panel
Double Click the System icon. On the Advanced tab, Click on the Environment Variables button

environment

 

 
  On this page, check if you can find a variable titled CLASSPATH in the list titled System varibles. If yes, highlight the CLASSPATH and click Edit button.

Append the path to classes and test folders at the end of the string click OK.

Close the System Properties Dialog by clicking on OK.

environment
 
     
  5. If the CLASSPATH variable does not exist in the list, click on New

In Variable Name box, type CLASSPATH
In Variable Value box, type C:\<jdk folder>\jre\classes;c:\test

where <jdk folder> is the location of Java Development Kit
addclass

 
Usage  
 

EvaluateExpr has a public static method called Evaluate( ) with the following signature

public static double Evaluate(String line, double x, double y, RefString Current, RefString Success, RefString Complex)

Following is a list of its arguments:

Argument

Data Type

Description

line String The expression to be evaluated is passed to this argument as of String type.
x double If the expression contains a variable x, its value is passed as of type double. Provide a default value of 0, in case the expression does not contain variable called x
y double If the expression contains a variable y, its value is passed as of type double. Provide a default value of 0, in case the expression does not contain variable called y

Current

RefString In Java, String objects passed to a function do not pass a value back to the calling method. Thus I created a type RefString which has a variable of type String that could be used to pass value to the calling method. RefString has a getRefString( ) and setRefString( ) properties that you can use to read or write to the String data member.

If the expression contained no errors and Evaluate method computed the correct result, Current will pass back the string value "$" . 

Success RefString Along with checking Current, you should check the value of Success to make sure Evaluate executed correctly. In case of erroneous result, Success would contain the error message. In case of successful evaluation of expression, Success will contain the string "ok".

Thus you need to check , after execution of Evaluate, Current has a value of "$" and Success has a value of "ok". If Current and Success do not contain these values, then the expression you passed to Evaluate had a syntax error.

Complex RefString It may be that expression you passed was evaluated to a value that was not a real number. As in the case of square root of a negative number or natural log of negative numbers. If its one of these situations, Current will contain "$" and Success will contain "ok", yet the results of the expression will be a NaN "Not a Number". Complex will contain a value of "true" in this case. If the result of the evaluated expression was a real number, Complex will contain a value of "false".
 
     
  Syntax of Expression

For Operator / Function

You Should use

Example

Addition

+ 2+13
Subtraction - 15.2-5.5
Unary Minus - -x
Multiplication * x*15
Division (Real) / 15/2.5
Exponentiation ^ x^2
( ) ( ) 2 * ( 3 + 5 )
Arc Tangent atan( ) atan( 3.2 )
Tangent tan ( ) tan ( x )
Tangent Hyperbolic tanh ( ) tanh( x^2)
Arc Cosine acos ( ) acos( pi )
Cosine cos( ) cos( x ) ^ 2
Cosine Hyperbolic cosh ( ) cosh(2)
Arc Sine asin( ) asin( x + 2)
Sine sin( ) sin( pi /2 )
Sine Hyperbolic sinh( ) sinh( 2.0 )
Absoulte value abs( ) abs( -3.57 )
Natural log ln( ) ln( 15 )
ex exp( ) exp( x )
square root sqrt( ) sqrt( 9.7 )
value of PI pi pi
varaible x x x
variable y y
Note: All trigonometric functions take arguments of angles measured in radians.
Function names are case insensitive, as Cos, COS,  cos, cOs have same meaning

 

 
Demonstration

Before calling Evaluate, you must declare six different variable for the arguments to be passed to Evaluate. You may choose any names for these variables. As as example:

String myExpression = "2 + 3 * sin (x) ";
double x = 2.0;
double y = 0.0;
RefString cur, succ, comp;

You must instantiate the three RefString object as

cur = new RefString( );
succ = new RefString( );
comp = new RefString( );


Now you can call the Evaluate method, for example

double result = EvaluateExpr.Evalute(myExpression, x, y, cur, succ, comp);

You could use a loop to get expression evaluated between intervals:

double x = 0 , result;
String myExpression = "x^2 - 2*x + 5";

do{
      result =  EvaluateExpr.Evalute(myExpression, x, y, cur, succ, comp);
     x += 1.0;
   System.out.println("f("+ x + ")" + result );
} while (x <= 10.0);

 

 
  You can run the demo program Test.java by typing java Test at the command prompt.

It should display the following output:

output