Simple Functions: nr2.py

The Newton Raphson method works with many functions, and not just the $4x - cos(x)$ 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” or function.

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




#! /usr/local/bin/python3                                                       

# Primitive code for finding roots of a function                                
# using the Newton-Raphson method                                               

# Physics 6720 9/09/17                                                          

# Usage                                                                         
#   nr2.py                                                                      

import math,sys

N = 100    # Maximum number of iterations                                       

############################################################                    
def f(x):
    """Evaluate the function"""
    return 4*x - math.cos(x)

############################################################                    
def dfdx(x):
    """Evaluate the derivative of the function"""
    return 4 + math.sin(x)

############################################################                    
def main():

    # The user is prompted for the tolerance and the starting point.            
    tol = eval(input(“Enter tolerance: “))
    pnew = eval(input(“Enter starting value x: “))

    for i in range(N):
        p = pnew
        # Evaluate the function and its derivative                              
        # The Newton-Raphson step                                               
        pnew = p - f(p)/dfdx(p)

        # Check for convergence and quit if done                                
        if math.fabs(p-pnew) < tol:
            print(“NR converged after”, i, “iterations”)
            print(“Root is”, pnew, “to within”, tol)
            sys.exit(0)

    # We reach this point only if the iteration failed to converge              
    print(“Failed to converge after”, N, “iterations.”)
    sys.exit(1)
############################################################                    
main()



Subsections