这是一个我希望能改进编程方式的问题。我有这个循环,它根据年度支付计算未来金额,按利息增加并通过通货膨胀贬值(它来自Excel中的PV函数):
var pmt = 66,449.75 // annual payment
var ip = 0.03 // interest rate
var fv = 0 // future value, not require here
var k = 1 // interest is applied at beginning / end of period
var n = 25 // number of periods (years in this case)
var ri = 0.025 // rate of inflation
var pv = 0;
for (var i = n - 1; i >= 0; i -= 1) {
pv = (pv + (pmt * k - fv) * Math.pow(1 + ri, i)) / (1 + ip);
}
是否可以使用Math.pow()重现此循环正在做什么?
答案 0 :(得分:0)
为了简化,我重命名了一些表达式
a = pmt * k - fv;
b = 1 + ri;
c = 1 + ip;
x = pv;
所以你的代码变成了
for (var i = n - 1; i >= 0; --i) {
x = x / c + a * Math.pow(b, i) / c;
}
然后
x_0
x_1 = x_0 / c + a b^{n-1} / c
x_2 = x_1 / c + a b^{n-2} / c = x_0 / c^2 + a b^{n-1} / c^2 + a b^{n-2} / c
...
x_i = x_{i-1} / c + a b^{n-i} / c = x_0 / c^i + \sum_{k=1}^i a b^{n-k} / c^{i-k+1}
...
x_n = x_0 / c^n + \sum_{k=1}^n a * b^{n-k} / c^{n-k+1}
根据WolframAlpha,
x_n = x_0 / c^n + a (b^n-c^n) / (c^n (b-c))
因此,您可以使用
代替循环var foo = Math.pow(1 + ip, n); // c^n
pv = pv / foo + (pmt*k-fv) * (Math.pow(1+ri,n) - foo) / foo / (ri-ip);