home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / octa21eb.zip / octave / SCRIPTS.ZIP / scripts.fat / misc / bincoeff.m next >
Text File  |  1999-04-29  |  2KB  |  74 lines

  1. ## Copyright (C) 1995, 1996  Kurt Hornik
  2. ## 
  3. ## This program is free software; you can redistribute it and/or modify
  4. ## it under the terms of the GNU General Public License as published by
  5. ## the Free Software Foundation; either version 2, or (at your option)
  6. ## any later version.
  7. ## 
  8. ## This program is distributed in the hope that it will be useful, but
  9. ## WITHOUT ANY WARRANTY; without even the implied warranty of
  10. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  11. ## General Public License for more details. 
  12. ## 
  13. ## You should have received a copy of the GNU General Public License
  14. ## along with this file.  If not, write to the Free Software Foundation,
  15. ## 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  16.  
  17. ## usage:  bincoeff (n, k)
  18. ##
  19. ## Returns the binomial coefficient of n and k.
  20.  
  21. ## Author: KH <Kurt.Hornik@ci.tuwien.ac.at>
  22. ## Created: 8 October 1994
  23. ## Adapted-By: jwe
  24.  
  25. function b = bincoeff (n, k)
  26.   
  27.   if (nargin != 2)
  28.     usage ("bincoeff (n, k)");
  29.   endif
  30.   
  31.   [retval, n, k] = common_s (n, k);
  32.   if (retval > 0)
  33.     error ("bincoeff:  n and k must be of common size or scalars");
  34.   endif
  35.   
  36.   [r, c] = size (n);
  37.   s = r * c;
  38.   n   = reshape (n, s, 1);
  39.   k   = reshape (k, s, 1);
  40.   b   = zeros (s, 1);
  41.   
  42.   ind = find (! (k >= 0) | (k != real (round (k))) | isnan (n));
  43.   if (any (ind))
  44.     b(ind) = NaN * ones (length (ind), 1);
  45.   endif
  46.   
  47.   ind = find (k == 0);
  48.   if (any (ind))
  49.     b(ind) = ones (length (ind), 1);
  50.   endif
  51.  
  52.   ind = find ((k > 0) & ((n == real (round (n))) & (n < 0)));
  53.   if any (ind)
  54.     b(ind) = (-1) .^ k(ind) .* exp (lgamma (abs (n(ind)) + k(ind)) ...
  55.     - lgamma (k(ind) + 1) - lgamma (abs (n(ind))));
  56.   endif
  57.   
  58.   ind = find ((k > 0) & ((n != real (round (n))) | (n >= k)));
  59.   if (length (ind) > 0)
  60.     b(ind) = exp (lgamma (n(ind) + 1) - lgamma (k(ind) + 1) ...
  61.     - lgamma (n(ind) - k(ind) + 1));
  62.   endif
  63.   
  64.   ## clean up rounding errors
  65.   ind = find (n == round (n));
  66.   if (any (ind))
  67.     b(ind) = round (b(ind));
  68.   endif
  69.   
  70.   b = reshape (b, r, c);
  71.   
  72. endfunction
  73.  
  74.