在信用卡债务最低还款上使用二分查找

0 投票
2 回答
1747 浏览
提问于 2025-04-17 17:05

我的代码:

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

当我测试它的时候,程序在“while month < 13:”这一行卡住了。

这是为什么呢?我该怎么解决这个问题?

2 个回答

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

撰写回答