问题描述:
利用弦截法求方程的根。
方法:弦截法和牛顿法很像。以下给出两个公式。
牛顿法:。弦截法:
。其实就是将牛顿法中的 f ' 斜率,用y/x表示罢了。函数差值除与两点之间的距离得到斜率。
具体计算过程如下:
代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<math.h>
double x, x0, x1;
//计算当前x的函数值f(x)
double caculatefx(double x) {
double c;
c = x * x * x - 5 * x * x + 16 * x - 80;//题目要求计算的方程式
return c;
}
double find_root(double x0, double x1) {
do {
double k, b;
k = (caculatefx(x0) - caculatefx(x1)) / (x0 - x1);//计算斜率
b = caculatefx(x0) - k * x0; //计算截距,为计算x的值作铺垫
x = -b / k; //根据k和b的值,可以求出x的值
if (caculatefx(x) * caculatefx(x0) < 0) {//f(x)与f(x0)异号,说明根在x和x0之间
x1 = x;
}
if (caculatefx(x) * caculatefx(x1) < 0) {//反之
x0 = x;
}
//while循环中,当f(x)函数值接近0时,认为找到了根
} while (caculatefx(x) < -1e-6 || caculatefx(x) > 1e-6);
return x;
}
int main() {
//一定要输入函数值异号的两个端点,不然这两个端点之间不可能有根
do {
printf("please input x0,x1:\n");
scanf("%lf,%lf", &x0, &x1);
} while (caculatefx(x0) * caculatefx(x1) >= 0);
find_root(x0, x1);//调用函数找到根
printf("the root is %.2f\n", x);
return 0;
}
运行结果截图:
上述要求函数的方程根为5。
如果该内容对你有小小的帮助,请给我点个赞!谢谢。