## Code for Newton Raphson square root computation

A forum for general discussion of the Python programming language.

### Code for Newton Raphson square root computation

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/2while 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

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.01guess = number/2.0while 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
• Use code tags when posting code.
• Include any errors with your post (in code tags).
• Make examples the minimum length to demonstrate your issue.

Mekire

Posts: 1711
Joined: Thu Feb 07, 2013 11:33 pm
Location: Tucson, Arizona

### Re: Code for Newton Raphson square root computation

Thank you.
Krishna

Posts: 2
Joined: Thu Apr 17, 2014 4:44 am