Using Bisection Search in the lowest credit card debt payments and

My code is:

monthlyInterestRate = annualInterestRate/12.0 low = balance/12 high = (balance*(1+monthlyInterestRate)**12)/12 guess = (low+high)/2 unpaidBalance = balance month = 1 while True: unpaidBalance= unpaidBalance-guess while month < 13: if unpaidBalance <= -0.1: low = guess month += 1 elif unpaidBalance >= 0.1: high = guess month += 1 else: break guess = (low + high)/2 print "Lowest Payment: " + str(round(guess, 2)) 

When I test it, it gets stuck in the line "while month <13:"

Why is he doing this and how to fix it?

0
python bisection
source share
2 answers

If you break every cycle of the inner while, you stay less than 13.

And it goes on and on as you continue While True and not update your guess .

I am afraid that you are faced with an endless cycle.

Your break statement breaks the closest loop, i.e. the While month < 13 loop. The next line is not readable. guess not updated. While True not broken.

Perhaps you wanted to say

 while month < 13: unpaidBalance= unpaidBalance-guess if unpaidBalance <= -0.1: low = guess elif unpaidBalance >= 0.1: high = guess month += 1 guess = (low + high)/2 
+1
source share

Here you

No, this is the best solution, but it works.

 monthlyPaymentRate = (balance*annualInterestRate/12)/((1-(1+annualInterestRate/12)**-12)) interest = monthlyPaymentRate * (annualInterestRate/12) #print (monthlyPaymentRate) #print (interest) monthlyPaymentRate = (monthlyPaymentRate - interest) +1 #print (monthlyPaymentRate) balanceInit = balance epsilon = 0.01 low = monthlyPaymentRate while low*12 - balance > epsilon: balances = balanceInit for i in range(12): minpay = monthlyPaymentRate unpaybal = balances - minpay interest = (annualInterestRate /12) * unpaybal smontfinal = unpaybal + interest balances = smontfinal #print('Remaining balance: ' ,round(balances,2) ) if balances <0: low = -1 break if balances < 0 : low = -1 else: monthlyPaymentRate =monthlyPaymentRate + 0.001 print('Lowest Payment:' ,round(monthlyPaymentRate,2) ) 
+1
source share

All Articles