i have a problem with the code i have written to find the squareroot of a number here is the code http://pastebin.com/0Dr5yAkk the problem is that say if we enter 4 the computer should leave the loop for ans=2 but it takes one more guess...(please just make one change in code increase the ans by 0.001 instead of 0.01)
there should be in the reading materials for the course an explanation of dealing with floating point errors. i think the 2008 course had this mentioned in one of the lectures, i would bet that one of the early 2011 lectures does also. I can't recall but there is probably an explanation in the Tutorial in the Python documentation which should be installed on your computer; also there is probably something in "How to Think Like a Computer Scientist...." your problem is at line 9 and it is due to floating point inaccuracies.
even if the problem is in line 9 , then say for x=4 when the ans reaches value 2 it must exit the while loop but rather it makes one more guess 2.001 and then exits the loop(i had checked by introducing a print command in the while loop portion)
thanks anyways but i forgot to mention just increase the ans by 0.001 and then see the difference. it`ll give 2.001 as the ans for x=4 and by the way what did you do in line 7 could you explain can tell me a more competent (perhaps a better one) code that will also take into consideration the floating point error.
line 7 is prints a formatted string 7.1.3, 7.1.3.1 and 7.3.1.2 in the python standard library documentation shows how to use the string format() method. \t is a tab character http://docs.python.org/library/string.html#format-string-syntax http://docs.python.org/release/1.6/ref/strings.html
again, the problem is because of floating point errors. this shows why ans has to go to 2.001 - http://dpaste.com/803795/ 1.007 cannot be accurately stored as a binary number - the value that gets stored is a little less than 1.007. after that, ans never catches up, it is always a bit less than it should be so it has to go one more iteration to satisfy the the while condition: http://dpaste.com/803800/
this is why it is sometimes necessary to define an accuracy tolerance for testing floating point results. - http://dpaste.com/803804/
thank you ! finally i got the concept of floating point error
Join our real-time social learning platform and learn together with your friends!