2016-11-26 20 views
0

私はこのMIT OCW assignmentの3番目の問題を解決しようとしています。これは、二分探索法を使用して1年間に特定の債務をクリアするために必要な毎月の支払い額を計算することを必要とします。私は予想される出力タイプを取得していますが、結果は非常に不正確です。誰かが間違っているところを指摘できますか?ありがとうございますPythonバイセクション検索ロジックエラー - 不正確な結果を返す

# Problem Set 1("C") 
# Time Spent: xx hours 

def payInOne_BisectionSearch (balance,annualRate): 
    #initialize variables 
    initialBalance = balance 
    monthlyRate = float(annualRate/12.0) 
    minMonthly = float(balance/12.0) 
    maxMonthly = float((balance * (1 + monthlyRate ** 12.0))/12.0) 
    monthlyPayment = float((minMonthly + maxMonthly)/2) 
    numMonths = 1 
    #define function to check balance after 12 months  
    def balanceAfterYear (balance, monthlyRate, monthlyPayment): 
     for numMonths in range (1,13): 
      interest = balance * monthlyRate 
      balance += interest - monthlyPayment 
      if balance <= 0: 
        break 
     return [balance, numMonths] 

    while maxMonthly - minMonthly >= .005: 
     balance = initialBalance 
     monthlyPayment = float((minMonthly + maxMonthly)/2) 
     if balanceAfterYear(balance,monthlyRate,monthlyPayment)[0] < 0:#paying too much 
      maxMonthly = monthlyPayment 
     elif balanceAfterYear(balance,monthlyRate,monthlyPayment)[0] > 0:#paying too little 
      minMonthly = monthlyPayment 
     else: 
      break 
    print "Monthly payment to pay off debt in 1 year:", round(monthlyPayment,2) 
    print "Number of months needed:", round(balanceAfterYear(balance,monthlyRate,monthlyPayment)[1], 2) 
    print "Balance:", round(balanceAfterYear(balance,monthlyRate,monthlyPayment)[0], 2) 

payInOne_BisectionSearch (float(raw_input("Enter the outstanding balance")),float(raw_input("Enter annual rate as a decimal"))) 


    '''Test Case Expected: 
     Enter the outstanding balance on your credit card: 320000 
     Enter the annual credit card interest rate as a decimal: .2 
     RESULT 
     Monthly payment to pay off debt in 1 year: 29643.05 
     Number of months needed: 12 
     Balance: -0.1 

     Test Case Actual Output: 
     Enter the outstanding balance320000 
     Enter annual rate as a decimal.2 
     Monthly payment to pay off debt in 1 year: 26666.67 
     Number of months needed: 12.0 
     Balance: 39179.43''' 
+0

また、Python 2では、 '/'は必ずしも真の除算ではありません。浮動計算をしている場合は、 'balance/12'のようなものが' balance/12.0'になるはずです –

+0

サンプルのテストケースを追加し、スペースの問題を修正しました。申し訳ありませんが、私のコードを貼り付ける際にスペースを失ってしまいました。ありがとうございました –

+0

すべての '12'インスタンスを' 12.0'に変更しても、出力に大きな影響はありませんでした。 –

答えて

1

問題はあなたの最初のmaxMonthly値にあります。私はそれが

maxMonthly = float((balance * ((1 + monthlyRate) ** 12.0))/12.0) 

として定義するために何が実際に希望することはそうでない場合monthlyRate**12がちょうどmaxMonthly balance/12.0に評価するだろう(0と1の間monthlyRateのための)ゼロに近い数、と評価されますだと思いますあなたのminMonthlyと同じです。これは、最後のwhileループが始まらないようにします。

+0

これは問題です。誰もが読むことのための素晴らしい説明。非常に明白なのは、これを読んで確認するためにテストしたときの問題だった。ありがとうございました!! –

関連する問題