A quick 'n dirty way to do this is to use Java's JavaScript engine. An example:
import javax.script.*;
interface GraphFunction {
double eval(double x);
public static GraphFunction createFromString(String expression) {
try {
ScriptEngine engine = new ScriptEngineManager()
.getEngineByName("JavaScript");
engine.eval("function graphFunc(x) { return " + expression + "; }");
final Invocable inv = (Invocable)engine;
return new GraphFunction() {
@Override
public double eval(double x) {
try {
return (double)inv.invokeFunction("graphFunc", x);
} catch (NoSuchMethodException | ScriptException e) {
throw new RuntimeException(e);
}
}
};
} catch (ScriptException e) {
throw new RuntimeException(e);
}
}
}
Now, to use it:
class Test {
public static void main(String[] args) {
GraphFunction f = GraphFunction.createFromString("2*x+1");
for (int x = -5; x <= +5; x++) {
double y = f.eval(x);
System.out.println(x + " => " + y);
}
}
}
Output:
-5 => -9.0
-4 => -7.0
-3 => -5.0
-2 => -3.0
-1 => -1.0
0 => 1.0
1 => 3.0
2 => 5.0
3 => 7.0
4 => 9.0
5 => 11.0