-2

我试图弄清楚如何使用平分搜索来查找:

每月还款以清除贷款金额

  • 月利率=(年利率)/12
  • 月供下限=余额/12
  • 月供上限 = (余额 x (1 + 月利率)12) / 12

目前我有:

balance = 6758
annualInterestRate = 0.20
monthlyRate = annualInterestRate/12
numGuesses = 0
lo = balance/12
hi = (balance)*((1+monthlyRate)**12)/12
monthPay = (hi + lo)/2.0
NuBalance = balance
while abs((NuBalance)*(1+monthlyRate))-(monthPay) >= 0.01:
    print('low = ' + str(lo) + ' high = ' + str(hi) + ' MonthPay = ' + str(monthPay))
    numGuesses += 1
    if ((NuBalance)*(1+monthlyRate))-(monthPay) <= 0.01:
        print('Month Pay LO = ' + str(monthPay))
        lo = monthPay
    else:
        print('Month Pay HI = ' + str(monthPay))
        hi = monthPay
    monthPay = (hi + lo)/2.0
print('numGuesses = ' + str(numGuesses))
print('Month Pay = ' + str(monthPay))

任何对我出错的地方的帮助将不胜感激。

4

1 回答 1

2

它应该是:

while abs((NuBalance)*(1+monthlyRate)-(monthPay)) >= 0.01:
                                    ^           ^

并且一直存在

(hi + lo)/2.0 < (NuBalance)*(1+monthlyRate)

True因为hilo都小于(NuBalance)*(1+monthlyRate)

In [9]: print 'lo:', lo
lo: 563

In [10]: print 'hi:', hi
hi: 686.720412649

In [11]: print 'monthPay:', monthPay
monthPay: 624.860206325

In [12]: print '(NuBalance)*(1+monthlyRate):', (NuBalance)*(1+monthlyRate)
(NuBalance)*(1+monthlyRate): 6870.63333333
于 2012-10-11T10:40:52.417 回答