David
David

Reputation: 23

Why do I get into an infinite loop with this simple Python code?

balance = 4773
annualInterestRate = 0.2

pay = 10

while balance > 0:
    for key in range(1,13):
        balance -= pay
        balance = balance + (balance * (annualInterestRate / 12.0))
    pay += 10

print('Lowest Payment: '+str(pay))

When balance is 3329, it returns the good result of 310 but when 4773 I get into an infinite loop instead of getting the result of 440...

Upvotes: 0

Views: 114

Answers (2)

Maxime Chéramy
Maxime Chéramy

Reputation: 18851

At each iteration of the while loop, balance increases, so it keeps greater than 0. You can print the intermediate values of balance:

balance = 4773
annualInterestRate = 0.2

pay = 10

while balance > 0:
    print balance
    for key in range(1,13):
        balance -= pay
        balance = balance + (balance * (annualInterestRate / 12.0))
    pay += 10

Output:

4773
5686.32508646
6666.19699272
7727.21549777
8887.18344195
10167.8094501
11595.5648257
13202.7284403
15028.6608622
17121.3580173
...

Can you explain how you would obtain 440? With which calculus? So we can try to fix your code. It looks like 3390 is the greater (integer) initial value you can set to balance that converges.

In your loop, you do:

balance -= pay
balance = balance + (balance * (annualInterestRate / 12.0))

which is equivalent to:

balance = balance - pay + ((balance - pay) * (annualInterestRate / 12.0))

or:

balance = balance + balance * (annualInterestRate/12) - pay * (annualInterestRate/12)

Let's simplify but putting pay2 = pay * (annualInterestRate/12). So, basically, balance will decrease if pay2 is greater than the interest balance * (annualInterestRate/12).

In order to better understand what's going on, imagine it's a race between the interests and the increase of pay. The interests are greater than pay at the beginning so it keeps increasing but at some point, pay might be big enough to reduce the balance and at this point, pay will always be greater than the interest. However, if the interests start at a high level, the interest will grow and the pay will never reach the amount of interest (that's actually sad). The mathematical reason is that pay is linear whereas the interests are not and increase more and more as the balance continues growing.

Upvotes: 2

aIKid
aIKid

Reputation: 28332

Nothing's wrong witht the code. With your formula, the increase of balance at 4773 is more than the increase of payment, which is 10. That explains why the balance keeps growing to infinity, and thus the loop never ends.

while balance > 0:
    for key in range(1,13):
        balance -= pay
        balance = balance + (balance * (annualInterestRate / 12.0))
    pay += 10

I think you might want to lower your interest, or make your salary higher, so you can pay your debt :)

Upvotes: 1

Related Questions