#! /usr/local/bin/python3
# Primitive code for finding roots of a function
# using the NewtonRaphson 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 NewtonRaphson step
pnew = p  f(p)/dfdx(p)
# Check for convergence and quit if done
if math.fabs(ppnew) < 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()
