基于二分法求方程的根,主要思路是通过给定两个初始值a和b,使f(a)f(b)<0。如果f(x)是连续的,则必然在(a,b)内存在一个值c,使f(c)=0。
首先计算c=(a+b)/2;
如果f(c)=0,则直接返回c即可,否则,进行下面的判断:
如果f(a)f(c)>0,则令a=c,否则令b=c。
参考代码如下:
#include <stdio.h>
#include <math.h>
int main()
{
//2x3-4x2+3x-6
float a,b,mid;
float temp1,temp2,temp3;
a=-10.;
b=10.;
mid=(a+b)/2;
temp3=2*mid*mid*mid-4*mid*mid+3*mid-6;
while(fabs(temp3)>1e-6)
{
temp1=2*a*a*a-4*a*a+3*a-6;
temp2=2*b*b*b-4*b*b+3*b-6;
if(temp1*temp3>0)
a=mid;
else
b=mid;
mid=(a+b)/2;
temp3=2*mid*mid*mid-4*mid*mid+3*mid-6;
}
printf("the solution of the equation is %.4f.\n",mid);
return 0;
}