開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Xcode - Apple
- Windows 10 Pro (OS)
- Visual Studio (コンパイラー)
- Visual Studio Code (Text Editor)
- C++17 (プログラミング言語)
Modern C++チャレンジ ―C++17プログラミング力を鍛える100問 (Marius Bancila(著)、島 敏博(監修)、黒川 利明(翻訳)、オライリージャパン)の1章(数学の問題)、問題13(πの計算)の解答を求めてみる。
コード
#include <iostream> #include <random> #include <cmath> int main() { std::cout << "モンテカルロ法によりπの近似値を求める。" << std::endl; double r = 0.5; std::random_device seed_gen; std::default_random_engine engine(seed_gen()); std::uniform_real_distribution<> dist(0.0, 1.0); for (size_t i = 1;; i++) { int n = std::pow(10, i); int count = 0; std::cout << "試行回数: " << n << "回" << std::endl; for (size_t j = 0; j < n; j++) { double x = dist(engine); double y = dist(engine); if (std::pow(x, 2) + std::pow(y, 2) <= 1) { count += 1; } } double circle_area = count / n; double pi = count / (n * pow(r, 2)); std::cout << "πの近似値: " << pi << std::endl; if (pi > 3.135 && pi < 3.144) { break; } } }
入出力結果(VS 2017 用 x64 Native Tools コマンド プロンプト、Terminal)
C:\Users\...>cl /O2 sample13.cpp && sample13.exe Microsoft(R) C/C++ Optimizing Compiler Version 19.16.27027.1 for x64 Copyright (C) Microsoft Corporation. All rights reserved. sample13.cpp C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include\xlocale(319): warning C4530: C++ 例外処理を使っていますが、アンワインド セマンティクスは有効にはなりません。/EHsc を指定してください。 Microsoft (R) Incremental Linker Version 14.16.27027.1 Copyright (C) Microsoft Corporation. All rights reserved. /out:sample13.exe sample13.obj モンテカルロ法によりπの近似値を求める。 試行回数: 10回 πの近似値: 3.6 試行回数: 100回 πの近似値: 2.92 試行回数: 1000回 πの近似値: 3.132 試行回数: 10000回 πの近似値: 3.1416 C:\Users\...>
0 コメント:
コメントを投稿