In Lecture 3: when we calculate the square root of 25, why do we have (in line 5 of the script) "...and ans <= x" ? Can't understand what purpose that serves?
The while loop will run forever if we fail to find the square root of x. Like when the professor changes the increment of ans to 1 instead of 0.0001 the first condition of while that abs(ans^2 -x) > epsilon will always be true. So it will keep executing the code and the program will never terminate. However by the second condition when ans gets greater than x, then the while loop will be false and we'll get out of it. That's what I understand by it. I'm not an expert just watched lecture 4 now.
Hi Waztaz, thanks for your reply. To backtest, I changed the increment of ans to 1 (instead of 0.0001), and removed the 'ans <=x' condition from the while statement --> I still get the answer. I suspect the reason you say is correct but I need to think more carefully and corroborate. Thanks!
You must further analyze the code. There are certain scenarios where the program would continue forever without the 'ans<=x' at the end. If the number you input for x is smaller than the amount that you increment, it is possible to skip over your target. If that happens, since the increment is a static positive number, the exit condition for the loop will never be met and the loop will run forever. The 'ans <=x' is there to safeguard against that.
Join our real-time social learning platform and learn together with your friends!