2014-03-05 27 views
0

使用二分查找工作來解決信用卡付款問題的答案。我認爲我堅如磐石(儘管我確定是基本的)代碼,它適用於示例輸入,但檢查返回的是無限循環。我已經嘗試了大約20種不同的平衡輸入,並且所有的輸入都恢復正確,直到插入Balance = 2000,然後它拋出了無限循環。我無法弄清楚爲什麼。任何幫助,非常感謝這裏是我的代碼:獲取某些輸入的無限循環

balance = 2000 
annualInterestRate = .18 
monthlyInterestRate = annualInterestRate/12.0 
lower_bound = balance/12.0 
upper_bound = (balance * (1 + monthlyInterestRate) ** 12)/12.0 
monthly_payment = (lower_bound + upper_bound)/2.0 
new_balance = balance 

while new_balance != 0: 
    monthly_payment = (lower_bound + upper_bound)/2.0 
    new_balance = balance 
    month = 0 

    while month < 12 and new_balance != 0: 

     month += 1 
     new_balance = new_balance - monthly_payment 
     new_balance = new_balance + (new_balance * monthlyInterestRate) 
     new_balance = round(new_balance,2) 

    if new_balance < 0: 
     upper_bound = monthly_payment 

    else: 
     lower_bound = monthly_payment 


print "Lowest Payment:", round(monthly_payment,2) 

回答

0

舍入誤差:new_balance結束0.01。您可能想要檢查while條件中的lower_bound和upper_bound仍然不相等。

0

我注意到new_balance可能變成負數。如果是這種情況,那麼它將永遠不會脫離主循環。在調試測試

if new_balance < 0: 
    raise ValueError 

你可以在打印中除了或只是用來檢查。作爲選擇,而改爲

while new_balance > 0: 

此外,檢查new_balance不是< .01輪之前。事實上,我絕不會允許一輪比賽,但會一直下降。

同樣具有運行快速檢查後,我看到了一個打印出new_balance的

.01 
1846.64 
1690.98 

輪捐贈後的結果和循環再和周圍繼續向下.01。