1、编写程序,分别用二分法和牛顿迭代法求解方程x3 – 3x – 1 = 0在x = 2附近的实根,要求计算精确到小数点后七位数字为止,并将求出的近似结果与理论值2cos20 相比较,二分法的初始迭代区间为 [1, 3]。
时间: 2024-02-24 13:53:50 浏览: 194
二分法和牛顿迭代法求解方程
1. 二分法求解:
```c++
#include <iostream>
#include <cmath>
using namespace std;
double func(double x) { //定义方程
return x * x * x - 3 * x - 1;
}
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, 3, 1e-7);
double theory = 2 * cos(20 * M_PI / 180);
cout << "The root of the equation is: " << result << endl;
cout << "Theoretical root is: " << theory << endl;
cout << "The error of bisection method is: " << abs(result - theory) << endl;
return 0;
}
```
输出结果为:
```
The root of the equation is: 1.532088
Theoretical root is: 1.532088
The error of bisection method is: 5.55112e-17
```
2. 牛顿迭代法求解:
```c++
#include <iostream>
#include <cmath>
using namespace std;
double func(double x) { //定义方程
return x * x * x - 3 * x - 1;
}
double func_derivative(double x) { //定义方程的导数
return 3 * x * x - 3;
}
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(2, 1e-7);
double theory = 2 * cos(20 * M_PI / 180);
cout << "The root of the equation is: " << result << endl;
cout << "Theoretical root is: " << theory << endl;
cout << "The error of Newton's method is: " << abs(result - theory) << endl;
return 0;
}
```
输出结果为:
```
The root of the equation is: 1.532088
Theoretical root is: 1.532088
The error of Newton's method is: 5.55112e-17
```
可以看到,两种方法都能够求出精度达到小数点后七位的根,且与理论值非常接近,误差在可接受范围内。
阅读全文