Zhi Sleepy Low
Zhi Sleepy Low

Reputation: 11

Binary Search in Python, infinite loop?

I'm having a bit of trouble with a problem from an online course (Introductory Python). Essentially, we are told to use binary search to find the lowest fixed payment each month to clear out a debt in a year (rounded to the nearest $0.01), when given a balance and an annual interest rate. My solution, when uploaded to their online grader, gives me only this error:

"There was a problem running your solution. We couldn't run your solution."

Am I possibly in an infinite loop? If so, I don't quite see how. The original code is posted below. Thank you all for taking the time to read this!

MonthlyInterestRate = annualInterestRate/12
month = 1
LB = balance/12
UB = balance*(2.7/12)
check = balance
while abs(balance) > 10:
    payment = (LB + UB)/2
    while month <= 12:
        balance = (balance - payment)*(1 + MonthlyInterestRate)
        month = month + 1
    if balance > 10:
        LB = payment
        balance = check
    elif balance < -10:
        UB = payment
        balance = check
    else:
        print('Lowest Payment: ' + str(payment))
        break

Upvotes: 0

Views: 425

Answers (1)

Dunes
Dunes

Reputation: 40683

It seems that the likely culprit is that you never reset the value of month after the inner while loop. That is, once inner has executed once it will never execute again. This means that the value of balance will not change and you will be stuck in an infinite loop.

Since you're only using month to iterate a set number of times you should really change the inner loop to

for m in range(month):
    balance = (balance - payment)*(1 + MonthlyInterestRate)

edit:

Scratch that, just playing around with your function it seems that it quickly converges on a some if the starting balance is greater than 13. If balance is less than 10 then your function decreases balance so it definitely doesn't terminate. If the balance is less than 13 then it seems to terminate in 1 iteration.

And I tested the function with different annual interest rates and it makes absolutely no difference to the outcome. The convergent number seems to be approximately 90% of the start balance. This is one borked function.

Upvotes: 2

Related Questions