How can I implement MS Excel's "IRR()" formula in PHP?
I tried the algorithm mentioned in this page but the results were not accurate and it was really slow.
How can I implement MS Excel's "IRR()" formula in PHP?
I tried the algorithm mentioned in this page but the results were not accurate and it was really slow.
This is modified from Tomas's answer. It stops the infinite loop by a check at the start to make sure cashflow is greater than investment. I have also increased the precision and run it a maximum of 20 times.
private function IRR($investment, $flow, $precision = 0.000001) {
if (array_sum($flow) < $investment):
return 0;
endif;
$maxIterations = 20;
$i =0;
if (is_array($flow)):
$min = 0;
$max = 1;
$net_present_value = 1;
while ((abs($net_present_value - $investment) > $precision)&& ($i < $maxIterations)) {
$net_present_value = 0;
$guess = ($min + $max) / 2;
foreach ($flow as $period => $cashflow) {
$net_present_value += $cashflow / (1 + $guess) ** ($period + 1);
}
if ($net_present_value - $investment > 0) {
$min = $guess;
} else {
$max = $guess;
}
$i++;
}
return $guess * 100;
else:
return 0;
endif;
}