Javascript Excel';JS中的s RATE函数在值过高后发生故障
Bellow脚本工作准确,直到paymentAmount/futureValue的组合过高,然后它计算出的结果完全错误Javascript Excel';JS中的s RATE函数在值过高后发生故障,javascript,excel,algorithm,math,Javascript,Excel,Algorithm,Math,Bellow脚本工作准确,直到paymentAmount/futureValue的组合过高,然后它计算出的结果完全错误 export function rate(paymentsPerYear, paymentAmount, presentValue, futureValue, dueEndOrBeginning, interest) { //If interest, futureValue, dueEndorBeginning was not set, set now if (inte
export function rate(paymentsPerYear, paymentAmount, presentValue, futureValue, dueEndOrBeginning, interest)
{
//If interest, futureValue, dueEndorBeginning was not set, set now
if (interest == null)
interest = 0.01;
if (futureValue == null)
futureValue = 0;
if (dueEndOrBeginning == null)
dueEndOrBeginning = 0;
var FINANCIAL_MAX_ITERATIONS = 1280;//Bet accuracy with 128
var FINANCIAL_PRECISION = 0.0000001;//1.0e-8
var y, y0, y1, x0, x1 = 0, f = 0, i = 0;
var rate = interest;
if (Math.abs(rate) < FINANCIAL_PRECISION)
{
y = presentValue * (1 + paymentsPerYear * rate) + paymentAmount * (1 + rate * dueEndOrBeginning) * paymentsPerYear + futureValue;
}
else
{
f = Math.exp(paymentsPerYear * Math.log(1 + rate));
y = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;
}
y0 = presentValue + paymentAmount * paymentsPerYear + futureValue;
y1 = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;
// find root by 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 = presentValue * (1 + paymentsPerYear * rate) + paymentAmount * (1 + rate * dueEndOrBeginning) * paymentsPerYear + futureValue;
}
else
{
f = Math.exp(paymentsPerYear * Math.log(1 + rate));
y = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;
}
y0 = y1;
y1 = y;
++i;
}
return rate;
}
导出函数利率(付款期、付款金额、现值、未来值、到期日、利息)
{
//如果利息、未来价值、开始未设置,则立即设置
如果(利息==null)
利息=0.01;
如果(futureValue==null)
未来价值=0;
如果(开始==null)
初始值=0;
var FINANCIAL_MAX_ITERATIONS=1280;//押注精度为128
var FINANCIAL_PRECISION=0.0000001;//1.0e-8
变量y,y0,y1,x0,x1=0,f=0,i=0;
var利率=利息;
if(算术平均值(比率)<财务精度)
{
y=当前价值*(1+付款金额*比率)+付款金额*(1+比率*到期日)*付款金额*未来价值;
}
其他的
{
f=Math.exp(paymentsPerYear*Math.log(1+费率));
y=当前价值*f+付款金额*(1/费率+到期日)*(f-1)+未来价值;
}
y0=当前价值+付款金额*付款金额当前价值+未来价值;
y1=当前价值*f+付款金额*(1/费率+应付期初)*(f-1)+未来价值;
//牛顿割线法求根
i=x0=0.0;
x1=速率;
而((数学abs(y0-y1)>金融精度)
&&(i
输入稍有不同的工作和非工作示例可在此处找到:
有什么想法吗
编辑:正如一条评论中所建议的,我在jsbin上的示例中添加了正确的结果(0.005420910)。什么是“完全错误”呢?你期望得到什么样的结果?你得到了什么?像这样的信息应该是问题的一部分。谢谢你的建议。非工作示例的正确计算是:
0.005420910
(使用EXCEL中相同的输入计算)而不是0.0016340684111754143
。这花了我一段时间,所以如果有人遇到相同的问题,这个库实现了正确的版本:只需复制lib/tvm.js
和lib/common.js
(可能需要编辑一两个导入路径)然后通过tvm.RATE(args)