Code for Newton Raphson square root computation

A forum for general discussion of the Python programming language.

Code for Newton Raphson square root computation

Postby Krishna » Thu Apr 17, 2014 4:51 am

Hello,
I'm a novice in Python. As part of an exercise, I tried to compute the square root of a number using Newton Raphson's method.
It compiled perfectly, but failed to run.(Blank Screen in the Terminal)

Here's the code -
Code: Select all
number = 24           #Number to be computed - I avoided raw_input() thinking that might be the cause.
epsilon = 0.01        # Least error tolerable in the computation of the square root.
guess = number/2

while abs(guess*guess - number) >= echleon:
   guess = guess - (((guess**2) - number)/(2*guess))

print guess, 'is close to the answer'
Last edited by Mekire on Thu Apr 17, 2014 5:04 am, edited 2 times in total.
Reason: First post lock. Code tags.
Krishna
 
Posts: 2
Joined: Thu Apr 17, 2014 4:44 am

Re: Code for Newton Raphson square root computation

Postby Mekire » Thu Apr 17, 2014 5:15 am

Well for starters, you wrote epsilon here:
Code: Select all
epsilon = 0.01        # Least error tolerable in the computation of the square root.
but wrote echleon here:
Code: Select all
while abs(guess*guess - number) >= echleon:

After fixing that, you do indeed enter an infinite loop. This is because this:
Code: Select all
guess = guess - (((guess**2) - number)/(2*guess))
is doing integer division, not floating point division.

Division in Python 2 (not Python 3) defaults to integer division if both numbers are ints.

Float the numerator or the denominator to fix:
Code: Select all
number = 24           
epsilon = 0.01
guess = number/2.0

while abs(guess*guess-number) >= epsilon:
    guess -= (guess**2-number)/float(2*guess)

print("{:.5f} is close to the answer.".format(guess))
Result:
Code: Select all
4.89899 is close to the answer.

-Mek
User avatar
Mekire
 
Posts: 1025
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Code for Newton Raphson square root computation

Postby Krishna » Thu Apr 17, 2014 7:38 am

Thank you.
Krishna
 
Posts: 2
Joined: Thu Apr 17, 2014 4:44 am


Return to General Discussions

Who is online

Users browsing this forum: W3C [Linkcheck] and 3 guests