#! /usr/local/bin/python3
# Primitive code for finding roots of
# 4*x = cos(x)
# using the NewtonRaphson method
# Physics 6720 8/28/17
# Usage
# ./nr.py
# The user is prompted for the tolerance and the starting point.
import sys, math
N = 100 # Maximum number of iterations
tol = eval(input("Enter tolerance: "))
pnew = eval(input("Enter starting value x: "))
# Main loop
for i in range(N):
p = pnew
# Evaluate the function and its derivative
f = 4*p  math.cos(p)
dfdx = 4 + math.sin(p)
# The NewtonRaphson step
pnew = p  f/dfdx
# 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)
