private double EPSILON = 0.25;
private int iteration = 0;
public double f(double x){
return x*x - 2;
}
public double bisection(double a, double b){ //main algorithm
iteration++;
if(f(a) * f(b) >= 0){
return 0.0; // Wrong [a, b]
}
double c = a;
while((b-a) >= EPSILON){
c = (a+b)/2; // middle point
if(f(c) == 0.0){ // that means middle point is the root
break;
}
else if (f(c)*f(a) < 0){
b = c;
bisection(a, b); // continue calculating by recu
}
else{
a = c;
bisection(a, b);
}
}
return c;
}
public int getIteration(){
return iteration;
}
}我正在处理一种递归二分法/算法。我把递归放在了or /else if语句中,不知道我是否错了。它也返回不需要递归的正确的根,但是主要的问题是使用递归。
发布于 2022-10-23 15:41:29
好吧,我找到出路了。
private double EPSILON = 0.25;
private int iteration = 0;
private double c = 1.0;
public double f(double x){
return x*x - 2;
}
public double bisection(double a, double b){ //main algorithm
iteration++;
if(f(a) * f(b) >= 0){
return 0.0; // Wrong [a, b]
}
if((b-a) >= EPSILON){
c = (a+b)/2; // middle point
if(f(c) == 0.0){ // that means middle point is the root
return c;
}
else if (f(c)*f(a) < 0){
b = c;
bisection(a, b);
}
else {
a = c;
bisection(a, b);
}
}
return c;
}
public int getIteration(){
return iteration;
}
}https://stackoverflow.com/questions/74172214
复制相似问题