2012-12-23 22 views
0

對於下面的公式,我嘗試在我的一個模型中重新創建一個名爲nper的方法。計算結果並不像預期的那樣(在Excel中使用NPER函數進行測試),我認爲這是因爲我如何編寫我的方法。在Rails中重新創建NPER

enter image description here

def nper(rate, pmt, pv, fv = 0, type = 0) 
    a = pmt * (1 + rate * type) + (-1/rate) * fv 
    b = pv * rate + pmt * (1 + rate * type) 
    c = Math.sqrt(a/b) 
    d = Math.sqrt(1 + rate) 
    e = (c/d) * 100 
end 

我試圖先計算括號,然後使用平方根函數的Math模塊中,以幫助計算的其餘部分。我正在計算抵押貸款的期限。我哪裏錯了?

要進行測試,以下內容:

nper(((3.5/100)/12), -561.31, 125000)

應該產生:~360(30年期固定貸款)

率除以100,然後12,因爲rate是利率每期

+0

不,它不應該。這在數學上是不可能的。沒有輸入,結果是負數。 – meagar

+0

我已經在Excel中對它進行了測試,結果如上所示。讓我們嘗試另一個數字然後(更新)。 – Steve

回答

2

使用Math.log10(),下面的公式就像一個魅力。我修改了一下,所以我可以使用pmt的負面版本,並使用type和fv(未來值)。

def nper(rate, pmt, pv, fv = 0, type = 0) 
    Math.log10((pmt*(1+rate*type)+(-1/rate)*fv)/(pv*rate+pmt*(1+rate*type)))/Math.log10(1 + rate) 
end 

參考:MrExcel.com Forum Thread