Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 23 Online
OpenStudy (anonymous):

Ok I'm stuck here. Code is to find the true square root of a number give or take by 0.01. x = 25 epsilon = 0.01 numGuesses = 0 ans = 0.0 while abs(ans**2 - x) >= epsilon and ans <= x: ans += 0.00001 numGuesses += 1 print 'numGuesses =', numGuesses if abs(ans**2 - x) >= epsilon: print 'Failed on square root of', x else: print ans, 'is close to square root of', x -------------------------------------- I can't figure out this line... while abs(ans**2 - x) >= epsilon and ans <= x: ans is 0.0 to begin with, so 0.0squared is 0, minus 25, is -25. Which is

OpenStudy (anonymous):

Correct but abs is absolute thus -25 becomes 25 which is indeed >= epsilon and ans which is 0.0 is <= 25

OpenStudy (anonymous):

you probably do not need this ' and ans <= x' in your while statement.

OpenStudy (anonymous):

I missed that sneaky abs, Thank you!

OpenStudy (anonymous):

Hi bwCA, I think maybe that line is there so that we can change the value of epsilon and it will still guarantee that the loops terminates? Because if the step is too big it will skip the answer and keep going?

OpenStudy (anonymous):

maybe

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!