/*Program for caculating mean of a normal r.v. using monte carlo simulation */ #include //for mathfunctions #include #include #include // for timing //function for generate Z ~ N(0,1) (Box-Muller) double normrnd(double mu,double sigma) { double chi,eta,z; chi=drand48(); eta=drand48(); z=mu+sigma*sqrt(-2*log(chi))*cos(2*M_PI*eta); return z; } main() { int i,n; double tid,est,mu,sigma; clock_t ticks1, ticks2; srand48(time(NULL)); //Make a new seed for the random number generator mu=0.0; sigma=1.0; est=0.0; ticks1=clock()/CLOCKS_PER_SEC; n=10000000; for(i = 0; i < n; i = i + 1) { est+=normrnd(mu,sigma); //est=est+normrnd; } est*=1.0/n; //est=est*1/n; ticks2=clock()/CLOCKS_PER_SEC; tid=difftime(ticks2, ticks1); printf("Time is %f\n", tid); printf("Est is %f\n", est); return 0; }