c#版NPV函数
static void Main(string[] args)
{
double[] flow = new double[] { 565.43, 565.43, 565.43, 565.43, 565.43, 565.43, 565.43, 565.43, 565.43, 565.43, 565.43, 565.43, 635.47, 635.47, 635.47, 635.47, 635.47, 635.47, 635.47, 635.47, 635.47, 635.47, 635.47, 635.47, 707.61, 707.61, 707.61, 707.61, 707.61, 707.61, 707.61, 707.61, 707.61, 707.61, 707.61, 707.61, 781.92, 781.92, 781.92, 781.92, 781.92, 781.92, 781.92, 781.92, 781.92, 781.92, 781.92, 781.92, 858.45, 858.45, 858.45, 858.45, 858.45, 858.45, 858.45, 858.45, 858.45, 858.45, 858.45, 858.45 };
//方法1
var vb_npv = Microsoft.VisualBasic.Financial.NPV(0.02, ref flow);
Console.WriteLine(vb_npv);
//方法2
Console.WriteLine(GetNPV(0.02,flow));
Console.ReadKey();
}
public static double GetNPV(double dcRate, double[] values)
{
double counter = 0;
return values.Sum(value => value / Math.Pow(1 + dcRate, ++counter));
}
SqlServer版NPV函数:
DECLARE @rate DECIMAL(30, 10) ,
@strIDs VARCHAR(8000);
SET @strIDs = '565.43, 565.43, 565.43, 565.43, 565.43, 565.43, 565.43, 565.43, 565.43, 565.43, 565.43, 565.43, 635.47, 635.47, 635.47, 635.47, 635.47, 635.47, 635.47,635.47, 635.47, 635.47, 635.47, 635.47, 707.61, 707.61, 707.61, 707.61, 707.61, 707.61, 707.61, 707.61, 707.61, 707.61, 707.61, 707.61, 781.92, 781.92,781.92, 781.92, 781.92, 781.92, 781.92, 781.92, 781.92, 781.92, 781.92, 781.92, 858.45, 858.45, 858.45, 858.45, 858.45, 858.45, 858.45, 858.45, 858.45,858.45, 858.45, 858.45';
SET @rate = 0.0200000000;
DECLARE @t_IDs TABLE
(
id INT IDENTITY(1, 1) ,
value DECIMAL(30, 10)
);
DECLARE @strID VARCHAR(12) ,
@sepPos INT;
SET @strIDs = COALESCE(@strIDs + ',', '');
SET @sepPos = CHARINDEX(',', @strIDs);
WHILE @sepPos > 0
BEGIN
SET @strID = LEFT(@strIDs, @sepPos - 1);
INSERT INTO @t_IDs
( value
)
SELECT ( CAST(@strID AS DECIMAL(30, 10)) )
WHERE ISNUMERIC(@strID) = 1;
SET @strIDs = RIGHT(@strIDs, DATALENGTH(@strIDs) - @sepPos);
SET @sepPos = CHARINDEX(',', @strIDs);
END;
SELECT SUM(value / POWER(1 + @rate, id))
FROM @t_IDs;