1

I am writing a code to print a table for the square root. But it doesn't loop. I need it to loop.

import math
                
def test_sqrt():
    a = 1
    def my_sqrt(a):
        while True:
            x = 1
            y = (x + a/x) / 2.0
            if y == x:
                return y

    while(a < 26):
        print('a = ' + str(a) + ' | my_sqrt(a) = ' + str(my_sqrt(a)) + ' | math.sqrt(a) = ' + str(math.sqrt(a)) + ' | diff = ' + str(my_sqrt(a) - math.sqrt(a)))
        a = a + 1
        

test_sqrt()
2
  • 1
    Which while loop are you referring to? Commented Feb 27, 2022 at 17:48
  • How do you know it doesn't loop? What values have you tried it with? What were the results? Edit the question. See how to create a minimal reproducible example. Commented Feb 27, 2022 at 17:49

4 Answers 4

1

You're almost there:

import math
            
def test_sqrt():
    a = 1
    err = 1e-6

    def my_sqrt(a):
        x=1
        while True:
            y = (x + a/x) / 2.0

            if abs(y-x)<err:
                return y
        
            x = y

    while(a < 26):
         print('a = ' + str(a) + ' | my_sqrt(a) = ' + str(my_sqrt(a)) + ' | math.sqrt(a) = ' + str(math.sqrt(a)) + ' | diff = ' + str(my_sqrt(a) - math.sqrt(a)))
        a = a + 1
    

 test_sqrt()

Notes:

  1. The initial value of x is defined at the beginning, not each loop
  2. The value of x needs to be updated each loop, if we haven't returned from the function
  3. The computation is continued until it is close enough, absolute difference is less than err
Sign up to request clarification or add additional context in comments.

Comments

0

Reason is that python is going into infinite loop when a=2. This can be checked via debugger.

Comments

0

Cause you built an infinite while-loop in your my_sqrt(a) function:

def my_sqrt(a):
    while True:
        x = 1
        y = (x + a/x) / 2.0
        if y == x:
            return y

With the second run you have y != x (unequal), hence there is no changing in y or x within the infinite loop, the loop will never break by reaching the return y.

By this, the loop:

while(a < 26):
    print('a = ' + str(a) + ' | my_sqrt(a) = ' + str(my_sqrt(a)) + ' | math.sqrt(a) = ' + str(math.sqrt(a)) + ' | diff = ' + str(my_sqrt(a) - math.sqrt(a)))
    a = a + 1

runs once an then gets stuck on the second iteration of the my_sqrt(a) function when a = 2.

Comments

0

You are stuck in an endless loop when a = 2 and you call my_sqrt(2):

my_sqrt(2):
    x = 1
    y = (x + a/x) / 2.0 = 1.5

Since all of the variables x, a and y are constant in that context, the if y == x: condition is never used. So you stay stuck in the while True: loop forever.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.