Reputation:
I would like to iterate an existing for loop so many times that when I take the average of the resulting list, they converge. I am unsure of how to do this and appreciate suggestions.Looping to infinity or a really large number? Is there a more elegant method?
Thank you.
Upvotes: 1
Views: 8564
Reputation: 365747
While looping to infinity (with for loop in itertools.count():
) would work, there doesn't seem to be any reason to make things that complicated, since you aren't planning to use that counter.
If you just want to loop until a condition is true, use a while
loop:
while not converged():
# your code here
If you can't conveniently put that converged()
test at the head of the loop, just loop forever and test in the body:
while True:
# your code here
if converged():
break
I'm not sure exactly what you mean by "converged" here, but it sounds like it might involve the results being close enough to the previous loop's results? If so, you'll need to keep those previous results around to test against.
For example:
lastavg = None
while True:
# your code
avg = statistics.mean(FinalLengths)
if lastavg is not None and math.isclose(avg, lastavg):
break
lastavg = avg
Or maybe you want to know whether the change was in the same direction as and smaller than the previous change? Then you'd need to keep the two previous averages, or the previous average and the previous change. Whatever you want should be easy to do.
Upvotes: 2