李珮喬Javascript財務內部報酬率計算四期現金流量圖形介
大部分的程式語言,指令之間用;分隔,可是為了閱讀程式碼, 會分行而且縮排,python乾脆將「分行」有;的功能,相同的縮排代表同一個{區塊}。順便加上P段落。
function calculateIRR(cashFlows, guess = 0.1) {
const maxIteration = 100; // 最大疊代次數
const precision = 1e-7; // 精度
let irr = guess;
for (let i = 0; i < maxIteration; i++) {
let npv = 0;
let dNpv = 0; // NPV 的導數
for (let t = 0; t < cashFlows.length; t++) {
npv += cashFlows[t] / Math.pow(1 + irr, t);
dNpv -= t * cashFlows[t] / Math.pow(1 + irr, t + 1);
}
let newIrr = irr - npv / dNpv;
if (Math.abs(newIrr - irr) < precision) {
return newIrr;
}
irr = newIrr;
}
return null; // 無法收斂
}
// --- 4期現金流量範例 ---
// 第0期:初始投資 -1000
// 第1-4期:現金流入 300, 400, 500, 600
const cashFlows = [-1000, 300, 400, 500, 600];
const irrResult = calculateIRR(cashFlows);
if (irrResult !== null) {
console.log(`IRR 結果: ${(irrResult * 100).toFixed(2)}%`);
} else {
console.log("IRR 計算未收斂");
}
512很優!如果你對期中考分數不滿意,我會在期末給你再加分。https://penny0610.blogspot.com/2026/05/javascriptinput.html
回覆刪除https://penny0610.blogspot.com/2026/05/javascript.html