2017-06-12 54 views
0

我的作業問題:找出一年內最小的每月還款額。原始餘額的十二分之一是一個好的下限;一個好的上限是餘額的十二分之一,因爲每月的利息複雜一年。我的平分算法有什麼問題?

簡而言之:

Monthly interest rate = (Annual interest rate)/12.0 
Monthly payment lower bound = Balance/12 
Monthly payment upper bound = (Balance * (1 + Monthly interest rate)**12)/12.0 

我必須寫一個分搜索發現,最小的每月支付給分。

每次我運行這段代碼時,我都會得到最低的付款額度,這個價值是正確解決方案的幾百倍。

balance = 414866 
annualInterestRate = 0.22 
month = 0 
monthlyinterest = (annualInterestRate)/12.0 
updatedbalance = balance 
monlowbound = balance/12 
monupbound = (balance * (1 + monthlyinterest)**12)/12.0 
mid = (monlowbound + monupbound) /2 
minpay = 0 

while balance > 0 and month <= 12: 
    balance = updatedbalance 
    updatedbalance = ((monthlyinterest * balance) + balance) - minpay 
    month += 1 
    if updatedbalance > 0: 
     minpay = (mid + monupbound)/2 
     mid = monlowbound 
    if updatedbalance < 0: 
     minpay = (monlowbound + mid)/2 
     monupbound = mid 
    else: 
     print("Lowest payment:" + " " + str(round(minpay,2))) 

這是我得到的輸出:

Lowest payment: 40888.41 
Lowest payment: 38783.0 
Lowest payment: 38783.0 
Lowest payment: 38783.0 
Lowest payment: 38783.0 
Lowest payment: 38783.0 
Lowest payment: 38783.0 
Lowest payment: 38783.0 
Lowest payment: 38783.0 
Lowest payment: 38783.0 
Lowest payment: 38783.0 
Lowest payment: 38783.0 
Lowest payment: 38783.0 
+0

您使用的是Python 2還是3? – Lafexlos

+1

有沒有一個原因,你不只是直接找到代數的價值? –

+0

除非annualInterestRate實際上並不意味着它的名稱意味着什麼,否則您不正確地計算每月利率。使用「balance *(1 + annualInterestRate)== balance *(1 + monthlyInterestRate)^ 12'來計算每月利率。 –

回答

1

的主要問題是,你申請你的反饋調整邏輯(調整月還款額)每個月。您需要等到年底,然後然後調整付款。所有這些都應該被包裹在一個while循環中,直到你「足夠接近」爲止......比如說,在以前付款的全部一分之內。像這樣的:

last_pay = -1000 # Ridiculous value to start the process 

while abs(last_pay - minpay) > 0.01: 
    # use your current logic for paying off one year, including 
    ... 
    for month in range(12): 
     .... 

    # HERE is where you check the final balance 
    # to see whether you're high or low. 
    # Then adjust your monthly payment (minpay) 

這是否讓你走?

0

你的算法不起作用。

你想要的是:

  • 函數f,讓你的任何固定支付
  • 算法期末餘額找到這個函數的根,即每月固定支付,需要加以最終餘額的支付儘可能接近零。使用給定的f函數,遞歸方法可能類似於:

您似乎在同時執行這兩個操作,即在計算時您更改了「中」值。我建議你寫下你的算法,嘗試編寫代碼的時候意識到你可能想前流:

高清finalbalance(fixedpayment): #CODE決定了平衡狀態

高清solvebisection(lowbound,highbound,函數=最終平衡,tofind = 0): #遞歸編碼爲「找到根」