/************************* Program 2.D ****************************/ /* */ /************************************************************************/ /* Please Note: */ /* */ /* (1) This computer program is written by Tao Pang in conjunction with */ /* his book, "An Introduction to Computational Physics," published */ /* by Cambridge University Press in 1997. */ /* */ /* (2) No warranties, express or implied, are made for this program. */ /* */ /************************************************************************/ #include #include #include #define NMAX 1000 int iseed; double pi,x,y; main() /* Another example program to use the Gaussian random number generator. Copyright (c) Tao Pang 1999. */ { int i,n; int t1,t2,t3,t4,t5,t6; time_t ts,tp; struct tm t; void grnf(); extern int iseed; extern double pi,x,y; pi = 4.0*atan(1.0); n = NMAX; /* Initial seed from the system time and and forced to be odd */ ts = time(&tp); t = *gmtime(&tp); t1 = t.tm_sec; t2 = t.tm_min; t3 = t.tm_hour; t4 = t.tm_mday; t5 = t.tm_mon; t6 = t.tm_year; iseed = t6+70*(t5+12*(t4+31*(t3+23*(t2+59*t1)))); if ((iseed%2) == 0) { iseed = iseed-1; } /* Generate the Gaussian random number set */ for (i = 0; i < n; ++i) { grnf(); printf("%16.8lf %16.8lf\n", x,y); } } void grnf() /* Two Gaussian random numbers generated from two uniform random numbers. Copyright (c) Tao Pang 1999. */ { extern int iseed; extern double pi,x,y; double r1,r2; double ranf(); r1 = -log(1.0-ranf()); r2 = 2.0*pi*ranf(); r1 = sqrt(2.0*r1); x = r1*cos(r2); y = r1*sin(r2); } double ranf() /* Uniform random number generator x(n+1)= a*x(n) mod c with a = pow(7,5) and c = pow(2,31)-1. Copyright (c) Tao Pang 1997. */ { const int ia=16807,ic=2147483647,iq=127773,ir=2836; int il,ih,it; double rc; extern int iseed; ih = iseed/iq; il = iseed%iq; it = ia*il-ir*ih; if (it > 0) { iseed = it; } else { iseed = ic+it; } rc = ic; return iseed/rc; }