Skip to content

Instantly share code, notes, and snippets.

@ev-br
Created May 28, 2013 09:19
Show Gist options
  • Save ev-br/5661560 to your computer and use it in GitHub Desktop.
Save ev-br/5661560 to your computer and use it in GitHub Desktop.
A trivial Monte Carlo integrator. Just a quick-and-dirty example, nothing more.
/************** A simple MC integrator **************/
#include<iostream>
#include<boost/random.hpp>
using namespace std ;
double f(double); // to be integrated
double w(double); // probab. dens.
int main(){
boost::mt19937 rng(11u);
boost::variate_generator< boost::mt19937&, boost::uniform_01<> > rndm(rng, boost::uniform_01<>()) ;
double sum=0., Z=0. ;
size_t sweep=0;
for(;;){
sweep++;
for(int j=0; j<1000000 ; ++j ){
double x=-log(rndm()); // W(x)dx = exp(-x)dx
sum += f(x)/w(x) ;
Z += 1.;
};
cout<<sweep<<": "<<sum/Z<<"\n";
}
}
// to be integrated
double f(double x){
return exp(-8.*x);
}
// probab density
double w(double x){
return exp(-x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment