繁体   English   中英

使用C ++中的割线函数查找根

[英]Finding roots using the secant function in C++

我正在为自己正在上课的课程而苦苦挣扎。 我必须使用C ++中的secant方法找到函数的根。 我都写了,我发现第二个零是0.146。 但是,我的教授正在寻找的根是.064。 我已经尝试了所有可以做的事情,但是我不知道如何使它输出0.064。 他告诉我们放入一个包含功能的头文件,这是头文件:

    #define FX0 pow(x0, 3) - 0.165*pow(x0, 2) + 3.993E-4
    #define FX1 pow(x1, 3) - 0.165*pow(x1, 2) + 3.993E-4

这是代码:

    #include <iostream>
    #include <cmath>
    #include <iomanip>
    #include "Secant.h"
    #include "Keyboard.h"
    using namespace std;


    int main()
    {
    //Define Variables
    float x0,x1,x2,tolerance,maxIterations,count,FX;
    count = 0;
    x0 = 0.02;
    x1 = 0.05;
    tolerance = .000001;
    maxIterations = 100;
    FX = pow(x0, 3) - 0.165*pow(x0, 2) + 3.993E-4;

    //Loop statement that runs until a Zero is found
    while(fabs(FX0-FX1)>tolerance && count < maxIterations && fabs(FX)>tolerance)
    {
    x2=x1-(FX1*((x0-x1)/(FX0-FX1)));
         FX = pow(x2, 3) - 0.165*pow(x2, 2) + 3.993E-4;

    x0=x1;
    x1=x2;

    count++;
    }


    //Display the zero
    if (fabs(FX)<tolerance)      
    cout << "The zero is at x = " << setprecision(4) << x2;
    //Or Report that no zero was found
    else
    cout << "No zeroes were found within the given function.";

    return 0;
    }

使用#define时,编译器仅将FX1宏替换为其文本值(在这种情况下)。 所以

 FX1*((x0-x1)/(FX0-FX1))

变成

 pow(x1, 3) - 0.165*pow(x1, 2) + 3.993E-4*((x0-x1)/(pow(x0, 3) - 0.165*pow(x0, 2) + 3.993E-4-pow(x1, 3) - 0.165*pow(x1, 2) + 3.993E-4))

这会导致括号在错误的位置出现问题,而是将3.9993E-4乘以。

尝试将括号放在定义中,或者将其更改为函数。

#define FX0 (pow(x0, 3) - 0.165*pow(x0, 2) + 3.993E-4)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM