import numpy as np def newtonRap(fn,dfn,h,tol,maxiter): for iteration in range(maxiter): hnew=h-fn(h)/dfn(h) if np.abs(hnew-h)<tol:break e=np.abs((hnew-h)/hnew)*100 print("h=",h) print("Ea=",e) h=hnew return hnew, iteration fy= lambda h: h**3-9*h**2+3.8197 dfy= lambda h: 3*h**2-18*h h, n = newtonRap(fy,dfy,1,0.001,10) print("The root is %f at %d iteration." %(h,n))