0
確定此代碼是在另一個問題,但我無法解決如何添加我的更新代碼。我得到了這個代碼工作,並提出正確的答案,但它並沒有停止根據我的while循環條件。我不確定我在那裏做錯了什麼?答案顯然是收斂的,所有的值都是正確的,只是在循環被忽略的時候。Java中的無限while循環 - Newton-Raphson方法
/* 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);
}
}
在你遞增'N'兩次'for'循環。這是假設嗎? –
ahm,你爲什麼在這段時間內有一個for ...在打破循環之前你需要至少5000個結果嗎? – diazazar
嘗試將「或」更改爲「和」。在for循環內完成eps比較可能會更好,如果足夠接近,可能會中斷。也就是說,放棄外部循環。 –