/****************************************************************************** * Program that uses the Monte Carlo Method and the Central Limit Theorem * to compute π. * * 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_TRIALS = 20; static int const SAMPLES_PER_TRIAL = 100000; double calcpi(int samples) noexcept { int inside_count = 0; for (int i = 0; i < 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; } } return (double(inside_count) / double(samples)) * 4; } int main(int argc, char **argv) { setlocale(LC_ALL, "en_US.UTF-8"); wcout.imbue(utf8loc); wcin.imbue(utf8loc); srand(time(0)); double sum = 0.0; for (int i = 0; i < MAX_TRIALS; ++i) { double const p = calcpi(SAMPLES_PER_TRIAL); wcout << fmt::format(L"PI{0:d}: {1:.15f}", i, p) << endl; sum += p; } double const PI = sum / MAX_TRIALS; wcout << fmt::format(L"PI: {0:.15f}", PI) << endl; wcout << fmt::format(L"abs(PI - π): {0:.10e}", abs(PI - M_PI)) << endl; return 0; }