On Tue, Feb 3, 2009 at 3:59 AM, WM. <wfergus...@socal.rr.com> wrote: > # program to find square root > square = float(raw_input ("Please enter a number to be rooted, ")) > guess = input("Please guess at the root, ") > i = 0 > while guess**2 != square: > i+=1 > # Newton's formula > guess = guess - (guess * guess - square) / (guess * 2) > print i > print "\n\n\n%s is the square root of %s" % (guess, square) > print "\n%s loops were run." % (i) > print "\n\n\nbye" > # > > > Here is my program, enhanced by Alan's good advice. The reason I wanted to > re-write the other program was, it had a limited number of loops and I felt > accuracy should be the measure. So, just now, I added a loop counter here > and found that the formula is a little buggy. Make 'square = 7' and you will > be in the 'i = 500' area before you can find ControlC.
The problem is the loop guard: while guess**2 != square There probably is no number guess for which Python has guess**2 == 7 exactly. You'll have to choose a certain precision, and look for a number for which this closer than your chosen precision rather than a number for which it is true exactly. Change the guard to: while abs(guess*guess-square) > 0.0000000000001: and (choosing 1 as my initial guess) I got an answer after 6 iterations. -- André Engels, andreeng...@gmail.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor