【发布时间】:2012-12-25 13:49:00
【问题描述】:
为了模拟 Excel 的 rate 函数,我使用了从 svn 中获取的 Apache POI rate 函数:
private double calculateRate(double nper, double pmt, double pv, double fv, double type, double guess) {
//FROM MS http://office.microsoft.com/en-us/excel-help/rate-HP005209232.aspx
int FINANCIAL_MAX_ITERATIONS = 20; //Bet accuracy with 128
double FINANCIAL_PRECISION = 0.0000001; //1.0e-8
double y, y0, y1, x0, x1 = 0, f = 0, i = 0;
double rate = guess;
if (Math.abs(rate) < FINANCIAL_PRECISION) {
y = pv * (1 + nper * rate) + pmt * (1 + rate * type) * nper + fv;
}
else {
f = Math.exp(nper * Math.log(1 + rate));
y = pv * f + pmt * (1 / rate + type) * (f - 1) + fv;
}
y0 = pv + pmt * nper + fv;
y1 = pv * f + pmt * (1 / rate + type) * (f - 1) + fv;
// Find root by the Newton secant method
i = x0 = 0.0;
x1 = rate;
while ((Math.abs(y0 - y1) > FINANCIAL_PRECISION) && (i < FINANCIAL_MAX_ITERATIONS)) {
rate = (y1 * x0 - y0 * x1) / (y1 - y0);
x0 = x1;
x1 = rate;
if (Math.abs(rate) < FINANCIAL_PRECISION) {
y = pv * (1 + nper * rate) + pmt * (1 + rate * type) * nper + fv;
}
else {
f = Math.exp(nper * Math.log(1 + rate));
y = pv * f + pmt * (1 / rate + type) * (f - 1) + fv;
}
y0 = y1;
y1 = y;
++i;
}
return rate;
}
对于calculateRate(120, 28.1, -2400, 0, 0, 0.1)),输出与Excel相同:0.599
但如果我尝试相同的计算,这次使用值:
calculateRate(360, 15.9, -2400, 0, 0, 0.1))
在 Excel 中我得到 0.580,程序返回 -1.1500428517726355。有什么提示吗?
【问题讨论】:
-
在 Apache POI 项目中打开一个错误报告,或者搜索他们的错误数据库,看看它是否是一个已知问题。
-
看起来 OP 采纳了错误报告建议 - Bug #54349 刚刚在项目中提出
标签: java apache-poi