+ 6

How many zeros does it take?

Print(10 < 10.1) outputs True, of course, but print(10 < 10.000000000000000000000000001) outputs False Why can I see when numbers are unequal but the computer can't? I wrote this little code to pin down the number of zeros required to produce False, but it times out, and I'm not sure if the problem is my code or the platform. Thoughts welcome!! def num_of_zeros(n): i = 0 a = float("10." + "0" * i + str(n)) while (10 < a): i += 1 print(i) num_of_zeros(1)

17th May 2017, 12:52 PM
David Ashton
David Ashton - avatar
7 ответов
+ 1
here it is in the code playground. it runs fine, no timeouts https://code.sololearn.com/c68AXldXdmGM/?ref=app
17th May 2017, 3:07 PM
LordHill
LordHill - avatar
+ 3
@Kyle Thanks - now I've got it. I should have put a = float("10." + "0" * i + str(n)) inside the loop. I revised the code (and gave you a credit). https://code.sololearn.com/c6hPk05yqx9X/#py
17th May 2017, 3:37 PM
David Ashton
David Ashton - avatar
+ 2
@Kyle I'm not sure that's correct. The function prints i, not a. To test your theory, I shortened the number of loop cycles (because it times out on the code playground) by using while (10 < a and i < 2): instead of while (10 < a): and got the output 2
17th May 2017, 2:35 PM
David Ashton
David Ashton - avatar
+ 1
Happy to help David.. Keep up the good work!
17th May 2017, 3:38 PM
LordHill
LordHill - avatar
0
David.. Your code output is 10.1 10.1 10.1 10.1 etc The reason being you change I, but you don't change a.. Perhaps this will help. def num_of_zeros(n): i = 0 a = float("10." + "0" * i + str(n)) while (10 < a): a = float("10." + "0" * i + str(n)) print(a) i += 1 print(i) num_of_zeros(1)
17th May 2017, 2:16 PM
LordHill
LordHill - avatar
0
correct. but a is your number 10.0 + number of zeros. you print i after it's done to show how many runs it does. I print a inside your loop just to show the progress. my output is 10.1 10.01 10.001 etc. And when it is done running, it has your I listed as 16.. The only difference between my code and yours is that mine adds a 0 each time it runs where as yours runs indefinitely at 10.1
17th May 2017, 3:02 PM
LordHill
LordHill - avatar