-1

Here is my code thus far. I don't know why it doesn't print anything. I hope it isn't because of some stupid mistake.

y = float(raw_input("Enter a number you want square rooted: ")) 
x = 0 
# Newton's Method: y = (x+y)/x + 2 
while y > x:
    x += 0.1 
    if x == y/(2*y-1):
        print x 
    else:
        pass 

Any suggestions or alternatives? Any help would be greatly appreciated.

Nayuki
  • 17,911
  • 6
  • 53
  • 80

1 Answers1

4

Your code doesn't resemble Newton's method at all. Here is code with rewritten logic:

y = float(raw_input("Enter a number you want square rooted: ")) 

# Solve f(x) = x^2 - y = 0 for x.
# Newton's method: Iterate new_x = x - f(x)/f'(x).
# Note that f'(x) = 2x. Thus new_x = x - (x^2 - y)/(2x).
prevx = -1.0
x = 1.0
while abs(x - prevx) > 1e-10:  # Loop until x stabilizes
    prevx = x
    x = x - (x*x - y) / (2*x)
print(x)

Side note: An alternate but similar way of iteratively approximating the square root is the Babylonian method.

Nayuki
  • 17,911
  • 6
  • 53
  • 80