Next: What is New Here? Up: nr2 Previous: nr2

# Simple Functions: nr2.cc

The Newton Raphson method works with many functions, and not just the of the previous chapter. So it is convenient to separate the Newton-Raphson machinery, which is unchanged, from the function, whose roots we seek and which may be changed from one application to the next. Separating code into modular functional units is a highly desirable software engineering practice. We do this by using a subprogram.

Here is the same code as in the previous lesson, but it uses subprograms for evaluating the function and its derivative.

 // Primitive code for finding roots of a function // using the Newton-Raphson method // Physics 6720 8/18/03 // Usage // nr // The user is prompted for the tolerance and the starting point. #include #include #define N 100 // Maximum number of iterations using namespace std; double f(double x){ return 4*x - cos(x); } double dfdx(double x){ return 4 + sin(x); } int main(){ double p,pnew; 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; // The Newton-Raphson step pnew = p - f(p)/dfdx(p); // Check for convergence and quit if done if(fabs(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; }

Subsections

Carleton DeTar 2007-08-17