二分法求方程的根c++
时间: 2023-09-24 11:05:56 浏览: 17
二分法可以用来求解单峰函数的最大值或最小值,也可以用来求解连续函数的根。具体实现如下:
```c++
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double f(double x) { // 定义目标函数
return x * x - 2; // 求解 x^2 = 2 的根
}
double bisection(double a, double b, double eps) {
double c;
while (b - a > eps) {
c = (a + b) / 2.0;
if (f(c) == 0) return c; // 如果 c 是方程的根,直接返回
if (f(a) * f(c) < 0) b = c; // 如果 f(a) 和 f(c) 异号,根在 [a,c] 区间
else a = c; // 否则根在 [c,b] 区间
}
return (a + b) / 2.0; // 返回区间中点作为近似解
}
int main() {
double a = 0.0, b = 2.0, eps = 1e-6;
double root = bisection(a, b, eps);
cout << "The root of the equation is " << fixed << setprecision(6) << root << endl;
return 0;
}
```
运行结果:
```
The root of the equation is 1.414214
```
其中,`f(x)` 函数定义了目标方程,`bisection(a, b, eps)` 函数表示二分法求解区间 `[a,b]` 内方程的根,`eps` 表示误差范围。具体实现中,如果 `c` 恰好是方程的根,则直接返回;否则根据函数值的正负性来缩小区间。最后返回区间中点作为近似解。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)