Secant method
Please help? Not sure why it won't compile. Any suggestions?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double f( double ); // function whose root is sought
double secant( double, double, bool&);
int main()
{
const double MAX_ERROR = 0.00001;
double xGuess;
bool rootFound;
double rootApprox;
cout << "Enter an initial guess for a root of f => ";
cin >> xGuess;
rootApprox = secant( xGuess, MAX_ERROR, rootFound );
cout << setiosflags( ios::fixed ) <<
setprecision( 5 );
if (rootFound) {
cout << "Starting with an initial guess of " << xGuess <<
", Secant's method " << endl << "approximates a root of f at "
<< rootApprox << endl;
cout << "f( " << rootApprox << " ) = " << f(rootApprox) << endl;
}
return 0;
}
double secant( double xGuess, double okError, bool& converges )
{
const int MAX_ITER = 25;
double xN, xNplus1, xNminus1;
int iter = 0;
xN = xGuess;
do {
++iter;
xNplus1 = (xNminus1* f( xN )-xN*f ( xNminus1)) / (f (xN)- f ( xNminus1));
xN = xNplus1;
} while (xNplus1 >= okError && iter < MAX_ITER);
if (xNplus1 < okError) {
converges = true;
return xN;
} else {
cout << "Newton's method did not converge to a root of f "
<< "in " << MAX_ITER << endl << "iterations using an initial"
<< " guess of " << xGuess << endl;
converges = false;
return xGuess;
}
}
double f ( double xN)
{
int x;
return x*x+1;
}
| |
Last edited on
Topic archived. No new replies allowed.