On 01/04/14 02:07, Scott W Dunning wrote:
I’m working on a few exercises and I’m a little stuck on this one.

This is what the book has but it just gives me an endless loop.

def square_root(a, eps=1e-6):
        while True:
                print x
                y = (x + a/x) / 2
                if abs(y-x) < epsilon:
                        break


Are you sure that's what the book has?
If so I'd consider another book. That code is seriously broken.
- It prints x before an x is defined.
- It never modifies x and so the abs(y-x) will always be the
  same so the loop never breaks.
- it tests for epsilon but has eps as parameter
- It also never returns any value from the function.

round(square_root(9))

So this call will always try to round None(the default return value)
And of course it produces no output since it prints nothing.

Are you sure that's actually what is in the book?

I tweaked it to what I thought was correct but when I test it I get nothing 
back.

def square_root(a, eps=1e-6):
    x = a/2.0
    while True:
        y = (x + a/x)/2.0
        if abs(x - y) < eps:
            return y
        x = y

This is slightly better than the above, at least it creates an x and modifies it and returns a value.

And it seems to work on my system. How did you test it?

round(square_root(9))

If you used the >>> prompt this would have produced a result but if you used a script file you would need to print it.


HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to