[Tutor] newton's sqrt formula
Alan Gauld
alan.gauld at btinternet.com
Tue Feb 3 01:44:27 CET 2009
"WM." <wferguson1 at socal.rr.com> wrote
> square = input ('Please enter a number to be rooted, ')
> square = square * 1.0
Use raw_input() instead of input() and don't multiply
by 1.0 - instead convert to float using float():
square = float( raw_input ('Please enter a number to be rooted, '))
> guess = input('Please guess at the root, ')
> guess = guess * 1.0
> newguess = 0.
>
> while guess**2 != square:
> # Newton's formula
> newguess = guess - (guess * guess - square) / (guess * 2)
> guess = newguess
You could just combine these two
guess = guess - (guess * guess - square) / (guess * 2)
> guess**2 - square
That line does not do anything!
> print
> print
> print guess, ' is the square root of ', square
> print
> print
> print 'bye'
Partly a style thing but I would prefer you either used triple
quoted strings and format chars or inserted \n characters.
ie either:
> print """
%s is the square root of %s
bye""" % (guess, square)
OR
print "\n\n\n",guess," is the square root of", square,"\n\n\nbye!"
Or combine both:
print "\n\n\n%s is the square root of %s\n\n\nbye!" % (guess, square)
Actually, if it was me I'd use two prints:
print "\n\n\n%s is the square root of %s" % (guess, square)
print"\n\n\nbye!"
> I offer this rewrite for your critique. Can it be terser, faster,
> prettier?
> Thank you.
Not very critical but maybe it helps...
Alan G.
More information about the Tutor
mailing list