1 ## Copyright (C) 2012 Rik Wehbring
2 ## Copyright (C) 1995-2012 Kurt Hornik
4 ## This file is part of Octave.
6 ## Octave is free software; you can redistribute it and/or modify it
7 ## under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 3 of the License, or (at
9 ## your option) any later version.
11 ## Octave is distributed in the hope that it will be useful, but
12 ## WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ## General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with Octave; see the file COPYING. If not, see
18 ## <http://www.gnu.org/licenses/>.
21 ## @deftypefn {Function File} {} binopdf (@var{x}, @var{n}, @var{p})
22 ## For each element of @var{x}, compute the probability density function
23 ## (PDF) at @var{x} of the binomial distribution with parameters @var{n}
24 ## and @var{p}, where @var{n} is the number of trials and @var{p} is the
25 ## probability of success.
28 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
29 ## Description: PDF of the binomial distribution
31 function pdf = binopdf (x, n, p)
37 if (! isscalar (n) || ! isscalar (p))
38 [retval, x, n, p] = common_size (x, n, p);
40 error ("binopdf: X, N, and P must be of common size or scalars");
44 if (iscomplex (x) || iscomplex (n) || iscomplex (p))
45 error ("binopdf: X, N, and P must not be complex");
48 if (isa (x, "single") || isa (n, "single") || isa (p, "single"));
49 pdf = zeros (size (x), "single");
51 pdf = zeros (size (x));
54 k = (x == fix (x)) & (n == fix (n)) & (n >= 0) & (p >= 0) & (p <= 1);
58 k &= ((x >= 0) & (x <= n));
59 if (isscalar (n) && isscalar (p))
60 pdf(k) = exp (gammaln (n+1) - gammaln (x(k)+1) - gammaln (n-x(k)+1)
61 + x(k)*log (p) + (n-x(k))*log (1-p));
63 pdf(k) = exp (gammaln (n(k)+1) - gammaln (x(k)+1) - gammaln (n(k)-x(k)+1)
64 + x(k).*log (p(k)) + (n(k)-x(k)).*log (1-p(k)));
77 %! y = [0 1/4 1/2 1/4 0];
78 %!assert(binopdf (x, 2*ones(1,5), 0.5*ones(1,5)), y, tol);
79 %!assert(binopdf (x, 2, 0.5*ones(1,5)), y, tol);
80 %!assert(binopdf (x, 2*ones(1,5), 0.5), y, tol);
81 %!assert(binopdf (x, 2*[0 -1 NaN 1.1 1], 0.5), [0 NaN NaN NaN 0]);
82 %!assert(binopdf (x, 2, 0.5*[0 -1 NaN 3 1]), [0 NaN NaN NaN 0]);
83 %!assert(binopdf ([x, NaN], 2, 0.5), [y, NaN], tol);
85 %% Test class of input preserved
86 %!assert(binopdf (single([x, NaN]), 2, 0.5), single([y, NaN]));
87 %!assert(binopdf ([x, NaN], single(2), 0.5), single([y, NaN]));
88 %!assert(binopdf ([x, NaN], 2, single(0.5)), single([y, NaN]));
90 %% Test input validation
94 %!error binopdf (1,2,3,4)
95 %!error binopdf (ones(3),ones(2),ones(2))
96 %!error binopdf (ones(2),ones(3),ones(2))
97 %!error binopdf (ones(2),ones(2),ones(3))
98 %!error binopdf (i, 2, 2)
99 %!error binopdf (2, i, 2)
100 %!error binopdf (2, 2, i)