CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

1. Junior Member
Join Date
Oct 2008
Posts
8

## Secant Method problems

I'm trying to implement the secant method, but I'm having a problem. No matter the function or the initial guesses I use, I get the output "The solution is 0 and it was found in 2 iterations." I think my problem lies in the while loop, but my brain is mush and I can't pick it out.

Code:
```#include <iostream>
#include <math.h>
using namespace std;
double x0, x1, x, tol=0.5e-6;
int N = 2, Nmax = 100;

double f(double x) {return x*x - 4.0;}

double secant(double &x, double x0, double x1)
{
while ( (fabs ((f(x1)-f(x0))/f(x1)) > tol) && (N <= Nmax));
{
x = x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0));
x1 = x;
x0 = x1;

N++;
}

return x;
}

int main () {
cout << "Secant Method: \n\n";
cout << "Give the first initial approximation to a root. \n";
cin >> x0;
cout << "Give the second initial approximation to a root. \n";
cin >> x1;

if (N > Nmax)
cout << "In " << Nmax << " iterations, no solution was found. \n";
else
cout << "The solution is " << x << " and it was found in "
<< N << " iterations. \n";
return 0;
}```
Thank you!

2. Elite Member Power Poster
Join Date
Aug 2000
Location
West Virginia
Posts
7,712

## Re: Secant Method problems

1) Well, for one, you never call the secant() function.

2) You want to remove the semi-colon at the end of the line:

Code:
`while ( (fabs ((f(x1)-f(x0))/f(x1)) > tol) && (N <= Nmax)) ;`

3. Junior Member
Join Date
Oct 2008
Posts
8

## Re: Secant Method problems

I never would have caught that semi-colon.

This is what I have now, and it seems to work. Thanks!
Code:
```#include <iostream>
#include <math.h>
using namespace std;
double x0, x1, x, N = 2.0, tol=0.5e-6;
int Nmax = 100;

double f(double x) {return x*x-4.0;}

double secant(double &x, double x0, double x1)
{
while ( (fabs ((f(x1)-f(x0))/f(x1)) > tol) && (N <= Nmax))
{
x = x1 - ((f(x1) * (x1 - x0)) / (f(x1) - f(x0)));
x0 = x1;
x1 = x;

N++;
}

return N;
}

int main () {
cout << "Secant Method: \n\n";
cout << "Give the first initial approximation to a root. \n";
cin >> x0;
cout << "Give the second initial approximation to a root. \n";
cin >> x1;

N = secant(x, x0, x1);

if (N > Nmax)
cout << "In " << Nmax << " iterations, no solution was found. \n";
else
cout << "The solution is " << x << " and it was found in "
<< N << " iterations. \n";
return 0;
}```

4. ## Re: Secant Method problems

1) Every compiler I am familiar with should have issue3s a warning on the "Rogue" semicolon.

2) if a function is only going to be called from within the same compilation unit (typically same CPP), it should always be declared as "static" (making it file scope!)

You should have gotten one warning, and with proper codign, the compiler would have pointed out both of your mistakes.....

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•