LoginSignup
0
5

More than 5 years have passed since last update.

C++でのモンテカルロ法の実装例

Posted at

本日は

モンテカルロ法C++での実装です. あくまでも例ですので,参考程度に...OTL

書いてみましょう

//monte.cpp
#include <iostream>
#include <random>
using namespace std;

#define NUM 100000000

int main(int argc, char const *argv[])
{
    random_device rnd;
    mt19937 mt(rnd());
    uniform_real_distribution<double> score(0.0,1.0);
    double x, y;
    int counter=0;
    for(int i=0;i<NUM;i++){
        x=score(mt);
        y=score(mt);
        if(x*x + y*y < 1.0){
            counter++;
        }
    }
    double pi=4.0*counter/NUM;
    printf("%f\n",pi );
    return 0;
}

乱数はどうやってやるけまと調べたところ
 Siv3D 開発ブログ C++11 の乱数ライブラリ
にたどり着きましたのでこれを参考にしました.

動かしましょう.

SublimeTextでの動作例です.
スクリーンショット 2017-09-17 20.46.50.png

最適化オプションを使う.

最適化オプションをつけましょう.
最適化オプションの種類の例として
最適化オプション込みのGCCとClangベンチマークの結果は?
を参考にしました.

$ clang++ -o monte -O1 monte.cpp
$ time ./monte
real    0m4.967s
user    0m4.869s
sys 0m0.033s
$ clang++ -o monte -O2 monte.cpp
$ time ./monte
real    0m3.965s
user    0m3.861s
sys 0m0.036s

$ clang++ -o monte -O3 monte.cpp
$ time ./monte
real    0m3.276s
user    0m3.219s
sys     0m0.021s

$ clang++ -o monte -Ofast monte.cpp 
$ time ./monte 
real    0m3.276s
user    0m3.218s
sys     0m0.018s

PCはMacBook12-inchの初代です. だいたい3秒ほどかかります.

0
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
5