https://modoocode.com/304

위 블로그를 참고하여 제작했다.


C스타일(srand, rand)사용시 단점

C++에서 random라이브러리를 이용

random 라이브러리의 Reference

- C++ Reference

random라이브러리에서는 'Mersenne Twister(메르센 트위트서)'라는 알고리즘으로 난수를 생성할 수 있게 해준다.

메르센 트위스터

코드와 주석을 자세하게 적어놓았다.

#include <iomanip>
#include <iostream>
#include <map>
#include <random>
using namespace std;

int main() {
    // 하드웨어 기반의 시드를 얻는다.
    random_device rd;

    // 위에서 얻은 시드를 기반으로 난수생성기를 초기화하자.
    // 함수호출연산자를 사용한다.
    // 원하는 시드가 있다면 직접입력해도 된다.
    // ex) mt19937 gen((unsigned int)time(NULL));
    // ex) mt19937 gen(123);

    // '메르센 트리거'알고리즘으로 난수를 생성하겠다는 뜻이다.
    mt19937 gen(rd());

    // 균등분포(Uniform Distribution) 객체를 정의한다.
    // 원하는 범위를 입력하자.
    uniform_int_distribution<int> dis(0, 49);
    // 검증
    int t = 10;
    while (t--) {
        cout << "uni rand = " << dis(gen) << "\\n";
    }

    // 정규분포 (Normal Distribution) 객체를 정의한다.
    // 평균과 표준편차를 인수로 넣는다.
    normal_distribution<double> dist(0, 1);
    // 검증을 위해 히스토그램을 그려보자
    map<int, int> hist{};
    for (int n = 0; n < 10000; n++) {
        ++hist[round(dist(gen))];
    }
    for (auto p : hist) {
        cout << setw(2) << p.first << ' '
             << string(p.second / 100, '*') << ' ' << p.second << '\\n';
    }
}

결과

uni rand = 28
uni rand = 36
uni rand = 17
uni rand = 45
uni rand = 0
uni rand = 29
uni rand = 43
uni rand = 25
uni rand = 47
uni rand = 48
-4  2
-3  51
-2 ***** 582
-1 ************************ 2404
 0 ************************************** 3894
 1 *********************** 2399
 2 ***** 598
 3  66
 4  4

vscode에서는 random_device로 시드를 생성하면 같은 값이 생성되는 오류가 있다.

Why do I get the same sequence for every run with std::random_device with mingw gcc4.8.1?