Python Bisection search overshoots target

428 views Asked by At

I have to create a code to find the exact payment, to the cent, needed to pay off a loan in 12 months using bisection. The code I created for this works but it overshoots it's target. The loan will be payed off within the 12 months but after making 12 payments the final balance should be around 0. However it is a way bigger negative number.

The code I am using is:

StartBalance = float(raw_input('Credit Balance in $: '))
AnnualRate = float(raw_input('Annual interest rate in decimals: '))
MonthlyRate = AnnualRate / 12.0
MinPaymentLow = StartBalance / 12.0
MinPaymentHigh = (StartBalance*(1+MonthlyRate)**12.0)/12.0
cent = 0.01
Payment = (MinPaymentHigh+MinPaymentLow)/2.0

while (Payment*12-StartBalance) >= cent:
    for month in range(0, 12):
        Balance = (StartBalance-Payment)/10*(1+MonthlyRate)   
    if Balance < 0:
        MinPaymentLow = Payment
    elif Balance > 0:
        MinPaymentHigh = Payment
    Payment = (MinPaymentHigh + MinPaymentLow)/ 2.0

print 'RESULT'           
print 'Number of months needed: 12'
print 'Montly pay: $', round(Balance,2)
2

There are 2 answers

0
James On BEST ANSWER

It looks like these lines:

for month in range(0, 12):
    Balance = (StartBalance-Payment)/10*(1+MonthlyRate)   

Should be:

Balance = StartBalance
for month in range(0, 12):
    Balance = (Balance-Payment) * (1 + MonthlyRate)  

Or something similar, depending on how you want to calculate interest, and whether you consider payments occurring at the start or end of the month.

1
blakev On

Your code seemed to work fine for me, but if you're getting results that are "way off" it's probably because you're using the float datatype. Float is untrustable, because it rounds on every operation. Given enough iterations and you've rounded off a lot of money. Try using decimal instead. This module keeps track of decimals as indexed integer values.