gsl_randist__poisson.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* randist/poisson.c
  2. *
  3. * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or (at
  8. * your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful, but
  11. * WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, write to the Free Software
  17. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. */
  19. #include "gsl__config.h"
  20. #include <math.h>
  21. #include "gsl_sf_gamma.h"
  22. #include "gsl_rng.h"
  23. #include "gsl_randist.h"
  24. /* The poisson distribution has the form
  25. p(n) = (mu^n / n!) exp(-mu)
  26. for n = 0, 1, 2, ... . The method used here is the one from Knuth. */
  27. unsigned int
  28. gsl_ran_poisson (const gsl_rng * r, double mu)
  29. {
  30. double emu;
  31. double prod = 1.0;
  32. unsigned int k = 0;
  33. while (mu > 10)
  34. {
  35. unsigned int m = mu * (7.0 / 8.0);
  36. double X = gsl_ran_gamma_int (r, m);
  37. if (X >= mu)
  38. {
  39. return k + gsl_ran_binomial (r, mu / X, m - 1);
  40. }
  41. else
  42. {
  43. k += m;
  44. mu -= X;
  45. }
  46. }
  47. /* This following method works well when mu is small */
  48. emu = exp (-mu);
  49. do
  50. {
  51. prod *= gsl_rng_uniform (r);
  52. k++;
  53. }
  54. while (prod > emu);
  55. return k - 1;
  56. }
  57. void
  58. gsl_ran_poisson_array (const gsl_rng * r, size_t n, unsigned int array[],
  59. double mu)
  60. {
  61. size_t i;
  62. for (i = 0; i < n; i++)
  63. {
  64. array[i] = gsl_ran_poisson (r, mu);
  65. }
  66. return;
  67. }
  68. double
  69. gsl_ran_poisson_pdf (const unsigned int k, const double mu)
  70. {
  71. double p;
  72. double lf = gsl_sf_lnfact (k);
  73. p = exp (log (mu) * k - lf - mu);
  74. return p;
  75. }