用c语言写出分别用下面几种方法求解方程 x 3 -2x-5=0 在 x0=2 附近的根,计算到 4 位有效 数字。 1) 二分法 2) 牛顿法 3) 割线法(取 x0=2, x1=2.2)
时间: 2024-09-30 17:05:38 浏览: 60
在C语言中,我们可以使用三种不同的数值方法来求解方程 \(x^3 - 2x - 5 = 0\) 在初始点 \(x_0 = 2\) 附近的根,并保留四位有效数字:
1) **二分法(Binary Search Method)**:
```c
#include <stdio.h>
#include <math.h>
double bisection(double a, double b, double epsilon, int max_iter) {
if (b - a < epsilon) return (a + b) / 2; // 如果区间太小直接返回平均值
while (max_iter > 0) {
double mid = (a + b) / 2;
if (pow(mid, 3) - 2 * mid - 5 == 0) break; // 找到零点则退出
else if (pow(mid, 3) - 2 * mid - 5 < 0) a = mid;
else b = mid;
max_iter--;
}
return round(mid * 1e4) / 1e4; // 四舍五入到四位有效数字
}
int main() {
double root = bisection(1.9, 2.1, pow(10, -4), 100); // 设置精度和最大迭代次数
printf("Root using Bisection: %.4lf\n", root);
return 0;
}
```
2) **牛顿法(Newton-Raphson Method)**:
```c
#include <stdio.h>
double f(double x) { return pow(x, 3) - 2 * x - 5; }
double df(double x) { return 3 * pow(x, 2) - 2; }
double newton(double x0, double epsilon, int max_iter) {
if (fabs(df(x0)) < epsilon) return x0; // 若导数近似为0,说明已找到根
for (int i = 0; i < max_iter && fabs(f(x0)) > epsilon; ++i) {
x0 -= f(x0) / df(x0);
}
return round(x0 * 1e4) / 1e4; // 四舍五入到四位有效数字
}
int main() {
double root = newton(2.0, pow(10, -4), 100);
printf("Root using Newton's method: %.4lf\n", root);
return 0;
}
```
3) **割线法(Secant Method, 取 \(x_0 = 2\), \(x_1 = 2.2\))**:
```c
#include <stdio.h>
double secant(double x0, double x1, double epsilon, int max_iter) {
if (fabs(x1 - x0) < epsilon) return (x0 + x1) / 2;
double y = (f(x1) - f(x0)) / (x1 - x0);
double xn = x0 - x1) > epsilon) {
x0 = x1;
x1 = xn;
y = (f(x1) - f(x0)) / (x1 - x0);
xn = x0 - f(x0) / y;
max_iter--;
}
return round(xn * 1e4) / 1e4;
}
int main() {
double root = secant(2.0, 2.2, pow(10, -4), 100);
printf("Root using Secant method: %.4lf\n", root);
return 0;
}
```
运行上述程序,你会得到各个方法找到的根,注意实际执行可能会因为浮点误差而略有差异。
阅读全文
相关推荐


















