I have this newton Raphson code that asks the user for the function, the derivative of the function, the initial guess, the tolerance for the error and the maximum iteration. The output that I am expecting is the iteration of the calculation up until it either reaches the root or up until the placed maximum number of iteration that is set by the user. Still learning java so any help would be greatly appreciated
this is the code:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class NewtonRaphson {
private static ScriptEngine engine;
public static void main(String[] args) {
String f = "Enter function f(x): ";
String g = "Enter derivative of f(x): ";
String x0 = "Enter Guess: ";
String e = "Tolerable Error: ";
String N = "Maximum Step: ";
String func = getUserInput(f);
String der = getUserInput(g);
double guess = Double.parseDouble(getUserInput(x0));
double error = Double.parseDouble(getUserInput(e));
int maxSteps = Integer.parseInt(getUserInput(N));
newtonRaphson(func, der, guess, error, maxSteps);
}
public static void newtonRaphson(String f, String g, double x0, double e, int N) {
try {
engine = new ScriptEngineManager().getEngineByName("JavaScript");
String gFunc = "function(x) { return " + g + "; }";
engine.eval(gFunc);
System.out.println("\n\n*** NEWTON RAPHSON METHOD IMPLEMENTATION ***");
int step = 1;
int flag = 1;
boolean condition = true;
while (condition) {
if (Double.compare((Double) engine.eval(gFunc + "(x0)"), 0.0) == 0) {
System.out.println("Divide by zero error!");
break;
}
String fEval = f.replace("x", Double.toString(x0));
double fResult = (double) engine.eval(fEval);
String gEval = g.replace("x", Double.toString(x0));
double gResult = (double) engine.eval(gEval);
double x1 = x0 - fResult / gResult;
System.out.printf("Iteration-%d, x1 = %0.6f and f(x1) = %0.6f\n", step, x1, fResult);
x0 = x1;
step++;
if (step > N) {
flag = 0;
break;
}
condition = Math.abs(fResult) > e;
}
if (flag == 1) {
System.out.printf("\nRequired root is: %0.8f\n", x0);
} else {
System.out.println("\nNot Convergent.");
}
} catch (ScriptException ex) {
System.out.println(ex);
}
}
private static String getUserInput(String message) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
System.out.print(message);
return scanner.nextLine();
}
}
and this is the usual result:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "javax.script.ScriptEngine.eval(String)" because "NewtonRaphson.engine" is null
at NewtonRaphson.newtonRaphson(NewtonRaphson.java:29)
at NewtonRaphson.main(NewtonRaphson.java:21)