Hunting and gathering in the JEE landscape

I am Frank, a freelance Java developer specialized in backend development from south western germany.

exp4j: a simple mathematical expression parser for java

posted by fas on 2010-12-22 . Tagged as projects, exp4j, programming, java, math

Since i could not find a simple free and open math expression parser for java i decided to build one myself. So behold exp4j, a simple, free and open math expression parser for java.
exp4j is 20kb in size and has no external dependencies.

Update:A new version,exp4j 0.2.x has been released
Check here for a more detailed update note

exp4j is currently in development and not recommended for production use.

Project site & Download

exp4j takes a mathematical term in human readable infix notation and evaluate it's result by first converting the input through Dijkstra's Shunting Yard Algorithm to postfix (RNP) notation and evaluating the postfix term by a simple Stack Algorithm.

A simple demo of a function plotter applet using exp4j can be found here



Return the computed value of an expression:

System.out.println(PostfixExpression.fromInfix("2 * 17.41 + (12*2)^(0-1)").calculate());
> 34.861666666666665

define a function with two variables x and y:
double x=Math.E;
double y=Math.PI;
System.out.println(PostfixExpression.fromInfix("f(x,y)=x^2 - 2 * y").calculate(x,y));
> 1.1058707917510633

only thing to worry about is to pass the argument values to the calculate method in the same
order as the variable names in the function expression. so if instead we would have written "f(pi,e)=e^2 - 2 * pi" we would have to reverse the arguments for the calculate method. i.e. "calculate(pi,e)".

A simple commandline interpreter has also been added to the library:
java -jar exp4j.jar "3+4-log(23.2)^(2-1) * -1"
> 10.144152278672264

The following operations and functions are supported:
Functions are delegated to java.lang.Math, and named accordingly.

  • Addition
  • Subtraction
  • Multiplication
  • Divison
  • Modulo
  • Exponentiation
  • Unary minus, plus
  • abs: absolute value
  • acos: arc cosine
  • asin: arc sine
  • atan: arc tangent
  • cbrt: cubic root
  • ceil: next integer value
  • cos: the cosine
  • cosh: hyperbolic cosine
  • exp: euler's number raised to the value (e^x)
  • floor: previous integer value
  • log: logarithmus naturalis (base e)
  • sin: sine
  • sinh: hyerbolic sine
  • sqrt: square root
  • tan: tangent
  • tanh: hyperbolic tangent

exp4j is published under the Apache License Version 2.0

Download exp4j.

if you find any bugs please post them here or drop me a mail and expect my eternal gratitude.

Tags: projects, exp4j, programming, java, math