本是书后习题 ,难度不大,但在实现时对于语法有值得借鉴的地方,就记录下来:
题目:对某个任意的函数f找出方程f(X)=0的一个解,该函数连续的并有两个点low、high使得f(low)和f(high)符号相反,那么在low和high之间即存在一个零点;
需要注意的如下:
——满足给定的low、high使得f(low)*f(high)<0;
——用一个函数作为参数传递我们需要不断变化的方程;
——对于那些位数过多的小数,当达到一定的精度时即可返回值。
代码如下:
//折半查找零点
//此函数可以自定义
double f(double x)
{
return x*x + 2 * x - 2;
}
double binarySearchZero(double (*f)(double), double low, double high)
{
if (high-low<1e-6)//这里控制你想要的精度
return low;
double mid = (low + high) / 2;
if (f(low) * f(mid) < 0)
binarySearchZero(f, low, mid);
else if (f(mid) * f(high) < 0)
binarySearchZero(f, mid, high);
else if (f(mid == 0))
return mid;
}
//条件:f(low) * f(high)<0;
double binarySearchZero(double(*f)(double))
{
int low, high;
do {
cin >> low >> high;
} while (f(low)*f(high)>0);
return binarySearchZero(f, low, high);
}