My program finds the roots using newton’s algorithm. I am having trouble with a last part when if there is not enough iterations to find the root to print that the root has not been found.
for i in range(N):
f= evaluate(p,deg,x0)
s=evaluate(d,deg-1,x0)
if s==0:
print "Can't divide by 0"
return -1
x1=x0 - f/s
print ("Iteration %d" %(i+1))
print "%f" %x0
if abs(x1-x0)<tol:
print "Found a root %f" %x1
return 0
else:
x0=x1
if abs(x1-x0)>tol:
print "root not found"
somehow it seems to skip the last if statement and doesn’t print anything, i tried to put it in different places. when i placed it before the previous if-statement then it skips the x0=x1 part. Im confused of whats wrong with it.
N is the number of iterations, x0 is the initial guess
The logic is not correct for displaying that a root is not found. You do not want to check that
abs(x0 - x1) > tol, because this is not relevant for finding a root. Think about it: the difference could be very large betweenx0andx1but you could still be on the right track to finding the root. You wouldn’t want to jump out of the iterations just becausex1is different thanx0on some iteration.A better thing would simply be to place the error statement outside of the
forloop, such as: