在Objective-C中以编程方式计算IRR(内部费率回报)和NPV

Rah*_*tel 7 c iphone excel objective-c ios

我正在开发一个理财软件,需要IRR (in-built functionality of Excel)的计算,发现在这样伟大的教程C 在这里和在这样的答案C# 在这里.

我实现了上面C语言的代码,但是当IRR为正时,它给出了完美的结果.它应该是没有返回负值.而Excel =IRR(values,guessrate)中的某些值也会返回负IRR.

我也参考了上面C#链接中的代码,似乎它遵循良好的程序并返回错误,并且也希望它也返回负IRR,与Excel相同.但我不熟悉C#,所以我无法在Objective-C或C中实现相同的代码.

我正在编写上面链接中的C代码,我已经实现了这些代码来帮助你们.

#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);
        }

        /* 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;
    }
    return guessRate;
}
Run Code Online (Sandbox Code Playgroud)

我已经附加了一些值的结果,这些值在Excel和上面的C语言代码中是不同的.

 Values:             Output of Excel: -33.5%
 1 = -18.5,          Output of C code: 0.010 or say (1.0%)
 2 =  -18.5,
 3 = -18.5,
 4 = -18.5,
 5 = -18.5,
 6 =  32.0

Guess rate: 0.1
Run Code Online (Sandbox Code Playgroud)

Qiu*_*Qiu 5

由于 low_rate 和 high_rate 都是正数,因此您无法获得负分。你必须改变:

#define LOW_RATE 0.01
Run Code Online (Sandbox Code Playgroud)

例如,

#define LOW_RATE -0.5
Run Code Online (Sandbox Code Playgroud)