对信用卡债务和最低支付的最低支付使用二分搜索

时间:2013-02-25 20:22:57

标签: python bisection

我的代码:

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))

当我测试时,它会卡在“月份&lt; 13:”

的行上

为什么要这样做以及如何解决?

2 个答案:

答案 0 :(得分:1)

如果你在内心的每个循环中突破,你仍然不到13岁。

这一直在继续,因为您继续While True并且不更新guess

我担心你在那里面临无限循环。

您的break语句会破坏最近的循环,即While month < 13循环。下一行未读。 guess未更新。 while True没有被打破。

也许你想说

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 :(得分:1)

你在这里

不是最好的解决方案,但它有效

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) )