Function = std::function<double(
66 constuint32_t& num_samples,
67 constuint32_t& discard = 100000) {
68std::vector<double> samples;
69samples.reserve(num_samples);
71 doublex_t = start_point;
73std::default_random_engine generator;
74std::uniform_real_distribution<double> uniform(0.0, 1.0);
75std::normal_distribution<double> normal(0.0, 1.0);
76generator.seed(time(
nullptr));
78 for(uint32_t t = 0; t < num_samples + discard; ++t) {
81 doublex_dash = normal(generator) + x_t;
82 doubleacceptance_probability = std::min(pdf(x_dash) / pdf(x_t), 1.0);
83 doubleu = uniform(generator);
86 if(u <= acceptance_probability) {
91samples.push_back(x_t);
114 constuint32_t& num_samples = 1000000) {
115 doubleintegral = 0.0;
116std::vector<double> samples =
119 for(
doublesample : samples) {
120integral += function(sample) / pdf(sample);
123 returnintegral /
static_cast<double>(samples.size());
134std::cout <<
"Disclaimer: Because this is a randomized algorithm," 137<<
"it may happen that singular samples deviate from the true result." 142math::monte_carlo::Function f;
143math::monte_carlo::Function pdf;
145 doublelower_bound = 0, upper_bound = 0;
148f = [&](
double& x) {
return-x * x + 4.0; };
152pdf = [&](
double& x) {
153 if(x >= lower_bound && x <= -1.0) {
156 if(x <= upper_bound && x >= 1.0) {
159 if(x > -1.0 && x < 1.0) {
166(upper_bound - lower_bound) / 2.0, f, pdf);
168std::cout <<
"This number should be close to 10.666666: "<< integral
172f = [&](
double& x) {
returnstd::exp(x); };
176pdf = [&](
double& x) {
177 if(x >= lower_bound && x <= 0.2) {
180 if(x > 0.2 && x <= 0.4) {
183 if(x > 0.4 && x < upper_bound) {
190(upper_bound - lower_bound) / 2.0, f, pdf);
192std::cout <<
"This number should be close to 1.7182818: "<< integral
199f = [&](
double& x) {
returnstd::sin(M_PI * x) / (M_PI * x); };
201pdf = [&](
double& x) {
202 return1.0 / std::sqrt(2.0 * M_PI) * std::exp(-x * x / 2.0);
207std::cout <<
"This number should be close to 1.0: "<< integral
std::vector< double > generate_samples(const double &start_point, const Function &pdf, const uint32_t &num_samples, const uint32_t &discard=100000)
short-hand for std::functions used in this implementation
static void test()
Self-test implementations.
int main()
Main function.
double integral_monte_carlo(const double &start_point, const Function &function, const Function &pdf, const uint32_t &num_samples=1000000)
Compute an approximation of an integral using Monte Carlo integration.
Functions for the Monte Carlo Integration implementation.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4