2016-01-28 66 views
0

我目前正在參加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)) 
+0

你試過什麼? – Joost

+0

'while abs(round(z,2))> 0:'你永遠不會改變z的值爲非積極的 –

+0

好吧,所以這個練習的目的是找到最低的月度支付來支付整個信用卡餘額一年。要做到這一點,我們應該使用二分搜索。與最後一個循環。我每次都會改變猜測的想法,新的價值將進入我分配給變量z的函數......所以我正在改變z,不是嗎? –

回答

0

問題是與第二個循環。 你可以嘗試這樣做:

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)) 
+0

因爲我試圖用新的「猜測」分配來改變z。通過檢查從函數getBal獲得的餘額是否等於0 –

+0

來獲得正確的猜測值,在這種情況下,您需要在while循環的每個循環中重新計算z,否則它是無限循環,但它不會幫助,因爲abs是永遠是積極的 – tinySandy

+0

如果你擺脫了while循環,沒有一分爲二發生 –