用牛顿迭代法求方程的根——C语言实现

本文介绍牛顿迭代法原理及应用,通过C语言实现求解方程f(x)=0的根,展示了从算法构造到代码实现的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原理

参考链接牛顿法——知乎。比如说我想求一个函数 f ( x ) = 0 f(x)=0 f(x)=0的解,利用牛顿迭代法的话可以如下构造:
x n + 1 = x n − f ( x n ) f ′ ( x n ) x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)} xn+1=xnf(xn)f(xn)

代码

下面时C语言实现代码

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define N 200                                                               //最大迭代次数
#define EPS 0.000001                                                        //收敛误差
double newton(double (*fun)(double), double (*partialfun)(double), double); //牛顿迭代法,包括两个函数指针
double fun(double x);                                                       //原函数
double partialfun(double x);                                                //导函数
int main(int argc, char* argv[])
{
    double x0, root;
    x0   = 1;
    root = newton(fun, partialfun, x0);
    printf("迭代初值:%lf\n根:%lf\n", x0, root);
    return 0;
}
double fun(double x) //原函数
{
    return cos(x) - x * x * x;
}
double partialfun(double x) //原函数的导数
{
    return -sin(x) - 3 * x * x;
}
double newton(double (*fun)(double), double (*partialfun)(double), double xn)
{
    double xn1;
    for (int i = 0; i < N; i++) {
        xn1 = -(*fun)(xn) / (*partialfun)(xn) + xn;
        if (fabs(xn1 - xn) < EPS) {
            printf("迭代次数:%d\n", i+1);
            return xn1;
        }
        xn = xn1;
    }
    printf("迭代发散!");
    exit(0);
}

运行结果

方程cos(x)-x^3=0的解

牛顿迭代是一种数值优化算法,常用于寻找函数零点。在C语言中,我们可以利用这个方来逼近方程。以下是基本步骤: 1. **选择初始猜测**:首先需要选择一个接近解的初值`x0`。 2. **计算切线斜率**:对于函数f(x),其导数为f'(x)。在当前估计点附近,函数近似为直线,所以我们要找到的是这条直线的斜率,即f'(x0)。 3. **更新估计**:使用公式 `x_new = x_old - f(x_old) / f'(x_old)` 来更新估计值,这一步就是将函数图像的切线与x轴的交点作为新的近似。 4. **检查收敛条件**:如果新旧估计值的差满足一定的精度要(如绝对值小于某个阈值),则停止迭代;否则继续迭代到下一个循环。 5. **迭代直到达到收敛**:重复以上步骤,直到达到预设的迭代次数或满足收敛标准。 下面是一个简单的C语言实现牛顿迭代的例子: ```c #include <stdio.h> #include <math.h> double function(double x) { // 你要找的函数 } double derivative(double x) { // 函数的导数 } double newton_raphson(double initial_guess, double tolerance, int max_iterations) { double x_new = initial_guess; int iteration = 0; while (iteration++ < max_iterations && abs(function(x_new)) > tolerance) { x_new = x_new - function(x_new) / derivative(x_new); } return x_new; } int main() { double root = newton_raphson(0.0, 1e-6, 100); // 初始猜测为0,容忍度为1e-6次方,最多迭代100次 printf("The root is approximately %lf\n", root); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值