Author: Not specified Language: text
Description: Not specified Timestamp: 2017-01-30 02:08:25 +0000
View raw paste Child paste by: Not specified Reply
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <math.h>
  5. int main() {
  6.     double x, pi;
  7.     double p=0.0, p2=0.0, e=0.0;                //p=f(r),p2=f^2,e=error
  8.     int try, ntry;
  9.     printf("Input the number of MC trials\n");
  10.     scanf("%d",&ntry);
  11.     srand((unsigned)time((long *)0));
  12.     for (try=0; try<ntry; try++) {
  13.         x = rand()/(double)RAND_MAX;
  14.         p += 4.0/(1.0 + x*x);
  15.         p2 += 4.0* 4.0/((1.0 + x*x)*(1.0 + x*x));
  16.     }
  17.     pi = p/ntry;
  18.     p2 = p2/ntry;
  19.     e  = sqrt((p2-pi*pi)/((double)(ntry-1)));
  20.  
  21.     printf("MC estimate for PI = %f\n Error = %e\n",pi,e);
  22.     return 0;
  23. }
View raw paste Child paste by: Not specified Reply