Slightly modified answer to a similar question to handle x^n
term (where n
is a natural number):
public static double calcFunction(double arg, String str) throws ScriptException {
String expr = Pattern.compile("x(\\^(\\d+))")
.matcher(str)
.replaceAll(mr -> "x " + " * x".repeat(Integer.parseInt(mr.group(2))-1)) // x^n
.replaceAll("(\\d+)x", "$1 * " + arg) // ax
.replaceAll("x", Double.toString(arg));
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
// a checked ScriptException may be thrown
System.out.println(expr + " = " + engine.eval(expr));
double result = Double.parseDouble("" + engine.eval(expr));
System.out.println("result = " + result);
return result;
}
Test:
calcFunction(2, "x^2 + 3x + 1");
calcFunction(3, "3x^2 + 3x + 1");
Output:
2.0 * 2.0 + 3 * 2.0 + 1 = 11.0
result = 11.0
3 * 3.0 * 3.0 + 3 * 3.0 + 1 = 37.0
result = 37.0