C# How to calculate the IRR.

namespace IRRCalc
{
    internal class Program
    {
        static void Main(string[] args)
        {
            double[] cashFlows = { -1000, 200, 300, 600 };
            double irr = IRR(cashFlows);
            Console.WriteLine("The IRR is: " + irr.ToString("0.##%"));
        }

        static double IRR(double[] cashFlows)
        {
            double accuracy = 0.0001;
            double x1 = 0.0;
            double x2 = 1.0;

            while (Math.Abs(NPV(x2, cashFlows)) > accuracy)
            {
                double x3 = (x1 + x2) / 2;

                if (NPV(x3, cashFlows) * NPV(x1, cashFlows) < 0)
                    x2 = x3;
                else
                    x1 = x3;
            }

            return (x1 + x2) / 2;
        }

        static double NPV(double rate, double[] cashFlows)
        {
            double npv = 0;
            for (int i = 0; i < cashFlows.Length; i++)
            {
                npv += cashFlows[i] / Math.Pow(1 + rate, i);
            }
            return npv;
        }

    }
}

Simple program to calculate the IRR

About myprogrammingexp
I am glad to do a job where work feels like play.

Comments are closed.