二分查找
注意浮點數(shù)如果為負數(shù)的情況,因為負數(shù)也可以開立方根
public static double cubeRoot(double num) {
double left = 0;
double right = num;
if (num < 0) {
left = num;
right = 0;
}
double mid = (left + right) / 2;
double ans = mid* mid *mid;
while (Math.abs(num - (ans)) > 1e-5) {
mid = (left + right) / 2;
ans = mid * mid * mid;
if (ans - num > 1e-5) {
right = mid;
} else if (num - ans > 1e-5){
left = mid;
}
}
return mid;
}