Python 为什么我需要使用另一个名为updatebalance的变量?

Python 为什么我需要使用另一个名为updatebalance的变量?,python,python-3.x,search,bisection,Python,Python 3.x,Search,Bisection,我正在创建一个程序,找到支付有利息的银行余额所需的最低付款额。考虑到初始的余额和年度利率,我需要使用二等分搜索来找到在年底前还清余额的最低月付款额。我已经查看了正确的代码和我的代码,我认为唯一的区别是它使用了一个名为updatedBalance的变量,我认为没有必要这样做。当我试图编写代码时,程序陷入了一个无限循环,其中高和低是相同的 这是根据余额、年利率和每月付款计算年末年度余额的代码。我相当肯定这没有bug,但这可能有助于理解代码的其余部分: def returnAnnual(balance

我正在创建一个程序,找到支付有利息的银行余额所需的最低付款额。考虑到初始的
余额
年度利率
,我需要使用二等分搜索来找到在年底前还清余额的最低月付款额。我已经查看了正确的代码和我的代码,我认为唯一的区别是它使用了一个名为
updatedBalance
的变量,我认为没有必要这样做。当我试图编写代码时,程序陷入了一个无限循环,其中高和低是相同的

这是根据余额、年利率和每月付款计算年末年度余额的代码。我相当肯定这没有bug,但这可能有助于理解代码的其余部分:

def returnAnnual(balance, annualInterestRate, monthlyPayment):
    def updateBalance(balance, annualInterestRate, monthlyPayment):

        monthlyInterestRate = annualInterestRate/12
        #print ("Monthly Interest Rate:", monthlyInterestRate)
        monthlyUnpaidBalance = balance - monthlyPayment
        #print ("Monthly unpaid balance:", monthlyUnpaidBalance)
        updatedBalance = monthlyUnpaidBalance + (monthlyInterestRate*monthlyUnpaidBalance)

        return updatedBalance

    months = 12
    result = balance
    while months >= 1:
        result = updateBalance(result, annualInterestRate, monthlyPayment)
        months -= 1
    return result
这是我用来完成对分搜索的代码。对于这个例子,我使用的是余额999999和年利率0.18。我应该得到的正确输出是90325.03

balance = 999999
annualInterestRate = 0.18


monthlyInterestRate = (annualInterestRate) / 12
epsilon = 0.01
numGuesses = 0
lowerBound = balance / 12
upperBound = (balance * (1 + monthlyInterestRate)**12) / 12
ans = (upperBound + lowerBound)/2.0

while abs(0 - balance) >= epsilon:

    numGuesses += 1
    n = returnAnnual(balance, annualInterestRate, ans)
    if  n >= 0:
        lowerBound = ans
    else:
        upperBound = ans
    ans = (upperBound + lowerBound)/2.0

print("Lowest Payment: " + str(round(ans, 2)))
正确的代码使用更新的平衡,就我所见,这是两段代码之间唯一重要的区别。它是这样写的:


balance = 999999
annualInterestRate = 0.18
monthlyInterestRate = annualInterestRate/12
epsilon = 0.01
low = balance/12
high = (balance*(1+monthlyInterestRate)**12)/12
ans = (high + low)/2.0
n = returnAnnual(balance, annualInterestRate, ans)
while abs(=-n) >= epsilon:
    print('low =', low, 'high =', high, 'ans=',ans, 'n=', n)
    if n < 0:
        low = ans
    else:
        high = ans
    ans = (high + low)/2.0

余额=999999
年利率=0.18
月利率=年利率/12
ε=0.01
低=平衡/12
高=(余额*(1+月利率)**12)/12
ans=(高+低)/2.0
n=年度回报(余额、年度利息、ans)
而abs(=-n)>=ε:
打印('low=',low,'high=',high,'ans=',ans,'n=',n)
如果n<0:
低=ans
其他:
高=ans
ans=(高+低)/2.0

最后一块代码毫无意义-
abs(=-n)
是一个语法错误,循环中没有调用
returnAnnual()
,因此没有实际的对分。你确定你粘贴了你想粘贴的内容吗?