# -*- coding: utf-8 -*-
"""
Created on Sat Aug  6 12:06:41 2022

@author: Chris

Lab 2 Q2: Newton's method
"""

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    f = np.cos(x)-x
    return f

def dfdx(x):
    dfdx = -np.sin(x) - 1
    return dfdx

xc = 0.5    #initial estimate
tol = 1e-5

NMAX = 1000 #maximum iterations allowed

N = 1       # set up loop counter
while N<NMAX:
    x = xc - f(xc)/dfdx(xc) #do Newton step
    eps = abs(x - xc)   #compute the change since the last step
    
    print(N,x,eps)
    
    if (eps<tol):
        print("Final value:",x)
        
        break
    
    if N==NMAX:
        print("Warning: Maximum iterations exceeded")

    xc = x   # set xc to x at the end of the loop
    N = N+1
        
    
    
    



    
    
 
