Author: Not specified Language: cpp-qt
Description: No description (v3) Timestamp: 2017-01-30 02:15:08 +0000
View raw paste Parent 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, pi2, sum = 0.0,sum1=0.0,sum2=0.0,s=0.0 ;  //sum1= sum over pi,  sum2= sum over pi^2, s= standard deviation
  7.   int try, ntry, n, Nneed=100;
  8.   printf("Input the number of MC trials\n");
  9.   scanf("%d",&ntry);
  10.   srand((unsigned)time((long *)0));
  11.   for(n=0; n<Nneed ; n++) {
  12.       sum=0;
  13.       for (try = 0; try < ntry; try++) {
  14.           x = rand() / (double) RAND_MAX;
  15.           sum += 4.0 / (1.0 + x * x);
  16.       }
  17.       pi = sum / ntry;
  18.       sum1 += pi;
  19.       sum2 += pi*pi;
  20.   }
  21.   s=sqrt(sum2/Nneed-(sum1/Nneed)*(sum1/Nneed));
  22.   printf("MC estimate for PI = %f\n standard deviation=%f", pi, s);
  23.   return 0;
  24. }
View raw paste Parent paste by: Not specified Reply