# include # include # include using namespace std; // // We can declare SECANT and F1 here, and they will be usable by // any function within this file. // double secant ( double a, double b, double f ( double x ) ); double f1 ( double x ); int main ( ) // // SECANT_F1 is a program which uses SECANT to solve for a solution // of F1(X) = 0. // { // // A and B are the "bracket" values we've chosen for our function. // double a = -10.0, b = +10.0, c; c = secant ( a, b, f1 ); cout << "\n"; cout << "SECANT returned solution estimate C = " << c << "\n"; cout << "F1(C) = " << f1 ( c ) << "\n"; return 0; } double secant ( double x0, double x1, double f ( double x ) ) { int step; double fx0, fx1, fx2, x2; // // Initialization. // step = 0; fx0 = f ( x0 ); fx1 = f ( x1 ); // // Iteration loop. // while ( true ) { x2 = ( fx1 * x0 - fx0 * x1 ) / ( fx1 - fx0 ); fx2 = f ( x2 ); step = step + 1; // // Can we accept the new point? // if ( fabs ( fx2 ) < 0.000001 ) { break; } // // Quit if we take too many steps! // if ( 25 <= step ) { cerr << "SECANT - Too many steps!\n"; exit ( 1 ); } // // Prepare for next step. // x0 = x1; fx0 = fx1; x1 = x2; fx1 = fx2; } return x2; } double f1 ( double x ) // // F1 is our "cosine" function. // { double value; value = cos ( x ) - x; return value; }