Skip to content

Instantly share code, notes, and snippets.

@kaityo256
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaityo256/eb9b4e246c3f0dda1570 to your computer and use it in GitHub Desktop.
Save kaityo256/eb9b4e246c3f0dda1570 to your computer and use it in GitHub Desktop.
MC calculation of Pi
#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