拟牛顿法
public static void sqrt1(double x){
// 方法1, 拟牛顿近似法
// x * x * x - N
// x1 = N ;
// y - y1 = 3x1*x1(x - x1)
// x1 = (3x1 * x1 * x1 - y1) / (3x1 * x1)
// y1 = x1 * x1 * x1 - N
// ===> x1 = (3x1 * x1 * x1 - x1 * x1 * x1 + N )/(3x1 * x1)
// ===> x1 = (2 * x1 * x1 * x1 + N)/(3 * x1 * x1)
double start = x;
double delta = 1;
while(delta > 1e-8 || delta < -1e-8){
double y_next = x * x * x - start;
double x_next = (2 * x * x * x + start)/(3 * x * x);
delta = x - x_next;
x = x_next;
}
System.out.printf("%.6f",x);
}
二分法
public static void sqrt2(double x){
double l = -10000;
double r = 10000;
while(r-l > 1e-8){
double mid = (l + r) / 2;
if(mid * mid * mid >= x){
r = mid;
}else{
l = mid;
}
}
System.out.printf("%.6f", l);
}
提交一下试试呗