/************************* Program 9.1 ****************************/ /* */ /************************************************************************/ /* 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 MMAX 1000000 #define f(x) (x*x) int iseed; main() /* Integration with the direct sampling Monte Carlo scheme. The integrand is f(x) = x*x. Copyright (c) Tao Pang 1997. */ { int i,m; int t1,t2,t3,t4,t5,t6; time_t ts,tp; struct tm t; double x,sum1,sum2,s,ds; double ranf(); extern int iseed; m = MMAX; /* 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)))); sum1 = 0; sum2 = 0; for(i = 0; i < m; ++i) { x = ranf(); sum1 = sum1+f(x); sum2 = sum2+f(x)*f(x); } s = sum1/m; ds = sqrt(fabs(sum2/m-(sum1/m)*(sum1/m))/m); printf("%16.8lf %16.8lf\n", s,ds); } 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; }