Java中的无限循环 - Newton-Raphson方法

时间:2014-02-14 14:12:16

标签: java while-loop newtons-method

好的,这段代码是另一个问题,但我无法弄清楚如何添加我更新的代码。我得到了这个代码工作并提出了正确的答案,但它并没有停止根据我的while循环条件。我不确定那里我做错了什么?答案明显收敛,所有值都是正确的,只是在忽略循环时。

/* 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 个答案:

答案 0 :(得分:2)

表达式

eps <= e_allow || n < nMax

到达时评估为true,因此for循环将再次运行,设置n = 0,从而设置无限循环。

具体来说,你会:

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

就这样:

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