Last active
August 29, 2015 14:24
-
-
Save kaityo256/eb9b4e246c3f0dda1570 to your computer and use it in GitHub Desktop.
MC calculation of Pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdio.h> | |
#include <math.h> | |
#include <stdlib.h> | |
//---------------------------------------------------------------------- | |
const int N = 10000; | |
const int SAMPLE = 65536; | |
//---------------------------------------------------------------------- | |
double | |
myrand(void){ | |
return static_cast<double>(rand())/static_cast<double>(RAND_MAX); | |
} | |
//---------------------------------------------------------------------- | |
double | |
one_trial(void){ | |
int sum = 0; | |
for(int i=0;i<N;i++){ | |
const double x = myrand(); | |
const double y = myrand(); | |
if (x*x+y*y < 1.0) sum ++; | |
} | |
return static_cast<double>(sum)/static_cast<double>(N)*4.0; | |
} | |
//---------------------------------------------------------------------- | |
int | |
main(void){ | |
double a = 0.0; | |
double v = 0.0; | |
for(int i=0;i<SAMPLE;i++){ | |
const double p = one_trial(); | |
a += p; | |
v += p*p; | |
} | |
const double s = static_cast<double>(SAMPLE); | |
a /= s; | |
v /= s; | |
v = sqrt((v -a*a)/(s-1.0)); | |
std::cout << "Total Samples " << N*SAMPLE << std::endl; | |
std::cout << a << std::endl; | |
std::cout << v << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment