Inspired by http://stackoverflow.com/questions/530192/implementing-excel-and-vbs-irr-function
var IRRCalc = function (CArray) {
var i,
f=999, // initial value for f before any calculations are done is well outside our accept_margin_of_error
fprime,
r=2, // this is an initial guess, we will revise it with each iteration
acceptable_margin_of_error = 0.005;
while(Math.abs(f) > acceptable_margin_of_error) {
//console.log(‘r: ‘+r);
// we are using Newton’s method http://en.wikipedia.org/wiki/Newton’s_method
// function f = the sum of Ci / (1+r)^i for i=0 to n where n is the index of the last element in the array
f = 0;
fprime = 0;
for (i=0; i<CArray.length; i++) {
f += CArray[i]/Math.pow(1+r, i);
fprime += -i*CArray[i]/Math.pow(1+r, i+1);
}
//console.log(‘f: ‘+f);
//console.log(‘fprime: ‘+fprime);
//console.log(‘revised r: ‘+r);
//console.log(‘———————‘);
r = r – f/fprime; // use the result of the equation f and the first derivative of f for the current r to iterate to the next r value
}
return r;
}