二分查找实现自己的sqrt函数
分析:
1.二分查找适用于单调序列。
2.求一个数的开平方,我们可以想象成从0到这个数进行查找 x*x = 这个数。
代码如下
/*************************************************************************
> File Name: binary_search.c
> Author: du
> Mail:
> Created Time: 2020年11月01日 星期日 01时42分10秒
************************************************************************/
#include<stdio.h>
#include <math.h>
//自己实现的sqrt函数
double f(double x){
return x * x;
}
//使用函数指针作为参数
double binary_search(double (*arr)(double), double x){
double head = 0;
double tail = x;
double mid;
//如果待查找的数小于1.0,那么它的开平方可定大于本身,比如0.01开平方为0.1 所有将尾指针设置为1.0。
if(x < 1.0) tail = 1.0;
//进行浮点数比较,自然不能直接进行比较,所以要使用误差进行比较。
#define EPSL 1e-10
while( tail - head > EPSL ){
mid = (head + tail) / 2.0;
if( arr(mid)< x ) head = mid;
else tail = mid;
}
return head;
#undef EPSL
}
int main(){
double x;
while( ~scanf("%lf",&x)){
double ans = binary_search(f, x);
printf("sqrt(%g) = %g\n", x, sqrt(x));
printf("my_sqrt(%g) = %g\n", x, ans);
}
return 0;
}
注意:
如果计算的结果和实际结果有误差,可以将EPSL设置更小。
测试结果