C++。谁能帮我找出我用简单迭代法求解方程的代码中的错误?我得到像 -1.#IND00 这样的解决方案

标签 c++


我正在尝试使用 C++ 帮助求解下一个方程:3sin(sqrt(x)) + 0.35x - 3.8 = 0
有解的区域是[2, 3]

我写了下一个代码:

float f(float x)
{
    return (3 * sin(sqrt(x))) + (0.35 * x) - 3.8; //this is equation i am trying to solve
}

float g(float x, float(*f_ptr)(float)) 
{
    const float CONST = 0.1f; //const used to solve equation

    return CONST * f_ptr(x) + x;
}

void Task4_CalculateSomething()
{
    float x0, //starting aproximation
        xk, //current aproximation
        a = 2, //left barrier
        b = 3, //right barrier
        epsilon = 0.001; //allowed error

    const float REAL_SOLUTION = 2.2985; //real solution of selected equation

    printf("Setup starting aproximation: ");
    scanf("%f", &x0);

    do
    {
        xk = g(x0, f); //calc current aproximation

        if (fabs(xk - x0) < epsilon) //if Xn - Xn-1 fits the allowed error, the solution must be found
            break; //then we exit
        else
            x0 = xk; //else reset x values
    }
    while (fabs(a - x0) > epsilon && fabs(b - x0) > epsilon);

    printf("Found solution: %f\nReal solution: %f\n", xk, REAL_SOLUTION);
}

但它给了我奇怪的结果,比如 -1.#IND00,我什至不知道它是什么。
而且我在那里找不到任何错误...

最佳答案

在高层次上,发生的事情是:

  1. 您的算法无法正常工作。
  2. 在某个迭代中,xk 变为负数。
  3. 当它传递给 sqrt 时,返回一个 NaN。
  4. 迭代终止。
  5. 调用 printfNaN 显示为 -1.#IND00

您可以使用调试器识别所有这些,甚至可以使用放入一些调试 printf 输出的老式技术。例如,添加一些代码以在循环的每次迭代中打印 xk

既然您知道解决方案在 [2,3] 中,我个人会使用括号根查找器。例如,bisection .

关于C++。谁能帮我找出我用简单迭代法求解方程的代码中的错误?我得到像 -1.#IND00 这样的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10676180/

相关文章:

C++ 对象不保存值

c++ - 如何在 VC++ 中重新启动我自己的应用程序

c++ - Qt 连接到 std::function

c++ - 字符到整数的转换?

c++ - 为什么我需要写 "std::string"而不是 "std::getline()"?

c++ - 不可内联的函数

c++ - C++基础程序抛出的错误

null - 检查列表中的每个列表是否在 Common Lisp 中为空

c++ - 为什么派生类不使用基类 operator=(赋值运算符)?

c++ - 如何将 qmake 项目移植到 cmake