next up previous
Next: Explanation of New Concepts Up: The Code Previous: Pseudocode

C++ code



// Primitive code for finding roots of 
//     4*x = cos(x)
// using the Newton-Raphson method

// Physics 6720 8/18/03

// Usage

//   nr

// The user is prompted for the tolerance and the starting point.

#include <iostream>
#include <cmath>
using namespace std;
#define N 100    // Maximum number of iterations

int main(){
  double p,pnew;
  double f,dfdx;
  double tol;
  int i;

  cout << "Enter tolerance: ";
  cin >> tol;
  cout << "Enter starting value x: ";
  cin >> pnew;

  // Main loop
  for(i = 0; i < N; i = i + 1){
    p = pnew;
    // Evaluate the function and its derivative
    f = 4*p - cos(p);
    dfdx = 4 + sin(p);
    // The Newton-Raphson step
    pnew = p - f/dfdx;
    // Check for convergence and quit if done
    if(abs(p-pnew) < tol){
      cout << "Root is " << pnew << " to within " 
	   << tol << "\n";
      return 0;
    }
  }
  // We reach this point only if the iteration failed to converge
  cerr << "Failed to converge after " << N << " iterations.\n";
  return 1;
}

Compile the code and run it to see how it works.

The compilation requires the -lm flag to get the trigonometric functions.



Carleton DeTar 2009-09-16