While loop does not show any output

68 views Asked by At

Please find time to answer this question.

When I print the following code, my while loop does not show any output.

import math
epsilon=.000000001

def mysqrt(a):
    while True:
       x=a/2
       y=(x+a/x)/2
       if abs(y-x)<epsilon:
         return (y)
        



def test_square_root():
    a=1.0
    print ('a'," " , "mysqrt(a)", " ", "math.sqrt(a)", " ", "diff")
    while a<10.0:
       print (a," " , mysqrt(a), math.sqrt(a),abs(mysqrt(a)-math.sqrt(a)))
       a+=1
     
test_square_root()

For the time being, I am not concthe erned about formatting of the table. I just need the following output. I am using the square root formula y=(x+a/x)/2

a mysqrt(a) math.sqrt(a) diff
1.0 1.0 1.0 0.0
2.0 1.41421356237 1.41421356237 2.22044604925e-16
3.0 1.73205080757 1.73205080757 0.0
4.0 2.0 2.0 0.0
5.0 2.2360679775 2.2360679775 0.0
6.0 2.44948974278 2.44948974278 0.0
7.0 2.64575131106 2.64575131106 0.0
8.0 2.82842712475 2.82842712475 4.4408920985e-16
9.0 3.0 3.0 0.0
3

There are 3 answers

0
Mahboob Nur On

I have modified your code slightly and the code is working for me

import math

epsilon = 1e-9

def mysqrt(a):
    x = a / 2
    while True:
        y = (x + a / x) / 2
        if abs(y - x) < epsilon:
            return y
        x = y

def test_square_root():
    a = 1.0
    print('a', 'mysqrt(a)', 'math.sqrt(a)', 'diff')
    while a < 10.0:
        result = mysqrt(a)
        print(a, result, math.sqrt(a), abs(result - math.sqrt(a)))
        a += 1

test_square_root()

My Console Output

0
Patryk Opiela On

For sure there is something wrong with mysqrt() function..

import math
epsilon=.000000001

def mysqrt(a):
    while True:
       x=a/2
       y=(x+a/x)/2
       if abs(y-x)<epsilon:
         return (y)
       else:
        return("abs(y-x) >= epsilon")
    
def test_square_root():
    a=1.0
    print('a', "mysqrt(a)", "math.sqrt(a)", "diff")
    while a<10.0:
       print(a, mysqrt(a), math.sqrt(a),abs(mysqrt(a)-math.sqrt(a)))
       a+=1.0

# test_square_root()
print(mysqrt(1))

Try to fix your mysqrt function

2
Ferret On

Let's state what's going on:

  1. You call a function (a)
  2. Your function (a) formats data using another function (b)
  3. Function (b) uses a while True loop with no limit, this means it'll repeat forever if the return is never called. This is why you're not printing anything

Your code also doesn't seem to be fully efficient, math shouldn't really be "searched" as there's almost always an algebraïc answer.

Please state what exactly you're trying to do and I'll try to explain it in a simpler way.