The Internal Rate of Return (IRR) is a crucial metric used in capital budgeting and investment appraisal. It represents the discount rate at which the net present value (NPV) of all cash flows from a particular project or investment equals zero. In simpler terms, it's the expected rate of return that an investment will generate.
function calculateIRR() {
var cashFlowsInput = document.getElementById("cashFlows").value;
var resultDiv = document.getElementById("result");
if (!cashFlowsInput) {
resultDiv.innerHTML = "Please enter cash flows.";
return;
}
var cashFlowsArray = cashFlowsInput.split(',').map(function(item) {
return parseFloat(item.trim());
});
for (var i = 0; i < cashFlowsArray.length; i++) {
if (isNaN(cashFlowsArray[i])) {
resultDiv.innerHTML = "Please ensure all cash flows are valid numbers.";
return;
}
}
// Basic check for at least one negative and one positive cash flow for IRR to be meaningful
var hasNegative = cashFlowsArray.some(function(cf) { return cf 0; });
if (!hasNegative || !hasPositive) {
resultDiv.innerHTML = "IRR calculation requires at least one initial outflow (negative) and at least one subsequent inflow (positive).";
return;
}
// IRR Calculation (using a numerical method, e.g., Newton-Raphson or Bisection)
// This is a simplified approximation. For precise financial calculations,
// specialized libraries or Excel's built-in function are recommended.
// This implementation uses a simple iterative search.
var guess = 0.1; // Initial guess for IRR
var tolerance = 0.0001;
var maxIterations = 1000;
var irr = NaN;
for (var iter = 0; iter < maxIterations; iter++) {
var npv = 0;
for (var t = 0; t < cashFlowsArray.length; t++) {
npv += cashFlowsArray[t] / Math.pow(1 + guess, t);
}
if (Math.abs(npv) < tolerance) {
irr = guess;
break;
}
// Calculate derivative for Newton-Raphson (optional, but improves convergence)
// For simplicity, we'll just adjust guess based on NPV sign
var derivative = 0;
for (var t = 1; t < cashFlowsArray.length; t++) {
derivative -= t * cashFlowsArray[t] / Math.pow(1 + guess, t + 1);
}
if (Math.abs(derivative) < tolerance) { // Avoid division by zero
guess += tolerance; // Perturb guess slightly
} else {
guess = guess – npv / derivative;
}
// Ensure guess stays positive
if (guess <= -1) {
guess = -0.999; // Prevent infinite loops or invalid rates
}
}
if (!isNaN(irr)) {
resultDiv.innerHTML = "