二分法求sqrt (2)精确到小数点后 10 位

因为 sqrt(2)约等于 1.4,所以可以在(1.4, 1.5)区间做二分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private static final double TEN = 0.0000000001;

private static double sqrt2() {
double low = 1.4;
double high = 1.5;
double mid = (low + high) / 2;
while ((high - low) > TEN) {
if (high * high > 2) {
high = mid;
} else {
low = mid;
}
mid = (low + high) / 2;
}
return mid;
}
坚持原创技术分享,您的支持将鼓励我继续创作!