Skip to content

Instantly share code, notes, and snippets.

@dc1394
Created December 31, 2023 13:13
Show Gist options
  • Save dc1394/fdde22bf8017371d9658d77e4bdcfb1e to your computer and use it in GitHub Desktop.
Save dc1394/fdde22bf8017371d9658d77e4bdcfb1e to your computer and use it in GitHub Desktop.
Twitterのモンテカルロ法のC++版の速度比較コード(C++のmt19937)
#include <iomanip> // for std::setprecision
#include <ios> // for std::ios::fixed, std::ios::floatfield
#include <iostream> // for std::cout, std::endl
#include <random> // for std::mt19937, std::uniform_real_distribution
namespace {
inline double mcpi();
}
int main()
{
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout << "pi = "
<< std::setprecision(16)
<< mcpi()
<< std::endl;
}
namespace {
double mcpi()
{
auto constexpr seed = 20231226;
auto constexpr num_points = 1000000000;
auto num_inside = 0;
std::mt19937 engine(seed);
// 一様実数分布
// [0.0, 1.0)の値の範囲で、等確率に実数を生成する
std::uniform_real_distribution<double> dist(0.0, 1.0);
for (auto i = 0; i < num_points; i++) {
auto const x = dist(engine);
auto const y = dist(engine);
auto const r2 = x * x + y * y;
if (r2 < 1.0) {
num_inside++;
}
}
return 4.0 * static_cast<double>(num_inside) / static_cast<double>(num_points);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment