0

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)
Renlyze
  • 1
  • 2
  • The JavaScript engine was removed in Java 15. Also, I'm really wondering why you're programming this in JavaScript inside Java, instead of programming it purely in Java. – Mark Rotteveel Apr 24 '23 at 08:09
  • this is how we are being taught in school and regarding javascript engine, I just didn't know it was removed – Renlyze Apr 24 '23 at 08:14
  • Switching to, for example, Java 11 will likely make it work (I'm not 100% sure though). – Mark Rotteveel Apr 24 '23 at 08:15
  • Do you know or can you point me towards any other method in order to get the output i am looking for? – Renlyze Apr 24 '23 at 08:25
  • If you use java 11 then you should be able to use the javascript script engine. Did you try that? You can download either java 11 or java 8 lts versions and they have nashorn still. – matt Apr 24 '23 at 08:35
  • yea I tried but the output I get looks like this Warning: Nashorn engine is planned to be removed from a future JDK release Warning: Nashorn engine is planned to be removed from a future JDK release *** NEWTON RAPHSON METHOD IMPLEMENTATION *** javax.script.ScriptException: ReferenceError: "x0" is not defined in at line num – Renlyze Apr 24 '23 at 08:48
  • Great, then the javascript is working and you have new errors to deal with. The warning is just that, a warning because, as you have seen, it is going to be removed. – matt Apr 24 '23 at 09:41
  • You haven't defined `x0` in the script you are using. `gFunc + "(x0)"` that looks broken. It seems you don't know how to use javascript, you need to call your function with different arguments. Maybe you should ask a new question where you just try to call javascript from java with changing arguments? This is really confusing to pick through at the moment. – matt Apr 24 '23 at 09:43
  • Yea I think I'll just scrap this one and start over, its gotten very confusing. Appreciate your help though! – Renlyze Apr 25 '23 at 00:49

0 Answers0