gamesmathematical programsotherabout author

Expression parser

ru
java expression parser
c++ expression parser
javascript expression parser
download source code
versions history

Expression parser is parser of strings like sin(pi/4) which is realized on java, c++ and javascript languages. There are two projects based on java parser. One can download them or run online. They are scientific calculator and java graph

List of supported functions and constants

Common functions

exp(x) = ex - exponent of x
log(x) - natural logarithm of x
pow(x, y) = xy - x to the power of y
sqrt(x) - square root of x
abs(x) = |x| - absolute value of x
random() - random number between 0 and 1
min(x1, x2) - minimum of two arguments
max(x1, x2) - maximum of two arguments

Constants

pi = 3.141592653589793
e = 2.718281828459045
sqrt2 = sqrt(2) = 1.4142135623730951
sqrt1_2 = sqrt(1/2) = 0.7071067811865476
ln2 = loge(2) = log(2) = 0.6931471805599453
ln10 = loge(10) = log(10) = 2.302585092994046
log2e = log2(e) = 1/log(2) = 1.4426950408889634
log10e = log10(e) = 1/log(10) = 0.4342944819032518

Trigonometric functions

sin(x) - sine of x
asin(x) - arcsine of x
cos(x) - cosine of x
acos(x) - arccosine of x
tan(x) - tangent of x
atan(x) - arctangent of x
atan2(x,y) - arctangent of x/y
cot(x)=cos(x)/sin(x) - cotangent of x
acot(x)=pi/2-atan(x) - arccotangent of x
sec(x)=1/cos(x) - secant of x
asec(x)=acos(1/x) - arcsecant of x
csc(x)=1/sin(x) - cosecant of x
acsc(x)=asin(1/x) - arccosecant of x

Hyperbolic trigonometric functions

sinh(x)=(ex-e-x)/2 - hyperbolic sine of x
asinh(x)=log(x+sqrt(x2+1)) - area hyperbolic sine of x
cosh(x)=(ex+e-x)/2 - hyperbolic cosine of x
acosh(x)=log(x+sqrt(x2-1)) - area hyperbolic cosine of x
tanh(x)=(ex-e-x)/(ex+e-x) - hyperbolic tangent of x
atanh(x)=log((1+x)/(1-x))/2 - area hyperbolic tangent of x
coth(x)=(ex+e-x)/(ex-e-x) - hyperbolic cotangent of x
acoth(x)=log((x+1)/(x-1))/2 - area hyperbolic cotangent of x
sech(x)=1/cosh(x)=2/(ex+e-x) - hyperbolic secant of x
asech(x)=acosh(1/x)=log[(1+sqrt(1-x2))/x] - area hyperbolic secant of x
csch(x)=1/sinh(x)=2/(ex-e-x) - hyperbolic cosecant of x
acsch(x)=asinh(1/x)=log[1/x+sqrt(1+x2)/abs(x)] - area hyperbolic cosecant of x

Rounding functions

ceil(x) - returns x, rounded upwards to the nearest integer
floor(x) - returns x, rounded downwards to the nearest integer
round(x) - rounds x to the nearest integer

Numbers

Numbers can be written in simple form, for example 1.2. Point is separtor. Exponent form is also possible.

1.2e1=12
1.2e+1=12
1.2e-1=0.12
1.2e0=1.2
1.2e+0=1.2
1.2e-0=1.2

Brackets

It's possible to use three types of brackets ( ), [ ], { }

Java expression parser

Very first example

package demo;

import estimator.ExpressionEstimator;

public class Example1 {

  public static void main(String[] args){

    try {
      double v=ExpressionEstimator.calculate("sin(pi/4)");
      System.out.println(v);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }

  }

}

Output

0.7071067811865475

Parameter of calculate() function is formula which can include variables x0, x1, ... If variables are presented then formula should be compiled at first. Then just call calculate() function with values.

package demo;

import estimator.ExpressionEstimator;

public class Example2 {

  public static void main(String[] args){
    ExpressionEstimator estimator=new ExpressionEstimator();
    try {
      estimator.compile("x0+x1");
      double[][]values={ {3,6}, {8,6} };
      for(double[]v:values){
        System.out.println( estimator.calculate(v) );
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }

  }

}

Output

9.0
14.0

More complicate example

package demo;

import java.util.Arrays;

import estimator.ExpressionEstimator;

public class Example3 {

