2019年阿里面試題中的一道
題目:已知 sqrt (2)約等於 1.414,要求不用數學庫,求 sqrt (2)精確到小數點後 10 位。
* 考察點
- 基礎算法的靈活應用能力(二分法學過數據結構的同學都知道,但不一定往這個方向考慮;如果學過數值計算的同學,應該還要能想到牛頓迭代法並解釋清楚)
- 退出條件設計
* 解決辦法
1. 已知 sqrt(2)約等於 1.414,那麼就可以在(1.4, 1.5)區間做二分
查找,如: a) high=>1.5 b) low=>1.4 c) mid => (high+low)/2=1.45 d) 1.45*1.45>2 ? high=>1.45 : low => 1.45 e) 循環到 c)
2. 退出條件
a) 前後兩次的差值的絕對值<=0.0000000001, 則可退出
解題思路就是二分法
public class sqrt2 {
static final double EPSILON = 0.0000000001;
static double sqrt2(){
double low = 1.4, high = 1.5;
double mid = (low + high) / 2;//利用二分法來循環比較
while(high - low > EPSILON){
if (mid * mid > 2) {//取其平均值,然後根據平方來與2比較
high = mid;
}else {
low = mid;
}
mid = (high + low) / 2;
}
return mid;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
double mid = sqrt2();
System.out.print(mid);
}
}
打印結果:1.4142135623376817