Created
December 31, 2023 13:09
-
-
Save dc1394/150bd5b59bd41da91038306f68389286 to your computer and use it in GitHub Desktop.
Twitterのモンテカルロ法のC++版の速度比較コード(C++に備え付けのrand())
This file contains hidden or 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
#include <cstdlib> // for std::rand, std::srand | |
#include <iomanip> // for std::setprecision | |
#include <ios> // for std::ios::fixed, std::ios::floatfield | |
#include <iostream> // for std::cout, std::endl | |
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::srand(seed); | |
for (auto i = 0; i < num_points; i++) { | |
auto const x = static_cast<double>(std::rand()) / static_cast<double>(RAND_MAX); | |
auto const y = static_cast<double>(std::rand()) / static_cast<double>(RAND_MAX); | |
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