Python: Program keeps getting into a infinite loop when using float
Here is my original working program:
def num_rushes(required_height, rush_height_gain, back_sliding):
current_height = 0
rushes = 0
while current_height < required_height:
rushes += 1
current_height += rush_height_gain
if current_height >= required_height:
break
else:
current_height -= back_sliding
return rushes
print num_rushes(100, 15, 7)
What this program does it calculates how many "rushes" it takes until we reach the desired height (required_height
), after each rush (rush_height_gain
), we fall back by a given amount (back_sliding
).
What I am trying to is after each rush, is multiply the height gained by 0.95 (we lose 5% of the rush each time).
As you can see below, what I have done is converted rush_height_gain to a float and then added the line rush_height_gain *= 0.95
into my while loop, however for some reason, which I cannot seem to figure out, I end up with an 开发者_如何学Goinfinite loop.
def num_rushes(required_height, rush_height_gain, back_sliding):
current_height = 0
rushes = 0
rush_height_gain = float(rush_height_gain)
while current_height < required_height:
rushes += 1
current_height += rush_height_gain
if current_height >= required_height:
break
else:
current_height -= back_sliding
rush_height_gain *= 0.95
return rushes
print num_rushes(100, 15, 7)
Any help as to why this occurs and how can I get my desired result would be greatly appreciated.
Cheers.
rush_high_gain
gets smaller with each pass through the while-loop
. But back_sliding
stays constant. If enough passes are made through the loop (about 15), rush_height_gain
may be less than backsliding
. At that point current_height
will get smaller and smaller, and you will never exit the loop.
If you temporarily add a print
statement into your loop to show the values of relevant variables at each iteration, you'll see that because you keep shrinking rush_height_gain
, it eventually becomes smaller than back_sliding
. Once that happens, the object slides back further than it goes up at each step, so you wind up actually losing height. That means that if you haven't reached required_height
by that point, you never will.
Probably the easiest solution is to change your loop condition to stop if current_height
becomes negative, or alternatively if rush_height_gain
becomes less than back_sliding
. Alternatively, you could change the way you compute rush_height_gain
so that it never becomes less than back_sliding
.
精彩评论