2016-09-16 1 views
0

を引き起こしだから私は「最適」貯蓄率を返すPythonで二分検索アルゴリズムを実装しようとしています。Pythonのバイセクト検索 - ABS()失敗

私は、いくつかの異なる機能を作成しようとしました、そしてプログラムが無限ループに陥っますなぜ私は理解していません。私は、abs(current_savings - down_payment)が再帰的な無限ループを引き起こす原因であることを知っていますが、私はなぜそれがわかりません。

まず第一に、物事、これは本当に私のプログラムが動作しない理由を説明するが、ここにはありません:

各月の終わりに、私は が最初に適用され、現在の貯蓄、上の利息を得ます、毎月の給与を受け取ります。それは私の年俸のちょうど の1/12です。

月額給与に適用される最高の料金を見つけようとしていますが、現在の節約額に加算しています。

私の最初の関数は、単純に自分の給料が今まで250K頭金のために保存するのに十分な高さかどうかを確認します。彼らの給料が十分に高くない場合、それは適切ではないと表示し、Falseを返します。

私の第二の機能は最高の割合(「部分が保存された」)、またはdown_paymentの100ドルの範囲内にするために、毎月の給与の節約するための最良の料金を見つけよう。さらに、二分探索機能が最適な速度を見つけるために必要な「ステップ」の数を記録する必要があります。ここで

はコードです:

#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

誰かが私を大いに助けてくれたら、これで何時間も修正してくれたことに感謝します。

答えて

0

私は同じ問題で混乱し、最終的に解決策を見つけました。二分関数内の最初のwhileループ内でinitial_salaryをannual_salaryにリセットし直してください。それ以外の場合は、内側ループで6か月間ヒットするたびに増加し続けます。それは動作しますか?

関連する問題