I am a beginner to python and was wondering why the code spans for infinity when it should've been stopped at 1.
def main():
i = 0.0
while i != 1.0:
print("i =", i)
i += 0.1
main()
I am a beginner to python and was wondering why the code spans for infinity when it should've been stopped at 1.
def main():
i = 0.0
while i != 1.0:
print("i =", i)
i += 0.1
main()
This is a well known problem in Python.
Your variable i
never becomes exactly 1, but instead becomes 0.9999999999999999.
Do instead:
def main():
i = 0.0
while i <= 1.0:
print("i =", i)
i += 0.1
In the general case, of course you shouldn't compare floats by equality, but there's more to it: when you're adding like this you get floating point accumulation error.
You can use an integer counter instead and apply multiplication every time to avoid that.
def main():
i = 0.0
count = 0
while i < 1.0:
print("i =", i)
count += 1
i = count*0.1
main()
I have replaced i != 1.0
by i < 1.0
because that's all you need, but it even works with !=
(although I don't recommend that) now because there's no accumulation error anymore the way it's computed with the integer counter.