Created
May 28, 2013 09:19
-
-
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.
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
/************** 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