c++ 二分法求根(一个根)
思路:
(1) 当f(a)*f(b)<0时证明[a,b]之间有一个零点
(2) a.如果f(a)>0,则f(b)<0
1. 取temp = (a + b)/2
2. 若 f(temp) < 误差值 d ,
-输出结果
3. 反之f(temp) > 误差值 d ,
- 若f(temp) < 0,则使b = temp
- 若f(temp) > 0,则使a = temp
4. 重复1-3
(3) a.如果f(a)<0,则f(b)>0
1. 取temp = (a + b)/2
2. 若 f(temp) < 误差值 d ,
-输出结果
3. 反之f(temp) > 误差值 d ,
- 若f(temp) > 0,则使b = temp
- 若f(temp) < 0,则使a = temp
4. 重复1-3
#include<iostream>
#include<math.h>
using namespace std;
long double a,b,temp;
long double d = 0.000000001; // 误差值
long double start = -10000;
long double end = 10000;
long double f(long double x){
return 6 * x * x * x+ 7 * x * x + x +5;
}
void cal(){
temp = (start+end)/2;
cout<<"temp:"<<temp<<",f(temp):"<<f(temp)<<endl;
if(f(end)>0){
if(f(temp)>0){
end = temp;
}
else{
start = temp;
}
}
else if(f(end)<0){
if(f(temp)<0){
end = temp;
}
else{
start = temp;
}
}
cout<<"a:"<<a<<",b:"<<b<<",temp:"<<temp<<",start:"<<start<<",end:"<<end<<endl;
if(f(temp)-0<d&&f(temp)-0>-d){
cout<<"f(temp):"<<f(temp)<<endl;
return;
}
cal();
}
int main(){
if(f(start)*f(end)<0){
cal();
}
cout<<"#######################################################"<<endl;
cout<<"x = "<<temp<<endl;
cout<<"abs(f(temp)):"<<abs(f(temp))<<endl;
cout<<"#######################################################"<<endl;
}
GITHUB:https://github.com/joeytsai03/ComputeAlgorithm/blob/master/src/TheDichotomyFindRoots.cpp
网友评论