基于二分法求方程的根,主要思路是通过给定两个初始值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 <iostream>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <math.h>
#include <cstring>
#include <string>
#include <queue>
#include <deque>
#include <stack>
#include <stdlib.h>
#include <list>
#include <map>
#include <utility>
#include <set>
#include <bitset>
#include <vector>
#define pi acos(-1.0)
#define inf 0x3f3f3f3f
#define linf 0x3f3f3f3f3f3f3f3fLL
#define ms(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
inline int read()
{
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
return x*f;
}
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;
}