/****************************************************************************** * Compute π using the Monte Carlo method. * * Copyright © 2017 Richard Lesh. All rights reserved. *****************************************************************************/ #undef NDEBUG #include #include #include #include #include #include #include #include std::locale utf8loc(std::locale(), new std::codecvt_utf8); using namespace std; static int const MAX_SAMPLES = 1000000; int main(int argc, char **argv) { setlocale(LC_ALL, "en_US.UTF-8"); wcout.imbue(utf8loc); wcin.imbue(utf8loc); srand(time(0)); int inside_count = 0; for (int i = 0; i < MAX_SAMPLES; ++i) { double const x = rand()/(RAND_MAX + 1.0); double const y = rand()/(RAND_MAX + 1.0); if (x * x + y * y <= 1.0) { ++inside_count; } } double const pi = (double(inside_count) / double(MAX_SAMPLES)) * 4; wcout << fmt::format(L"pi: {0:.15f}", pi) << endl; wcout << fmt::format(L"abs(pi - π): {0:.10e}", abs(pi - M_PI)) << endl; return 0; }