gauss.awk 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # generate a normally distributed random number
  2. function boxmuller(x1, x2, w)
  3. {
  4. if (gaussindex==1)
  5. {
  6. gaussindex = 0;
  7. return gauss1;
  8. }
  9. else
  10. {
  11. do
  12. {
  13. x1 = 2.0 * rand() - 1.0;
  14. x2 = 2.0 * rand() - 1.0;
  15. w = x1 * x1 + x2 * x2;
  16. } while (w >= 1.0);
  17. w = sqrt((-2.0 * log(w)) / w );
  18. gauss1 = x1 * w;
  19. gaussindex = 1;
  20. return (x2 * w);
  21. }
  22. }
  23. function boxmuller_old(x1, x2, w, y1, y2)
  24. {
  25. do
  26. {
  27. x1 = 2.0 * rand() - 1.0;
  28. x2 = 2.0 * rand() - 1.0;
  29. w = x1 * x1 + x2 * x2;
  30. } while ( w >= 1.0 );
  31. w = sqrt( (-2.0 * log( w ) ) / w );
  32. y1 = x1 * w;
  33. y2 = x2 * w;
  34. return y1;
  35. }
  36. BEGIN {
  37. srand();
  38. max = 0;
  39. min = 100;
  40. total = 0;
  41. for (j=-20; j<20; j++)
  42. {
  43. freq[j] = 0;
  44. }
  45. for (i=1; i<1000; i++)
  46. {
  47. foo = boxmuller();
  48. if (foo > max) max = foo;
  49. if (foo < min) min = foo;
  50. total += foo;
  51. freq[int((foo+4)*7)]++
  52. # for (j=-25; j<25; j++)
  53. # {
  54. # if (foo*7 > (j-1) && foo*7 < j)
  55. # {
  56. # freq[j]++;
  57. # }
  58. # }
  59. }
  60. print "min=" min;
  61. print "max=" max;
  62. print "avg=" total / 1000;
  63. for (j=1; j<55; j++)
  64. {
  65. printf "%3d ", j;
  66. for (k=1; k<freq[j]; k++)
  67. {
  68. printf "x";
  69. }
  70. printf "\n";
  71. }
  72. }