不使用API,怎样求一个数的近似平方根呢?
答案就是使用二分查找法。
思路就是我们用高低位两个数取中间值,然后求平方,看看和目标数的接近程度,只要平方结果精度超过小数点后六位,那么就认为是最终结果。
网上很多答案只能开整数平方根,这里我们以小数点后6位精度来求解,解法就和Java API Math的sqrt方法很相似了。
代码:
public static void main(String[] args) {
int x = 5;
double q = sqrt(x);
System.out.println("求一个数的近似平方根:" + q);
System.out.println("求一个数的近似平方根:" + q*q);
System.out.println("使用Java API对比:" + Math.sqrt(x));
}
/**
* 求一个数的平方根,精确到小数点后6位
* @param x
* @return
*/
public static double sqrt(int x) {
double low = 0;
double high = x;
double mid = low+(high-low)/2;
while(true) {
if(mid*mid - x > 0.0000001 && mid*mid - x < 0.000001) {
return mid;
}
if(mid*mid - x > 0.0000001) {
high = low+(high-low)/2;
}
if(mid*mid - x < 0.000001) {
low = low+(high-low)/2;
}
mid = low+(high-low)/2;
System.out.println("mid:"+mid);
}
}
输出:
mid:1.25
mid:1.875
mid:2.1875
mid:2.34375
mid:2.265625
mid:2.2265625
mid:2.24609375
mid:2.236328125
mid:2.2314453125
mid:2.23388671875
mid:2.235107421875
mid:2.2357177734375
mid:2.23602294921875
mid:2.236175537109375
mid:2.2360992431640625
mid:2.2360610961914062
mid:2.2360801696777344
mid:2.2360706329345703
mid:2.2360658645629883
mid:2.2360682487487793
mid:2.236067056655884
mid:2.2360676527023315
mid:2.2360679507255554
mid:2.2360680997371674
求一个数的近似平方根:2.2360680997371674
求一个数的近似平方根:5.000000546662187
使用Java API对比:2.23606797749979