Hello, I need a little help with the correct implementantion of the bisection search algorithm in the following exercise:
- with 2 given variables, balance and annual interest rate, calculate the smallest monthly payment so that we can pay off the balance within a year
test case:
balance = 320000
annualInterestRate = 0.2
below are the provided formulae to use in the problem:
monthly_interest = annualInterestRate / 12
lower_bound = balance / 12
upper_bound = ( balance * ( 1 + monthly_interest)** 12) / 12
here is my code:
new_balance = balance
while new_balance > 0:
pay = (upper_bound + lower_bound) / 2.0
for month in range(1,13):
new_balance = (new_balance - pay) * (1 + monthly_interest)
if new_balance < 0:
lower_bound = pay
else:
upper_bound = pay
print "Lowest payment: " + str(round(pay,2))
This is a problem from MIT courseware. I am getting the wrong result 29591.55, where the correct output is
29157.09. I have inserted various print statements which revealed that my upper and lower bounds do not change, so it must be somewthing wrong with my loop conditions but even after a few days of working on this I can't see the mistake, so any help is appreciated. If possible, I want explanations as to what I am doing wrong so I can correct it rather than plain working code, I want to understand it not just solve it
Cheers