Calculate lowest monthly payment using bisection search in python

我怕爱的太早我们不能终老 提交于 2019-12-02 15:55:57

问题


I'm currently taking the MITx course on edx and I have a problem with one exercise. Can you please tell me why I get stuck in an infinite loop with this code? I guess the bisectional search loop isn't working properly but I don't really know why. Here's the code:

balance = 5000
annualInterestRate = 0.18
low = balance/12
high = (balance * (1 + annualInterestRate / 12) ** 12) / 12
guess = (low + high)/2

def getBal(guess, balance, annualInterestRate):
    mon = 0
    while mon < 12:
        mon += 1
        ub = balance - guess
        balance = ub + (annualInterestRate/12) * ub
    return balance

z = getBal(guess, balance, annualInterestRate)

while abs(round(z, 2)) > 0:
    if round(z, 2) > 0:
        low = guess
    else:
        high= guess
    guess = (high+low)/2

print "Lowest Payment: " + str(round(guess,2)) 

回答1:


The problem is with the second loop. You could try to do it this way:

balance = 5000
annual_interest_rate = 0.18
low = balance/12
high = (balance * (1 + annual_interest_rate / 12) ** 12) / 12
guess = (low + high)/2


def get_bal(g, b, air):
    mon = 0
    while mon < 12:
        mon += 1
        ub = b - g
        b = ub + (air/12) * ub
    return b

while True:
    z = get_bal(guess, balance, annual_interest_rate)
    if abs(round(z, 2)) == 0:
        break
    if round(z, 2) > 0:
        low = guess
    else:
        high = guess
    guess = (high+low)/2

print "Lowest Payment: " + str(round(guess, 2))


来源:https://stackoverflow.com/questions/35068514/calculate-lowest-monthly-payment-using-bisection-search-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!