|
/*===========================================================================
* Title : Internal Rate of Return (IRR) calculation
*
* Author : Vivek Shankar Skandappan (vivekshankars@gmail.com)
*
* Reference : Wikipedia for the IRR formula
*
* Version : 1.0
*
=============================================================================*/
/* Complile as cc -lm irr.c */
#include <stdio.h>
#include <math.h>
/* Max rate variation considered is from 1% to 50% */
#define LOW_RATE 0.01
#define HIGH_RATE 0.5
#define MAX_ITERATION 1000
#define PRECISION_REQ 0.00000001
double computeIRR(double cf[], int numOfFlows)
{
int i = 0,j = 0;
double m = 0.0;
double old = 0.00;
double new = 0.00;
double oldguessRate = LOW_RATE;
double newguessRate = LOW_RATE;
double guessRate = LOW_RATE;
double lowGuessRate = LOW_RATE;
double highGuessRate = HIGH_RATE;
double npv = 0.0;
double denom = 0.0;
for(i=0; i<MAX_ITERATION; i++)
{
npv = 0.00;
for(j=0; j<numOfFlows; j++)
{
denom = pow((1 + guessRate),j);
npv = npv + (cf[j]/denom);
}
//printf("\n NPV for guessRate: %f : %f",guessRate, npv);
/* Stop checking once the required precision is achieved */
if((npv > 0) && (npv < PRECISION_REQ))
break;
if(old == 0)
old = npv;
else
old = new;
new = npv;
if(i > 0)
{
if(old < new)
{
if(old < 0 && new < 0)
highGuessRate = newguessRate;
else
lowGuessRate = newguessRate;
}
else
{
if(old > 0 && new > 0)
lowGuessRate = newguessRate;
else
highGuessRate = newguessRate;
}
}
oldguessRate = guessRate;
guessRate = (lowGuessRate + highGuessRate) / 2;
newguessRate = guessRate;
//printf("\n Rate: Old %f New %f ... NPV: Old %f New %f ... Low %f High %f", oldguessRate, newguessRate, old, new, lowGuessRate, highGuessRate);
}
printf("\n FINAL NPV after %d iterations = %.8f", i, guessRate);
printf("\n FINAL NPV = %.6f", (guessRate*1200));
return guessRate;
}
int main()
{
//Cash flows
double cf[30], irr = 0.00;
int numOfFlows = 7;
cf[0] = -70000;
cf[1] = 12000;
cf[2] = 15000;
cf[3] = 18000;
cf[4] = 21000;
cf[5] = 26000;
numOfFlows = 6;
irr = computeIRR(cf, numOfFlows);
printf("\nFinal IRR: %.8f", irr);
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.