2016-09-16 11 views
0

所以我試圖實現在Python 分搜索算法返回一個「最佳」的儲蓄率。Python的平分搜索 - ABS()導致失敗

我試圖創造一些不同的功能,我不明白爲什麼程序跑在一個無限循環抓獲。我知道abs(current_savings - down_payment)是導致遞歸無限循環的原因,但我不知道爲什麼。第一

第一件事,這並不能真正解釋爲什麼我的程序不工作,但這裏有雲:

在每個月我賺取活期儲蓄利息,這是 應用第一年底,然後我收到我的月薪,這只是我年薪的 1/12。

我試圖找到適用於我的月薪的最佳費率,然後添加到我目前的儲蓄。

我的第一個功能簡單的檢查,看看如果一個人的工資高到足以永遠保存爲250K首付。如果他們的薪水不夠高,則會打印出不足並返回False。

我的第二個函數試圖找到最好的速率(「部分保存」),或以落入100美元down_payment內保存月薪的最佳速度。另外,我必須記錄我的平分搜索功能用來找到最優速度的「步驟」數量。

下面是代碼:

#Givens 
annual_salary = 150000 
initial_salary = annual_salary 
interest_rate = float(0.04/12.0) 
down_payment = float(250000.0) 
semi_annual_raise = 0.07 

#Bisect-search 
low = float(0.0) 
high = float(10000.0) 
portion_saved = float((low+high)/2) 
current_savings = 0 
months = 0 
steps = 0 

def isPossible(annual_salary): 
    count = 0 
    current_savings = 0 
    while count < 36: 
     current_savings += (current_savings*interest_rate) + (annual_salary/12) 
     count += 1 
     if count % 6 == 0: 
      annual_salary += (annual_salary*semi_annual_raise) 
    if current_savings < down_payment: 
     print("It is not possible to pay the down payment in three years.") 
     return False 
    else: 
     return True 


def bisearch(initial_salary,interest_rate,down_payment,semi_annual_raise,low,high,portion_saved,steps): 
    current_savings = 0 
    months = 0 
    while abs(current_savings - down_payment) > 100.0: 
     months = 0 
     current_savings = 0 
     while months < 36: 
      current_savings = current_savings + (initial_salary*interest_rate) 
      current_savings = current_savings + (initial_salary/12*portion_saved/10000.0) 
      months += 1 
      if months % 6 == 0: 
       initial_salary += (initial_salary*semi_annual_raise) 
     steps += 1 
     if current_savings > down_payment: 
      high = portion_saved 
     else: 
      low = portion_saved 
     portion_saved = ((low+high)/2.0) 
    print("Best saving rate: ", (portion_saved/10000.0)) 
    print("Steps in bisection search: ", steps) 




if isPossible(annual_salary) == True: 
    bisearch(initial_salary,interest_rate,down_payment,semi_annual_raise,low,high,portion_saved,steps) 

而且測試用例:

注:的的分搜索步數不必相同,但幅度應該是同樣

測試案例1

Enter the starting salary: 150000 

Best savings rate: 0.4411 

Steps in bisection search: 12 

測試案例2

Enter the starting salary: 300000 

Best savings rate: 0.2206 

Steps in bisection search: 9 

如果有人可以幫助我,我將不勝感激,一直在這幾個小時試圖拿出一個修補程序。

回答

0

我在同樣的問題,困惑,終於找到了解決辦法。嘗試重置initial_salary回annual_salary第一里面,而你的分切函數內環路,否則將只是繼續增加你每次投中6個月內循環。那樣有用嗎?