Reputation: 11
I am new to Python and stackoverflow. I have been trying to solve Pyschools 'while loop' example for square root approximation (Topic 5: Question 9). However I am unable to get the desired output. I am not sure if this issue is related to the loop or the formula. Here is the question:
Create a function that takes in a positive number and return 2 integers such that the number is between the squares of the 2 integers. It returns the same integer twice if the number is a square of an integer.
Examples:
sqApprox(2)
(1, 2)
sqApprox(4)
(2, 2)
sqApprox(5.1)
(2, 3)
Here is my code:
def sqApprox(num):
i = 0
minsq = 1 # set lower bound
maxsq = minsq # set upper bound
while i*i<=num: # set 'while' termination condition
if i*i<=num and i >=minsq: # complete inequality condition
minsq = i
if i*i<=num and i <=maxsq: # complete inequality condition
maxsq = i
i=i+1 # update i so that 'while' will terminate
return (minsq, maxsq)
If I create this function sqApprox(4)
and call it on IDE, I get output (2, 0)
.
Could someone please let me know what I am doing wrong? Thanks in advance.
Upvotes: 1
Views: 387
Reputation: 52008
This is why your code does what it does:
After the line maxsq = minsq
is executed, both of those values are 1.
When we come to the loop
while i*i<=num: # set 'while' termination condition
if i*i<=num and i >=minsq: # complete inequality condition
minsq = i
if i*i<=num and i <=maxsq: # complete inequality condition
maxsq = i
i=i+1 # update i so that 'while' will terminate
first note that inside the loop i*i<=num
, so there is no need to retest it. Thus it is equivalent to:
while i*i<=num:
if i >=minsq:
minsq = i
if i <=maxsq:
maxsq = i
i=i+1
In the first pass through the loop i == 0
but maxsq == 1
, making the second condition true, hence setting maxsq
equal to the current value of i
, which is 0. In subsequent passes through the loop, i <= maxsq
is false (since maxsq == 0
but i > 0
) hence maxsq
is never moved beyond 0. On the other hand, the first condition in the while loop keeps updating minsq
as intended.
I would recommend forgetting about both minsq
and maxsq
completely. Have the loop simply be:
while i*i <= num:
i += 1 #shortcut for i = i + 1
When the loop is done executing, a simple test involving i-1
is enough to determine what to return.
Upvotes: 1