Gold University of Minnesota M. Skip to main content.University of Minnesota. Home page.
 
 
 

What's inside.

Ta Email

Download Compiler

Final Project

Lab Notes

Office Hours

Schedule

Syllabus

Announcements

Check Grades

 

CSci 1113 Home

 
 

Printer-friendly version

 
Newton-Raphson Root Finding Method

Algorithm:

xi+1 = xi - f(xi)/f'(xi)

Example:
find the roots of f(x) = 2x2 -x -21


% cat newt2.cpp
// Newton-Raphson method for finding the
// roots of f(x) = 0 for a polynomial function
#include <iostream>
using namespace std;

#include <cmath>

int main()
{
  double a, b, c, x1, x0, crit, delta;
  int iters = 0;
 
  cout << "Enter values for a, b, and c :";
  cin >> a >> b >> c;

  cout << "Enter a guess for the root :";
  cin >> x0;
 
  cout << "Enter the convergence criterion: ";
  cin >> crit;

  // use a do-while loop
 
  do
  {
     x1 = x0 - (a*x0*x0 + b*x0 + c) / ( 2*a*x0 + b);

     delta = fabs ( x1 - x0 );    

     x0 = x1;  // new approximation becomes the old
               // approximation for the next iteration

     iters++;  // count the number of iterations

  } while (delta > crit && iters <= 100);

  cout << "One root is " << x1 << endl;
  cout << "Found in "  << iters
       << " iterations" << endl;

  return 0;

}

% g++ newt2.cpp
% a.out
Enter values for a, b, and c :2 -1 -21
Enter a guess for the root :9
Enter the convergence criterion: .00001
One root is 3.5
Found in 6 iterations
cswanson@mega (~/spring06) % a.out
Enter values for a, b, and c :2 -1 -21
Enter a guess for the root :-10
Enter the convergence criterion: .00001
One root is -3
Found in 6 iterations
 
The University of Minnesota is an equal opportunity educator and employer.
CSci 1113: C++ Programming