[Tutor] newton's square root formula
Andre Engels
andreengels at gmail.com
Tue Feb 3 09:03:12 CET 2009
On Tue, Feb 3, 2009 at 3:59 AM, WM. <wferguson1 at 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, andreengels at gmail.com
More information about the Tutor
mailing list