""" lectureNote/chapters/chapt04/codes/try_except3.py try-except example, written by Prof. Dongwook Lee for AM 129/209. Modified by Ian May, FA2021 """ import numpy as np def fdf(x): f = x + np.exp(x) + 10/(1 + x**2) - 5 df = 1.0 + np.exp(x) - 20*x/(1 + x**2)**2 return f,df def root_finder(func, x0, thresh, MaxIter=100): # Put initial guess in list to store history x = [x0] # Query function at initial guess f,df = func(x0) res = [abs(f)] for i in range(0,MaxIter): # Raise error if slope is very flat if (abs(df)<1.e-5): raise ArithmeticError # Newton's iteration x.append(x[-1] - f/df) # Query function at new guess f,df = func(x[-1]) # Update residual res.append(abs(f)) print(x[-1],f,df) # Check for convergence if (res[-1] < thresh): break # If final residual is too big we stagnated if (res[-1] > thresh): raise ArithmeticError # Return sequence of guesses and residuals return x,res if __name__ == '__main__': # take an initial value as an input from users x0 = float(input("Please enter an initial search value: ")) # take a threshold value as an input from users threshold = float(input("Please enter a threshold value: ")) # Call Newton's method try: x, res = root_finder(fdf,x0,threshold) except ArithmeticError: print("Newton's method failed for that initial guess") else: print("Newton's method converged in %d iterations" % len(x)) for v,r in zip(x,res): print(v, r)