C语言实现牛顿-拉夫逊法求解方程根
下面是一个使用C语言实现牛顿-拉夫逊法(Newton-Raphson Method)求解方程根的代码示例:
#include <stdio.h>
#include <math.h>
#define EPSILON 0.00001 // 精度设定
// 定义方程,这里以求解 x^3 - x - 1 = 0 为例
double equation(double x) {
return pow(x, 3) - x - 1;
}
// 定义方程的导数,即 f'(x)
double derivative(double x) {
return 3 * pow(x, 2) - 1;
}
// 牛顿-拉夫逊法函数
double newtonRaphson(double x0) {
double x = x0;
double x_prev;
do {
x_prev = x; // 保存上一次的迭代结果
// 牛顿-拉夫逊法迭代公式
x = x - (equation(x) / derivative(x));
} while (fabs(x - x_prev) > EPSILON); // 判断精度是否足够
return x;
}
int main() {
double x0 = 1.5; // 初始猜测值
double root = newtonRaphson(x0);
printf("方程的根为: %f\n", root);
return 0;
}
这段代码实现了牛顿-拉夫逊法(Newton-Raphson Method)来求解方程根。首先,我们定义了要求解的方程 equation(x) 和方程的导数 derivative(x)。然后,实现了牛顿-拉夫逊法的迭代函数 newtonRaphson(x0),其中 x0 是初始猜测值。在迭代过程中,通过牛顿-拉夫逊法的迭代公式,不断更新 x 的值,直到满足设定的精度要求。
在 main() 函数中,我们设定初始猜测值 x0,然后调用 newtonRaphson(x0) 来求解方程的根。最后,使用 printf() 函数输出方程的根。
你可以根据需要修改和适应这段代码,修改方程和方程的导数的定义以适应你要求解的具体方程。
原文地址: https://www.cveoy.top/t/topic/bNbW 著作权归作者所有。请勿转载和采集!