递归:找到最低的最低付款额

时间:2019-02-06 19:16:40

标签: python-3.x

我正在尝试使用递归和二等分搜索来计算1年后还清贷款所需的最低每月还款额。我的代码太低了(对于给定的余额,正确答案应该是29157.09),我不知道为什么。我试过没有运气地调整所有变量,只是看不到逻辑错误在哪里。

代码如下:

def lowestMinPaymt(bal, int, lbound, ubound):
    def eval_year(bal, int, pay, mnth=12):
        bal = (bal - pay) + ((bal - pay) * (int))
        return bal if mnth <= 0 else eval_year(bal, int, pay, mnth - 1)

    pay = (lbound + ubound) / 2
    b = eval_year(bal, int, pay)
    print("LOWEST PAYMENT CALLED")
    print(f'\nB: {b}\nINT: {round(int, 4)}\nPAY: {pay}\nL: {round(lbound, 4)}\nH: {round(ubound, 4)}\n')

    if -0.02 <= b <= 0.02:
        print(f'Pay within threshold, returning: {pay}')
        return round(pay, 2)
    elif b < -0.02:
        print(f'\n\tBalance overpaid, decreasing pay guess: PAY: {round(pay, 4)} L: {round(lbound, 4)} H: {pay}\n')
        return lowestMinPaymt(bal, int, lbound, pay)
    elif b > 0.02:
        print(f'\n\tBalance underpaid, increasing pay guess: L: {round(lbound, 4)} H: {pay}\n')
        return lowestMinPaymt(bal, int, pay, ubound)
    '''
    return pay if -0.02 <= b <= 0.02 else \
        lowestMinPaymt(bal, int, lbound, pay) if b < -0.02 else \
        lowestMinPaymt(bal, int, pay, ubound)
    '''
bal = 320000
int = 0.2
print(lowestMinPaymt(bal, int / 12, lbound = bal / 12, ubound = bal))

输出:

LOWEST PAYMENT CALLED

B: 1.3938913907531363
INT: 0.0167
PAY: 27129.783630371094
L: 27129.6438
H: 27129.9235


    Balance underpaid, increasing pay guess: L: 27129.6438 H: 27129.783630371094

LOWEST PAYMENT CALLED

B: 0.37124559969306575
INT: 0.0167
PAY: 27129.853566487633
L: 27129.7836
H: 27129.9235


    Balance underpaid, increasing pay guess: L: 27129.7836 H: 27129.853566487633

LOWEST PAYMENT CALLED

B: -0.14007729570936742
INT: 0.0167
PAY: 27129.8885345459
L: 27129.8536
H: 27129.9235


    Balance overpaid, decreasing pay guess: PAY: 27129.8885 L: 27129.8536 H: 27129.8885345459

LOWEST PAYMENT CALLED

B: 0.11558415200664361
INT: 0.0167
PAY: 27129.871050516766
L: 27129.8536
H: 27129.8885


    Balance underpaid, increasing pay guess: L: 27129.8536 H: 27129.871050516766

LOWEST PAYMENT CALLED

B: -0.012246571875402878
INT: 0.0167
PAY: 27129.879792531334
L: 27129.8711
H: 27129.8885

Pay within threshold, returning: 27129.879792531334
27129.88 <- SHOULD BE 29157.09, +/- 1 cent.

0 个答案:

没有答案