# include # include # include using namespace std; // // We can declare NEWTON and F1 here, and they will be usable by // any function within this file. // double newton ( double x, double f ( double x ), double fp ( double x ) ); double f1 ( double x ); double fp1 ( double x ); int main ( ) // // NEWTON_F1 is a program which uses NEWTON to solve for a solution // of F1(X) = 0. // { // // X0 is the starting value. // double x0 = -0.0, x; x = newton ( x0, f1, fp1 ); cout << "\n"; cout << "NEWTON returned solution estimate X = " << x << "\n"; cout << "F1(X) = " << f1 ( x ) << "\n"; return 0; } double newton ( double x0, double f ( double x ), double fp ( double x ) ) { int step; double fx1, x1; // // Initialization. // step = 0; cout << step << " " << x0 << " " << f ( x0 ) << "\n"; // // Iteration loop. // while ( true ) { x1 = x0 - f ( x0 ) / fp ( x0 ); fx1 = f ( x1 ); step = step + 1; cout << step << " " << x1 << " " << f ( x1 ) << "\n"; // // Can we accept the new point? // if ( fabs ( fx1 ) < 0.00000001 ) { break; } // // Quit if we take too many steps! // if ( 15 <= step ) { cerr << "NEWTON - Too many steps!\n"; exit ( 1 ); } // // Prepare for next step. // x0 = x1; } return x1; } double f1 ( double x ) // // F1 is our "cosine" function. // { double value; value = cos ( x ) - x; return value; } double fp1 ( double x ) // // FP1 is the derivative of F1. // { double value; value = - sin ( x ) - 1; return value; }