gab gab - 11 months ago 55
Python Question

Why do I have an infinite loop in my code?

Below I have a piece of code which calculates credit card balance, but it doesn't work when

has an extreme value (such as
below). It throws the code through an infinite loop. I have a couple of theories as to how to fix this flaw, but don't know how to move forward with them. Here's my code:

balance = 9999999999
annualInterestRate = 0.2
monthlyPayment = 0

monthlyInterestRate = annualInterestRate /12
newbalance = balance
month = 0

while newbalance > 0:
monthlyPayment += .1
newbalance = balance

for month in range(1,13):
newbalance -= monthlyPayment
newbalance += monthlyInterestRate * newbalance
month += 1
print("Lowest Payment:" + str(round(monthlyPayment,2)))

My theory is that
while newbalance > 0

is causing the infinite loop, because newbalance is always larger than 0.

How can I change this
loop so that it doesn't cause my code to run infinitely?

By the way:
With moderate numbers, the program runs for a long time and finally gives an answer. For the larger numbers, the program just keeps on going.

Answer Source

The bisection method will execute much quicker if you're allowed to use it in your assignment. Will not help you though, if you're required to increment the monthly payment by .01.

static_balance = balance
interest = (annualInterestRate/12)
epsilon = 0.01
lo = balance/12
hi = balance

while abs(balance) > epsilon:
    balance = static_balance
    min_pmt = (hi+lo)/2
    for i in range(12):
        balance -= min_pmt
        balance *= 1+interest
    if balance > 0:
        lo = min_pmt
        hi = min_pmt
print("Lowest payment: ", round(min_pmt, 2))