牛顿开方法原理在http://www.guokr.com/question/461510/有详细介绍,只需要记住下面的公式即可;
以下是根据上述公式写的代码,其中n表示迭代次数,a表示被开方数,k表示开方次数
package ibbe.scheme.keydistrubution;
import java.lang.Math;
public class Nuton {
public static double root(int n) {
double k = 2;
double a = 3;
double flg = 0;
if (n == 0) {
return 1;
} else {
// flg=Math.pow(root(n-1), k-1);
return ((k - 1) / k) * root(n - 1)
+ (a / (k * (Math.pow(root(n - 1), k - 1))));
}
}
// 用来求2次方根,这个是百度到的求2次方根的代码
static double NewtonMethod(double fToBeSqrted) {
double x = 1.0;
while (Math.abs(x * x - fToBeSqrted) > 1e-5) {
x = (x + fToBeSqrted / x) / 2;
}
return x;
}
public static void main(String[] args) {
System.out.println(root(7));
System.out.println(NewtonMethod(2));
}
}
运行结果: