c - 牛顿拉夫森法中的无限循环

标签 c infinite-loop newtons-method

我正在编写一个程序来计算 lambda 的值,但它陷入了 do 循环中。它似乎没有更新 n 值,因为我希望通过设置 nMax = 100 它至少可以快速完成,以防其他情况(eps >= e_allow)从未发生。谁能发现无限循环是从哪里来的吗?

非常感谢您的帮助。我的程序是:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//Solution to Linear Dispersion Relationship for a Horizontal Bottom

double f ( double, double, double, double);
double df (double, double, double); 

int main(void) {


    float pi = 3.1415927;
    double g = 9.81;                //Acceleration due to gravity
    double omega;                  //Angular frequency of wave
    double kn, dk;             //Wave numbers
    double e_allow, eps;    //Tolerance used to find difference between kNew and kOld   
    int nMax, n;          // Setting up counter for iterations
    double lambda;                 //Value we need to solve for 
    double h, T;                   //Depth and Period. User needs to input these values.
    double fn, dfn;               //Declaring functions describing linear dispersion


    printf("Enter the value of the depth (m).\n");
    scanf("%lf", &h); 
    printf("\nEnter the value for the period (s).\n");
    scanf("%lf", &T);


    /* 
    Assuming shallow water conditions. Therefore, tanh(k*d) --> kd. kOld is calculated using 
    the relationship omega^2 = kold^2/(g*d) 
    */

    omega = (2.0 * pi)/T;
    printf("Angular velocity = %.5f\n", omega); 
    kn = sqrt((omega * omega)/(g * h));             
    printf("Wave number kn = %.5f\n", kn);

    e_allow = 1.0e-5;
    n = 0; 
    nMax = 100;

    //Following the Newton Raphson Method
    do {
        fn = f(kn, omega, g, h);
        dfn = df(kn, g, h);
        dk = -(fn/dfn);
        kn = kn + dk;
        eps = fabs(dk/kn);
        n = n + 1;
    } while (eps >= e_allow || n == nMax);


    //Calculating value of lambda using final kn value. 
    lambda = (2.0 * pi)/kn;


    //printf("\nfn = %.6f, dfn = %.6f, dx = %.6f, eps = %.6f\n", fn, dfn, dk, eps);


    printf("\nkn = %.5lf, Wavelength = %.5lf\n", kn, lambda); */

    //printf("fn = %.6lf, dfn = %.6lf, eps = %.6lf, dk = %.6lf, kn = %.6lf\n", fn, dfn, eps, dk, kn);



    return 0;

}


double f (double kn, double omega, double g, double h) {
    return ((omega*omega) - (g * kn * tanh(kn * h)));
}

double df (double kn, double g, double h) {
    return ((( g * kn * h )/( 1 + ( h * h * kn * kn ))) - g * tanh( kn * h));
}

最佳答案

你的导数有部分错误。您以某种方式插入了 arctan 函数的导数公式。

tanh(x) 的导数为 1/square(cosh(x))=1-square(tanh(x))。

并记住符号,减号不会在第一项中丢失。仅正确的符号即可使代码正常工作,而无需更正其余导数。

关于c - 牛顿拉夫森法中的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21905527/

相关文章:

c - 如何正确地从右向链表添加节点

javascript - 页面崩溃(可能是由于多维数组?)

algorithm - MatLab - 牛顿法算法

ruby - XIRR 实现的 bigdecimal/newton 错误

julia - 在 Julia 中实现多元牛顿法

c - 如何使用 MPI_Abort() 终止其他处理器

c - 为什么我无法在C语言中使用for循环比较两个字符串[如果字符串彼此相反]

c - 堆排序 : how to correct my coding and to implement my logic?

java - 异常处理导致的无限循环

Java:无限while循环中的If语句