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