gsl_randist__bigauss.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* randist/bigauss.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_math.h"
  22. #include "gsl_rng.h"
  23. #include "gsl_randist.h"
  24. /* The Bivariate Gaussian probability distribution is
  25. p(x,y) dxdy = (1/(2 pi sigma_x sigma_y sqrt(c)))
  26. exp(-((x/sigma_x)^2 + (y/sigma_y)^2 - 2 r (x/sigma_x)(y/sigma_y))/2c) dxdy
  27. where c = 1-r^2
  28. */
  29. void
  30. gsl_ran_bivariate_gaussian (const gsl_rng * r,
  31. double sigma_x, double sigma_y, double rho,
  32. double *x, double *y)
  33. {
  34. double u, v, r2, scale;
  35. do
  36. {
  37. /* choose x,y in uniform square (-1,-1) to (+1,+1) */
  38. u = -1 + 2 * gsl_rng_uniform (r);
  39. v = -1 + 2 * gsl_rng_uniform (r);
  40. /* see if it is in the unit circle */
  41. r2 = u * u + v * v;
  42. }
  43. while (r2 > 1.0 || r2 == 0);
  44. scale = sqrt (-2.0 * log (r2) / r2);
  45. *x = sigma_x * u * scale;
  46. *y = sigma_y * (rho * u + sqrt(1 - rho*rho) * v) * scale;
  47. }
  48. double
  49. gsl_ran_bivariate_gaussian_pdf (const double x, const double y,
  50. const double sigma_x, const double sigma_y,
  51. const double rho)
  52. {
  53. double u = x / sigma_x ;
  54. double v = y / sigma_y ;
  55. double c = 1 - rho*rho ;
  56. double p = (1 / (2 * M_PI * sigma_x * sigma_y * sqrt(c)))
  57. * exp (-(u * u - 2 * rho * u * v + v * v) / (2 * c));
  58. return p;
  59. }