二分法和牛顿迭代法解方程c++实现代码
时间: 2023-08-14 10:06:30 浏览: 135
二分法和牛顿迭代法都是求解方程的方法,下面分别给出 C++ 实现代码:
1. 二分法:
```c++
#include <iostream>
using namespace std;
double func(double x) { //定义方程
return x * x - 2;
}
double bisection(double a, double b, double eps) { //二分法求解方程
double mid = (a + b) / 2;
while (b - a > eps) {
if (func(mid) == 0) return mid;
else if (func(a) * func(mid) < 0) b = mid;
else a = mid;
mid = (a + b) / 2;
}
return mid;
}
int main() {
double result = bisection(1, 2, 0.00001);
cout << "The root of the equation is: " << result << endl;
return 0;
}
```
2. 牛顿迭代法:
```c++
#include <iostream>
using namespace std;
double func(double x) { //定义方程
return x * x - 2;
}
double func_derivative(double x) { //定义方程的导数
return 2 * x;
}
double newton(double x0, double eps) { //牛顿迭代法求解方程
double x1 = x0 - func(x0) / func_derivative(x0);
while (abs(x1 - x0) > eps) {
x0 = x1;
x1 = x0 - func(x0) / func_derivative(x0);
}
return x1;
}
int main() {
double result = newton(1, 0.00001);
cout << "The root of the equation is: " << result << endl;
return 0;
}
```
阅读全文