c - 在 C 中找到函数的第一个转折点

标签 c eclipse while-loop calculus

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

#define PI 3.14159265

int main()
{
    setvbuf(stdout,NULL,_IONBF,0);
    setvbuf(stderr,NULL,_IONBF,0);
    double x, y;        
    double a=0.4+(6019.0/25000.0);          
    double diff;
    double diff2;

    x=0;          //Starting Value of x=0
    diff=a;     //Setting diff to start with value of 'a'. Because at x=0, f'(x)=a


    while(fabs(diff)>0)     //Starts a while loop, which runs until diff<=0
    {
        diff=(a*pow(x, a-1)-((1/a)*pow(x, (1/a)-1)+a)) * cos(pow(x, a) - pow(x, 1/a) + (a*x));      //f'(x)
        x+=0.0001;      

    }

printf(" The First Maximum Turning Point is at x=%g\n",x);      //prints the x coordinate of the TP

return 0;
}

我正在尝试使用 C 中的线性搜索方法找到函数的第一个转折点。

您可以忽略我的“y”变量,因为它与代码的较早部分无关。

我正在尝试使用 while 循环将 x 放入 dy/dx(我已经验证导数是正确的),而 while |dy/dx| > 0(也不是转折点),x 每次都会略微增加,直到 dy/dx 达到零。然后它的意思是在此时打印 x 的值。

然而,当我运行这段代码时,我得到的只是一个永无止境的循环。

如果我改用 while(diff>0),我得到的 x 值与正确值相去甚远。

我真的迷失在这里,非常感谢任何帮助。

谢谢。

最佳答案

这里的问题是您将 double 值与零进行比较,这是永远不会满足的,结果是永无止境的循环。

例如

  if(.00001 > 0 )// a true value

  if(.00000000000000000001 > 0 )//is still true.

因此您的 while 循环变成了永无止境的循环。因此尝试像下面这样的东西

   while(fabs(diff)> .00001 )  

关于c - 在 C 中找到函数的第一个转折点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47023462/

相关文章:

c - 三元并转换为 qsort 参数

java - 使文件丢失,Eclipse

python - 将 html 作为字符串循环一次

c - scanf使while循环自动运行2次

c++ - 使用 MSVC 编译基于 make 的项目?

c - Notepad++ 的函数列表功能不正确

c - fopen - C 中作为流数据的原始数据

java - 如何通过 Android 模拟器从我的电脑访问我的 webapp?

java - 使用应用程序引擎时权限被拒绝

php - 基于 <select> PHP/Mysql 更改输入值