C   130
ran gauss
Guest on 14th March 2023 12:14:48 AM


  1. #define N 100000
  2.  
  3. #include <stdio.h>
  4. #include <strings.h>
  5. #include <stdlib.h>
  6. #include <math.h>
  7.  
  8.  
  9.  
  10. //
  11. // random numbers in { 0 - 1 }
  12. //
  13. double random_num()
  14. {
  15.   return (double)rand()/(double)RAND_MAX;
  16. }
  17.  
  18.  
  19.  
  20. //
  21. // Gaussian distributed random numbers
  22. //
  23. double Gaussian ( double *gauss1, double *gauss2 )
  24. {
  25.   double twou, radius, theta;
  26.  
  27.   twou = -2.0*log(1.0-random_num());
  28.   radius = sqrt(twou);
  29.   theta = 2*M_PI*random_num();
  30.   *gauss1 = radius*cos(theta);
  31.   *gauss2 = radius*sin(theta);
  32. }
  33.  
  34.  
  35.  
  36. int main()
  37. {
  38.   int    i, j, count, counter[100];
  39.   double deltav, gauss1, gauss2;
  40.  
  41.   deltav = 0.1;
  42.  
  43.   for ( j=0; j<100 ; j++ )
  44.     counter[j] = 0;
  45.  
  46.   count = 0;
  47.   for ( i=0; i<N ; i++ )
  48.     {
  49.       Gaussian( &gauss1, &gauss2 );
  50.       j = (int)( (gauss1+5.0)/deltav );
  51.       if ( j > 100 ) printf( " ----> %d\n", j );
  52.       counter[j]++;
  53.       j = (int)( (gauss2+5.0)/deltav );
  54.       if ( j > 100 ) printf( " ----> %d\n", j );
  55.       counter[j]++;
  56.       count++;
  57.     }
  58.   printf( " Check - %d\n", count );
  59.  
  60.   count = 0;
  61.   for ( j=0; j<100 ; j++ )
  62.     {
  63.       printf( "%7.3f   %d\n", deltav*j, counter[j] );
  64.       count = count + counter[j];
  65.     }
  66.   printf( " Check - %d\n", count );
  67. }

Raw Paste

Login or Register to edit or fork this paste. It's free.