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)) ;
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;
}
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.....