### Secant Method

Im supposed to be finding the roots on a function using the secant method. Im pretty sure i have the equation right but it isnt giving me the right answer. The answer i am supposed to get is 0.0624 but im way off. I dont think its my actual equation im thinking something needs to be different in the loop but im not sure what. Any help would be appreciated.

the values im entering are
.02
.05
.000001
100

this is the Secant header file so i can easily test out different functions
#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 this is keyboard.h, just something he gave us to use instead of cout and cin
 ``123456789101112`` ``````//pre: the string (character literal) that will prompt the user for input //post: the input read from the keyboard interpreted as an int is returned int readInt(const char prompt[]); //pre: the string that will prompt the user for input //post: the input read from the keyboard interpreted as a double is returned double readDouble(const char prompt[]); //pre: the string that will prompt the user for input // the string to store the user input and the length of the input storage string //post: the text read from the keyboard is copied into the storage string void readString(const char prompt[], char str[]);``````

Here is my main code
 ``123456789101112131415161718192021222324252627282930313233343536373839`` ``````#include #include #include using namespace std; #include "Secant.h" #include "Keyboard.h" int main () { float x2 = 2; double x0 = readDouble("Enter x0: "); cout << x0 << endl; double x1 = readDouble("Enter x1: "); cout << x1 << endl; double tolerance = readDouble("Enter tolerance: "); cout << tolerance << endl; int max = readInt("Enter max number of iterations: "); cout << max << endl; int n = 1; while(( n <= max ) && (x2 >= tolerance)) { x2 = x1 - ((FX1 * (x1 - x0)) / (FX1 - FX0)); x0 = x1; x1 = x2; n++; cout << x2 <
Your loop looks fine... maybe a little syntax tweaking could be done, but there's nothing "wrong" with it.

 ``123456789101112`` ``````while(( n++ <= max ) && (x2 >= tolerance)) { x2 = x1 - ((FX1 * (x1 - x0)) / (FX1 - FX0)); x0 = x1; x1 = x2; cout << x2 <<'\n'; if ((FX0 - FX1) < tolerance) { cout << "No zeros were found\n"; break; } }``````

I suspect the issue is with your #define for FX0 and FX1,

`#define identifier replacement `

I'd recommend you put brackets around the equation in the #define, like this:
 ``12`` ``````#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) ``````

Remember, BODMAS. :~)

Last edited on
Thanks for the help! Turns out I had the wrong variable with >= tolerance and I also needed parenthesis around the FX0 and FX1 in my equation which was why my answer was wrong.
Topic archived. No new replies allowed.