0
votes

Ok this code was in another question but I couldn't work out how to add my updated code. I got this code working and putting out the right answers but it isn't stopping according to my while loop conditions. i'm not sure what I've done wrong there? The answer clearly converges and all values are right, just while loop is ignored.

/* Newton Raphson Method*/

import java.util.Scanner; 
import static java.lang.Math.*; 

public class NewtRaphEx {

    // Creating Function f = x - cos(3.5x)

    double f = 0.0;
    double df = 0.0;

    public static double function(double x) {
        return (x - cos(3.5 * x)); 
    }

    public static double dfunction (double x) { 
        return (1 + 3.5*sin(3.5 * x));
    }

    public static void main (String[] args) {

       //Initialising all variables 
       double xn = 0.06;
       double xnew = 0.0;
       double e_allow = 0.001;
       double fn = 0.0;
       double eps = 0.0;
       double dfn = 0.0; 
       double dx = 0.0; 
       int n = 0;
       int nMax = 10000;

       do {
           for (n = 0; n <= nMax; n++) {
               fn = function(xn); 
               dfn = dfunction(xn);
               dx = -(fn / dfn); 
               xnew = xn + dx; 
               xn = xnew;
               eps = abs(dx / xn);
               n = n + 1;
           }
       } while (eps <= e_allow || n < nMax);

       System.out.print("N" + "\t" + "X" + "\t" + "F(x)" + "\t" + "dF(x)" + "\t");
       System.out.println("delX" + "\t" + "X_new" + "\t" + "Epsilon");
       System.out.format("%d\t" + "%.3f\t" + "%.3f\t" + "%.3f\t" + "%.3f\t" + "%.3f\t" + "%.3f", n, xn, fn, dfn, dx, xnew, eps);
    }
}
1
In the for loop you're incrementing n twice. Is that supposed?Hugo Sousa
ahm, why do you have a for in the while... do you need at least 5000 results before breaking the loop?diazazar
Try changing the OR to AND in the do while. It is likely better to just have the eps comparison done inside the for loop and break if you are close enough. That is, drop the outer loop.Teresa Carrigan
you should either use while or use for, not both of themhoaz

1 Answers

2
votes

The expression

eps <= e_allow || n < nMax

evaluates to true when you reach it, therefore the for loop will run again, setting n = 0 and thus the infinite loop.

Specifically, you would have:

eps = 0.0;
e_allow = 0.001;
n = 10002; // due to the increment inside the loop
nmax = 10000;

as as such:

eps <= e_allow || n < nMax
0.0 <= 0.001 (true) OR 10002 <= 10000 (false) -> true