Newton-Raphson method

From Programming In C

Exercise 4.2

Note: this is an example of an actual assessment

The Newton-Raphson Method is a powerful method of finding the roots of the function f(x), that is the values of x for which f(x) = 0. Suppose that xold is an estimate of the root. Then a better estimate is xnew which is defined by:

xnew = xold-f(xold)/g(xold)

where g(x) = df(x)/dx.

This procedure is iterated until convergence is achieved, defined by |xnew – xold| < acc, where acc is a user-defined accuracy.

Use the Newton-Raphson method to find the root of the function f(x) = exp(-x) – x, starting the iteration at x = -10.0.

Use a do-while loop (or equivalent) algorithm.

How many iterations are required to obtain an accuracy (acc) of 10-6, and what is the solution at this accuracy ?

Solution

//Ex 4.2 Newton-Raphson method
//
#include<stdio.h> 
#include<stdlib.h>
#include<math.h>

int main()
{                                        
   const double acc = 1.0e-6; // requested accuracy
   double xnew = -10.0; // starting value
   double xold = 0.0;      
   double f,g;
   int count = 0; // keeps track of number of iterations  
   do      
   {
      xold = xnew;   
      f = exp(-xold) - xold;
      g = -exp(-xold) - 1.0;
      xnew = xold - f/g;
      count++;
      printf(" it %d f %g g %g xold %g xnew %g \n",count,f,g,xold,xnew);
   }
   while ( fabs(xnew - xold) > acc);      
                
   printf("Root is %g in %d iterations\n",xnew,count);

  system("pause"); 
  return 0;
} 

Note for demonstrators
Root is 0.567143 in 14 iterations. Care is needed in the placement of the xold=xnew; statement. If placed at the end of the loop then the while condition is immediately met leading to a single pass through the loop.


Return to the course summary

phy225: Course Details

general


compilers


2011-12 assessments


2010-11 assessments


past exam papers

  • 2008-9 (http://physics-database.group.shef.ac.uk/exampapers/2008-09/PHY225%20LT.pdf)
  • 2009-10 (http://physics-database.group.shef.ac.uk/exampapers/2009-10/PHY225%20Exam%20Sem%201%202009-10.pdf)
  • 2010-11 (http://physics-database.group.shef.ac.uk/exampapers/2010-11/PHY225_10_11.pdf)