-->

对信用卡债务和支付最低使用二分法搜索(Using Bisection Search on Lowes

2019-11-01 16:32发布

我的代码:

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

当我测试了它卡住在行“而一个月<13”

它为什么这样做,我该如何解决?

Answer 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 


Answer 2:

这个给你

没有是最好的解决方案,但它的工作原理

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


文章来源: Using Bisection Search on Lowest Payments on Credit Card debt and