代码如下,不知是否满足楼主要求~ public class Test_diedai { double a1; double a1_1;
public double method(double a){ this.a1 = a; a1_1 = 9 /(a + 2); if(Math.abs(a1_1 - a1) > 1e-6){ method(a1_1); } return a1_1; } public static void main(String args[]){ Test_diedai d = new Test_diedai(); double x = d.method(2.0d); double b = x*x + 2*x; System.out.println(b); } }
楼主说的是迭代,刚才我用的是递归,所以把迭代也写了一下,呵呵public class Test_diedai { double a1; double a1_1;
public double method(double a){ this.a1 = a; a1_1 = 9 /(a + 2); if(Math.abs(a1_1 - a1) > 1e-6){ method(a1_1); } return a1_1; } public double method_(double a){ this.a1 = a; while(true){ double b = a; a1_1 = 9 /(a + 2); a = a1_1; if(Math.abs(a1_1 - b) < 1e-6){ return a; } } } public static void main(String args[]){ Test_diedai d = new Test_diedai(); double x = d.method_(2.0d); double b = x*x + 2*x; System.out.println(b); } }
用个while迭代就可以了,public class Test { public static double method(double num) { double a = num; double b = 9 / (a + 2); while (Math.abs(a-b)<1e-10) { a = b; b = 9 / (b + 2); } return b; } public static void main(String args[]) { System.out.println(method(2.0d)); } }
public class Test_diedai {
double a1;
double a1_1;
public double method(double a){
this.a1 = a;
a1_1 = 9 /(a + 2);
if(Math.abs(a1_1 - a1) > 1e-6){
method(a1_1);
}
return a1_1;
}
public static void main(String args[]){
Test_diedai d = new Test_diedai();
double x = d.method(2.0d);
double b = x*x + 2*x;
System.out.println(b);
}
}
double a1;
double a1_1;
public double method(double a){
this.a1 = a;
a1_1 = 9 /(a + 2);
if(Math.abs(a1_1 - a1) > 1e-6){
method(a1_1);
}
return a1_1;
}
public double method_(double a){
this.a1 = a;
while(true){
double b = a;
a1_1 = 9 /(a + 2);
a = a1_1;
if(Math.abs(a1_1 - b) < 1e-6){
return a;
}
}
}
public static void main(String args[]){
Test_diedai d = new Test_diedai();
double x = d.method_(2.0d);
double b = x*x + 2*x;
System.out.println(b);
}
}
public static double method(double num) {
double a = num;
double b = 9 / (a + 2);
while (Math.abs(a-b)<1e-10) {
a = b;
b = 9 / (b + 2);
}
return b;
} public static void main(String args[]) {
System.out.println(method(2.0d));
}
}
符号写反了,拍谢
x = x-f(x)/(x+2) x = (x*x + 2x - (x*x + 2x - 9) )/x+2 = 9/(x+2)