]> Creatis software - CreaPhase.git/blob - octave_packages/financial-0.4.0/npv.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / financial-0.4.0 / npv.m
1 ## Copyright (C) 1995-2000, 2002, 2004-2007 Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
2 ##
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
6 ## version.
7 ##
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 ## details.
12 ##
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn {Function File} {} npv (@var{r}, @var{p}, @var{i})
18 ## Net present value of a series of payments.
19 ##
20 ## Returns the net present value of a series of irregular (i.e., not
21 ## necessarily identical) payments @var{p} which occur at the ends of @var{n}
22 ## consecutive periods.  @var{r} specifies the one-period interest rates and
23 ## can either be a scalar (constant rates) or a vector of the same
24 ## length as @var{p}.
25 ##
26 ## The optional argument @var{i} may be used to specify an initial
27 ## investment.
28 ##
29 ## Note that the rate @var{r} is specified as a fraction (i.e., 0.05,
30 ## not 5 percent).
31 ## @seealso{irr, pv}
32 ## @end deftypefn
33
34 function v = npv (r, p, i)
35
36   if (nargin < 2 || nargin > 3)
37     print_usage ();
38   endif
39
40   if (! (isvector (p)))
41     error ("npv: p has to be a vector");
42   else
43     n = length (p);
44     p = reshape (p, 1, n);
45   endif
46
47   if (any (any (r <= -1)))
48     error ("npv: all interest rates must be > -1");
49   endif
50   if (isscalar (r))
51     d = 1 ./ (1 + r) .^ (0 : n);
52   elseif (isvector (r) && (length (r) == n))
53     d = [1, (1 ./ cumprod (reshape (1 + r, 1, n)))];
54   else
55     error ("npv: r must be a scalar or a vector of the same length as p");
56   endif
57
58   if (nargin == 3)
59     if (! isscalar (i))
60       error ("npv: I_0 must be a scalar");
61     endif
62   else
63     i = 0;
64   endif
65
66   p = [i, p];
67   v = sum (d .* p);
68
69 endfunction