The result is strange. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

The result is strange.

i = -1.05 while i <=5: print(i) i = i + 1 print("Finished!")

4th Apr 2018, 1:26 PM
Максим Сергеев
Максим Сергеев - avatar
5 Answers
+ 3
To explain it as simply as I can for you, it's because of how numbers and data are stored in bits. The more bits you have to store the number (the more decimal places) the less accurate it becomes. When we use math outside of computers, we're not bound by having to store it in bits in memory, so we don't run into the same issue with precision there; however, that's why we have precision issues when dealing with computers. It tries to round it, but as you can probably guess with math, that creates some inaccuracy when doing so, especially as you continue computing with the number.
4th Apr 2018, 1:51 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 4
Yeah, that's right. Of course, precision drops off well before 18 places, but still right for the most part. I assume you don't want that many decimal places? Try this: i = -1.05 while i <=5: print(round(i,2)) i = i + 1 print("Finished!") ::: OUTPUT ::: -1.05 -0.05 0.95 1.95 2.95 3.95 4.95 Finished! ^That'll round out the number to 2 decimal places to keep it consistent for you.
4th Apr 2018, 1:31 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 1
But why did these '4' appear?
4th Apr 2018, 1:38 PM
Максим Сергеев
Максим Сергеев - avatar
0
What's strange about it?
4th Apr 2018, 1:28 PM
Fata1 Err0r
Fata1 Err0r - avatar
0
-1.05 -0.050000000000000044 0.95 1.95 2.95 3.95 4.95 Finished!
4th Apr 2018, 1:30 PM
Максим Сергеев
Максим Сергеев - avatar