pset2 Python问题3使用bisectionsearch.py

2024-06-02 19:08:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python完全陌生,在计算缩进时有很多问题,无论如何,我需要有人帮助我理解为什么我的代码不能工作…(if条件是不能从内部while循环中识别值)

balance = 1000
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate /12
episilon = 0.01
numGuesses = 0
Low = balance / 12
High = (balance * (1 + monthlyInterestRate )**12) / 12.0 
ans = (Low + High) / 2.0
newbalance = balance
monthlyPayment = ans

while newbalance > 0:
    newbalance = balance
    month = 0

    while month < 12:
        print('low = ' + str(Low) + ' high = ' + str(High) + ' ans = ' + str(ans))
        newbalance -= monthlyPayment
        interest = monthlyInterestRate * newbalance
        newbalance += interest
        month += 1
        print month 


    if(newbalance > 0):
        Low = ans               
    else:
        High = ans

    ans = (Low + High) / 2.0

print 'Lowest payment: ' + str(ans)

Tags: iflowprintbalancehighwhilestrmonth
1条回答
网友
1楼 · 发布于 2024-06-02 19:08:39

您应该扣除ans而不是monthlyPayment,在循环外设置monthlyPayment = ans并不意味着每次在while循环内设置ans = (Low + High) / 2.0monthlyPayment都会更新,每次您都在创建一个新对象:

while abs(newbalance) > 0.001: # check if we are withing +- .001 of clearing balance
    newbalance = balance
    month = 0
    for month in range(12): # loop over 12 month range
        print('low = ' + str(Low) + ' high = ' + str(High) + ' ans = ' + str(ans))
        newbalance -= ans # deduct ans not the the original value set outside the while
        interest = monthlyInterestRate * newbalance
        newbalance += interest
        print month    
    if newbalance > 0:
        Low = ans
    else:
        High = ans    
    ans = (Low + High) / 2.0    
print "Lowest Payment: {:.2f}".format(ans) # format to two decimal places

而且最好使用for month in range(12),我们知道我们只希望有12次迭代,所以使用范围要简单得多。你知道吗

即使您正在执行ans += 2,您的monthlyPayment也不会更新,因为int是不可变的,所以monthlyPayment仍然只会指向ans的原始值。你知道吗

In [1]: ans = 10    
In [2]: monthlyPayment = ans    
In [3]: id(ans) 
Out[3]: 9912448    
In [4]: id(monthlyPayment) # still the same objects
Out[4]: 9912448    
In [5]: ans += 10 # creates new object
In [6]: ans
Out[6]: 20    
In [7]: monthlyPayment # still has original value
Out[7]: 10  
In [8]: id(monthlyPayment)  # same id as original ans
Out[8]: 9912448     
In [9]: id(ans)  # new id because it is a new object
Out[9]: 9912208

相关问题 更多 >