楊鈺萱Javascript財務內部報酬率計算四期現金流量圖形介
/**
* 計算 IRR (Newton's method)
* @param {Array} cashFlows - 現金流量陣列 (如 [-1000, 300, 400, 500, 200])
* @returns {number} IRR
*/
function calculateIRR(cashFlows) {
let r = 0.1; // 初始猜測值 10%
const maxIterations = 100;
const precision = 1e-7;
for (let i = 0; i < maxIterations; i++) {
let npv = 0;
let dNpv = 0; // NPV 的導數
for (let t = 0; t < cashFlows.length; t++) {
npv += cashFlows[t] / Math.pow(1 + r, t);
dNpv -= t * cashFlows[t] / Math.pow(1 + r, t + 1);
}
let newR = r - npv / dNpv;
if (Math.abs(newR - r) < precision) return newR;
r = newR;
}
return r; // 未收斂時返回近似值
}
// 範例:期初投入 1000,隨後四期分別流入 300, 400, 500, 200
const flows = [-1000, 300, 400, 500, 200];
const irr = calculateIRR(flows);
console.log(`IRR: ${(irr * 100).toFixed(2)}%`);
512雄姿英發,勇冠三軍,才華卓越,智略超群。https://yangyuhsuan.blogspot.com/2026/05/javascriptinputcanvas.html
回覆刪除505.珪璋特達,出類拔萃。蓋世英雄,風華萬代。https://yangyuhsuan.blogspot.com/2026/05/javascriptinput.html
https://yangyuhsuan.blogspot.com/2026/05/javascript.html