gsl_randist__bernoulli.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* randist/bernoulli.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_rng.h"
  22. #include "gsl_randist.h"
  23. /* The bernoulli distribution has the form,
  24. prob(0) = 1-p, prob(1) = p
  25. */
  26. unsigned int
  27. gsl_ran_bernoulli (const gsl_rng * r, double p)
  28. {
  29. double u = gsl_rng_uniform (r) ;
  30. if (u < p)
  31. {
  32. return 1 ;
  33. }
  34. else
  35. {
  36. return 0 ;
  37. }
  38. }
  39. double
  40. gsl_ran_bernoulli_pdf (const unsigned int k, double p)
  41. {
  42. if (k == 0)
  43. {
  44. return 1 - p ;
  45. }
  46. else if (k == 1)
  47. {
  48. return p ;
  49. }
  50. else
  51. {
  52. return 0 ;
  53. }
  54. }