CodingCowboy
CodingCowboy

Reputation: 1

Finding roots using the secant function in C++

I'm struggling with a program for a class I am taking. I have to find the roots of a function using the secant method in C++. I have it all written and I find the second zero at 0.146; however, the root my professor is looking for is .064. I have tried everything I can thing of but I can't figure out how to make it output a 0.064. He told us to put in a header file that has the the function in it, here is the header file:

    #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

and here's the code:

    #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;
    }

Upvotes: 0

Views: 1980

Answers (1)

The Dark
The Dark

Reputation: 8514

When you use #define, the compiler just replaces your FX1 macro with its text value (in this case). So

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

becomes

 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))

which leads to problems with brackets in the wrong spot it is multiplying the 3.9993E-4 through instead.

Try putting brackets around your defines, or perhaps change them into functions.

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

Upvotes: 3

Related Questions