Click here to Skip to main content
15,883,705 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Please find time to answer this question.

When I print the following code, my while loop does not show any output.
Python
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()


What I have tried:

I am trying to solve Allen Downey's 7.1.

For the time being i am not concerned about the format of the table. I need the following output. What is missing in my code?

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
Posted
Updated 10-Oct-23 23:30pm
v2

1 solution

Indentation in Python is significant: it controls what is and isn't in a block of code.
All the contiguous code indented by the same amount (or more) is part of the same code block:
Python
while foo == bar:
    Part of loop
    if (foo + bar == foobar:
        Still part of loop
Not part of loop - executed once the loop exits.

So your lack of indentation on the return statement means it isn't a part of the if or the while.
As a result, there is no way out of the loop and your app never does anything.

Indent it properly, and it should start to work:
Python
def mysqrt(a):
    while True:
       x=a/2
       y=(x+a/x)/2
       if abs(y-x)<epsilon:
           return(y)
However, you should note that you don't alter a or epsilon inside the loop, so either it will exit after the first iteration, or never ...
 
Share this answer
 
v3
Comments
Baziga 10-Oct-23 8:25am    
Can you please tell whether I should write x=a/2 inside the while loop or outside the while loop? Does it make any difference?
OriginalGriff 10-Oct-23 9:13am    
Are you planning on modifying "a" inside the loop at any point?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900