I'm creating a program that finds the lowest minimum payment necessary to pay of bank balance that that has interest. Given the initial balance and the annualInterestRate, I need to use a bisection search to find the lowest monthly payment to pay off of the balance by the end of the year. I've looked at the correct code and my code and I think the only difference is that it uses a variable called updatedBalance, which I don't see the need for. When I try to write my code, the program gets stuck into an infinite loop where the high and the low is the same.
This is the code to calculate the annual balance at the end of the year given the balance, annual interest rate and monthly payment. I'm fairly certain this has no bugs but this might be helpful to understand the rest of the code:
def returnAnnual(balance, annualInterestRate, monthlyPayment):
def updateBalance(balance, annualInterestRate, monthlyPayment):
monthlyInterestRate = annualInterestRate/12
#print ("Monthly Interest Rate:", monthlyInterestRate)
monthlyUnpaidBalance = balance - monthlyPayment
#print ("Monthly unpaid balance:", monthlyUnpaidBalance)
updatedBalance = monthlyUnpaidBalance + (monthlyInterestRate*monthlyUnpaidBalance)
return updatedBalance
months = 12
result = balance
while months >= 1:
result = updateBalance(result, annualInterestRate, monthlyPayment)
months -= 1
return result
This is the code that I used to complete the bisection search. For this instance I'm using the balance 999999 and annual interest rate of 0.18. The correct output I should get is 90325.03.
balance = 999999
annualInterestRate = 0.18
monthlyInterestRate = (annualInterestRate) / 12
epsilon = 0.01
numGuesses = 0
lowerBound = balance / 12
upperBound = (balance * (1 + monthlyInterestRate)**12) / 12
ans = (upperBound + lowerBound)/2.0
while abs(0 - balance) >= epsilon:
numGuesses += 1
n = returnAnnual(balance, annualInterestRate, ans)
if n >= 0:
lowerBound = ans
else:
upperBound = ans
ans = (upperBound + lowerBound)/2.0
print("Lowest Payment: " + str(round(ans, 2)))
The correct code utilizes an updated balance which, as far as I can see, is the only important difference between the two pieces of code. It's written as followed:
balance = 999999
annualInterestRate = 0.18
monthlyInterestRate = annualInterestRate/12
epsilon = 0.01
low = balance/12
high = (balance*(1+monthlyInterestRate)**12)/12
ans = (high + low)/2.0
n = returnAnnual(balance, annualInterestRate, ans)
while abs(=-n) >= epsilon:
print('low =', low, 'high =', high, 'ans=',ans, 'n=', n)
if n < 0:
low = ans
else:
high = ans
ans = (high + low)/2.0