+ 1
The result is strange.
i = -1.05 while i <=5: print(i) i = i + 1 print("Finished!")
5 Respostas
+ 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.
+ 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.
+ 1
But why did these '4' appear?
0
What's strange about it?
0
-1.05
-0.050000000000000044
0.95
1.95
2.95
3.95
4.95
Finished!