I I
I I

Reputation: 41

having trouble formatting if-else statement in python

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

Upvotes: 2

Views: 135

Answers (2)

ely
ely

Reputation: 77464

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 between x0 and x1 but you could still be on the right track to finding the root. You wouldn't want to jump out of the iterations just because x1 is different than x0 on some iteration.

A better thing would simply be to place the error statement outside of the for loop, such as:

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 we exhaust the for-loop without returning due to
# a found root, then there must have been an error with
# convergence, so just print that at exit.
print "Error: did not converge to the root in %d iterations."%(N)
print "Check your initial guess and check your functions for cyclic points."

Upvotes: 1

quodlibetor
quodlibetor

Reputation: 8433

I would guess, not having done anything with Newton's method in forever, that what you want is something more like:

x1 = sys.maxint # the first iteration is a throw-away
                # you could do this a different way, but you have a lot of global 
                # variables that I don't know how to handle.
for i in range(N):
    # ....
    if abs(x1-x0)<tol:
        # ...

    # you want these two lines together, somehow.
    x0 = x1
    x1 = x0 - f/s

    #...
    # no "else" down here

# no "if abs(x1-x0)>tol:", because it's taken care of by the return(0)
# earlier. Also note the unindent.
print "root not found"

Upvotes: 0

Related Questions