我目前正在參加edx的MITx課程,並且我有一個練習題。你能告訴我爲什麼我用這段代碼陷入無限循環嗎?我猜對分搜索循環無法正常工作,但我不知道爲什麼。這裏的代碼:使用python中的二分法搜索計算最低每月付款
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))
你試過什麼? – Joost
'while abs(round(z,2))> 0:'你永遠不會改變z的值爲非積極的 –
好吧,所以這個練習的目的是找到最低的月度支付來支付整個信用卡餘額一年。要做到這一點,我們應該使用二分搜索。與最後一個循環。我每次都會改變猜測的想法,新的價值將進入我分配給變量z的函數......所以我正在改變z,不是嗎? –