gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:12:15 25 4
gpt4 key购买 nike

好的,这段代码在另一个问题中,但我不知道如何添加更新的代码。我让这段代码正常工作并给出了正确的答案,但根据我的 while 循环条件它并没有停止。我不确定我在那里做错了什么?答案明显收敛,所有值都是正确的,只是 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);
}
}

最佳答案

表达式

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

关于java - Java中的无限while循环——Newton-Raphson方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21781645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com