Click here to Skip to main content
15,911,891 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Python
x = 25
epsilon = 0.01
step = epsilon**2
numGuesses = 0
ans = 0.0

while (abs(ans**2 - x)) >= epsilon and ans <= x:
    ans += step
    numGuesses += 1

print('numGuesses = ' + str(numGuesses))

if abs(ans**2-x) >= epsilon:
    print('Failed on square root of ' + str(x))

else:
    print(str(ans) + ' is close to the square root of ' + str(x))


What I have tried:

How does this program determine the square root?
Ans: I understood it. It reduces x by a small value i.e. 0.0001 i.e. step until x is less than epsilon. ans is incremented by ans += step. So when it reaches to the value greater than or equal to x, loop terminates.

I am not sure about this ans I wrote, tell me is this right or wrong
Posted
Updated 22-Jun-16 10:38am
v5
Comments
Richard MacCutchan 22-Jun-16 8:47am    
That's a math question, not a Python one.
Sergey Alexandrovich Kryukov 22-Jun-16 10:02am    
It is, essentially, not a Python question, but this is a question on a numeric algorithm, which I think is one of the topics of this forum. Please see Solution 1.
—SA

What's wrong? The whole idea. You use epsilon = 0.01 and write about the use of 0.0001. Fine, then try to find a square root not from 25, but from 0.000025 and see what happens. Of course, you can reduce epsilon, to make it a small fraction input value, but you cannot get any acceptable accuracy anyway. Two reasons for that are: 1) you only increase your "answer" ans, never decrease, 2) you use fixed step, that is, in your iterations, the accuracy of each iteration is not adopted as ans**2 gets closer to the input value.

And you even did not define any function for calculation of the root.

This is what works: Methods of computing square roots.

—SA
 
Share this answer
 
v4
Quote:
Ans: I understood it. It reduces x by a small value i.e. 0.0001 i.e. step until x is less than epsilon. ans is incremented by ans += step. So when it reaches to the value greater than or equal to x, loop terminates.
Wrong.
This program search for the square root of x by trying every possible ans in sequence starting at 0 and incrementing with a small value 0.0001 .
On every loop, the square of actual ans is compared to x until the difference is less than epsilon and ans is less that x.

The method is very naive and have many problems.
- it is slow, very slow, waaay slow.
- for x greater than 10000, you start to find values where ans never comes within the epsilon tolerance.
 
Share this answer
 

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