/* An example of Newton's method file: 4ex4.cpp FALL 1998 ___________________________________ Jacob Y. Kazakia jyk0 October 1, 1998 Example 4 of week 4 Recitation Instructor: J.Y.Kazakia Recitation Section 01 ___________________________________ Purpose: This program estimates the root of the function f(x) = x^2 - 3, near x = 2 [ which in fact is + sqrt(3) ]using Newton's method of root finding. Algorithm: The improvements to our initial guess x0 are obtained by repeated use of the formula: x_new = x_old - ( f(x_old) / f'(x_old) ). The initial guess ( x0 ), the maximum number of iterations(nmax), the root tolerance (xtol), the function value tolerance (ftol) are all inputed through the keyboard. The root tolerance is defined as follows: The iterations will stop if | x_new - x_old | / | x_old | < xtol. The function value tolerance is defined as follows: The iterations will stop if | f( x_new) | < ftol. For accuracy all variables will be declared as double. */ #include #include #include void main() { double x_old = 0., x_new = 0 ; // estimates of the root double xtol = 0. , ftol = 0. ; // tolerances double f = 0. , fprime = 0. ; // values of the function and of its derivative int nmax = 0 ; // max number of iterations int n = 0 ; // running index cout <<" \n\n enter your initial guess of the root ... "; cin >> x_old; cout <<" \n\n enter the maximum number of iterations ... "; cin >> nmax; cout <<" \n\n enter the root tolerance ... "; cin >> xtol; cout <<" \n\n enter the function value tolerance ... "; cin >> ftol; // Prepare the heading of the table cout <<"\n\n x_old f(x_old) f'(x_old) x_new \n\n"; cout<< setiosflags(ios:: scientific); cout<< setprecision(10); // START THE LOOP for( n = 1; n <= nmax ; n++ ) { f = x_old * x_old - 3 ; fprime = 2 * x_old ; x_new = x_old - f / fprime ; cout<>hold; }