  public static void main(String[] args) throws Exception{
    String expression[]={"sin(pi/4)","1+2+"};
    for(String s:expression){
      System.out.print("\""+s+"\"=");
      try {
        System.out.println(ExpressionEstimator.calculate(s));
      } catch (Exception e) {
        System.out.println(e.getMessage());
      }
    }

    ExpressionEstimator estimator=new ExpressionEstimator();
    expression=new String[]{"3*x0+2*x1*x0","6*x0"};
    double[][]values={ {3,6}, {8,6} };
    double[]v;
    int i=0;
    for(String s:expression){
      v=values[i++];
      System.out.print("\""+s+"\""+Arrays.toString(v)+"=");
      try {
        estimator.compile(s);
        System.out.println(estimator.calculate(v));
      } catch (Exception e) {
        System.out.println(e.getMessage());
      }
    }

  }

}

Output

"sin(pi/4)"=0.7071067811865475
"1+2+"=unexpected operator
"3*x0+2*x1*x0"[3.0, 6.0]=45.0
"6*x0"[8.0, 6.0]=invalid number of expression arguments

C++ expression parser

Very first example

#include "expressionEstimator.h"
#include <stdio.h>

int main(){
  try {
    ExpressionEstimator::Init();
    double v=ExpressionEstimator::calculate("sin(pi/4)");
    printf("%lf",v);
  }catch(Exception& e){
    printf("%s\n",e.what());
  }
  return 0;
}

Output

0.7071067811865475

Parameter of calculate() function is formula which can include variables x0, x1, ... If variables are presented then formula should be compiled at first. Then just call calculate() function with values and number of arguments.

#include "expressionEstimator.h"
#include <stdio.h>

int main(){
  try {
    ExpressionEstimator::Init();
    ExpressionEstimator estimator;
    estimator.compile("x0+x1");

    const int arguments=2;
    const double values[][arguments]={ {3,6}, {8,6} };
    const int valuesSize=sizeof(values)/sizeof(values[0]);
    for(int i=0;i<valuesSize;i++){
      printf("%lf\n", estimator.calculate(values[i],arguments) );
    }
  }catch(Exception& e){
    printf("%s\n",e.what());
  }
  return 0;
}

Output

9.0
14.0

More complicate example

#include "expressionEstimator.h"
#include <stdio.h>
#include <string>

std::string arraytoString(const double *v,const int arguments){
  std::string s="[";
  char buff[32];
  for(int i=0;i<arguments;i++){
    sprintf(buff, "%lf", v[i]);
    s+=buff;
    s+= i==arguments-1 ? "]" : ", " ;
  }
  return s;
}

int main(){
  ExpressionEstimator::Init();
  ExpressionEstimator estimator;
  int i;
  const char*s;
  const char* expression[]={"sin(pi/4)","1+2+"};
  const int expressionSize=sizeof(expression)/sizeof(expression[0]);
  for(i=0;i<expressionSize;i++){
    s=expression[i];
    printf("\"%s\"=",s);
    try {
      printf("%lf\n",ExpressionEstimator::calculate(s));
    } catch (Exception& e) {
      printf("%s\n",e.what());
    }
  }

  const char* expression1[]={"3*x0+2*x1*x0","6*x0"};
  const int expression1Size=sizeof(expression1)/sizeof(expression1[0]);

  const int arguments=2;
  const double values[][arguments]={ {3,6}, {8,6} };
  const int valuesSize=sizeof(values)/sizeof(values[0]);

  const double*v;
  for(i=0;i<valuesSize;i++){
    v=values[i];
    s=expression1[i];
    printf("\"%s\"%s=",s,arraytoString(v,arguments).c_str());
    try {
      estimator.compile(s);
      printf("%lf\n",estimator.calculate(v,arguments));
    } catch (Exception& e) {
      printf("%s\n",e.what());
    }
  }

  return 0;
}

Output

"sin(pi/4)"=0.7071067811865475
"1+2+"=unexpected operator
"3*x0+2*x1*x0"[3.0, 6.0]=45.0
"6*x0"[8.0, 6.0]=invalid number of expression arguments

Javascript expression parser

To use javascript parser include script file at first

<script src= type="text/javascript"></script>

and call calculate() function

<html>
<head>
<script src= type="text/javascript">
</script>
<script type="text/javascript">
expression=["sin(pi/4)","1+2+"]
out=''
for(i=0;i<expression.length;i++){
  s=expression[i]
  out+='"'+s+'"='
  try {
    out+=calculate(s)
  } catch (exception) {
    out+=exception.message;
  }
  out+='\n'
}
alert(out);
</script>
</head>
<body>
</body>
</html>

Output

"sin(pi/4)"=0.7071067811865475
"1+2+"=syntax error

Versions history

version 1.12 15 august 2014

fixed javascript bugs

version 1.11 17 july 2014

fixed bugs for c++ and javascript

version 1.1 11 july 2014

small changes is c++ code
added c++ calculator on GTK+

version 1.04 1 may 2014

fixed bugs of javascript calculator
added support of all functions for javascript calculator
fixed bug with acsch function

version 1.03 20 april 2013

interface of java graph is changed

version 1.01-1.02 17 april 2013

added source code of expression parser on c++ and javascript

version 1.0 22 february 2013

three projects (calculator, plotter and parser) are combined into one
code of plotter have rewritten from c++ to java