반응형


 

http://www.boost.org/doc/libs/1_51_0/doc/html/boost_random.html

boost 에서 랜덤 생성도 제공해 줍니다 rand(time(0)) 을 쓸때 생기는 흔한 (혹은 뻔한) 패턴을 피해서 각자 만들곤

하는데 그런 노고를 안해도 될 듯 하네요

 

1~6 랜덤 숫자 구하기

1
2
3
4
5
6
7
8
9
#include <boost/random.hpp>
 
int GetDice()
{
    boost::random::mt19937 rng;
    boost::random::uniform_int_distribution<> six(1,6);
 
    return six(rng);
}

 

특정 숫자 범위내에서 구하기

1
2
3
4
5
6
7
8
9
10
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
 
int GetRand()
{
    boost::random::mt19937 gen;
    boost::random::uniform_int_distribution<> dist(1, 6);
     
    return dist(gen);
}

 

랜덤 패스워드 구하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <boost/random/random_device.hpp>
#include <boost/random/uniform_int_distribution.hpp>
 
void Password()
{
    std::string chars(
        "abcdefghijklmnopqrstuvwxyz"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "1234567890"
        "!@#$%^&*()"
        "`~-_=+[{]{\\|;:'\",<.>/? ");
 
    boost::random::random_device rng;
    boost::random::uniform_int_distribution<> index_dist(0, chars.size() - 1);
     
    for(int i = 0; i < 8; ++i)
        std::cout << chars[index_dist(rng)];
 
    std::cout << std::endl;
}











boost random  tech-note 

2006/09/07 17:08

복사http://blog.naver.com/moonday/60028409808


1 링크 및 설명 #

2 개요 #

이 라이브러리는 몇가지 종류의 의사난수 생성기들을 제공합니다. 의사 난수 생성기의 품질은 알고리즘과 매개변수에 따라 확연히 차이가 나는 특징이 있습니다. 이 라이브러리는 이러한 알고리즘들을 boost::random에 숨겨둔 템플릿 매개변수를 사용한 클래스 템플릿으로 구현하고 있습니다. 모든 특정 매개변수 선택사항들은 boost namespace내에 typedef 형태로 알맞게 지정되어있습니다

의사 난수 생성기는 프로그램 실행중에는 그렇게 자주 구성(초기화)되지 않는 경향이 있는데, 이는 다음과 같은 이유 때문입니다.

첫째, 생성기의 초기화는 생성기 내부 정보의 전반적인 초기화를 요구합니다. 따라서, 많은 내부 상태를 가지고 있는 생성기는 초기화 비용이 많이 듭니다.(아래 참조)

둘째, 초기화는 언제나 생성될 난수배열의 "씨앗(seed)"값으로 사용될 값을 필요로 합니다. 예를 들어, seed 값을 얻는 방법들 중 하나는 가능한한 높은 해상도의 현재시간(예를 들면, 마이크로초 또는 나노초)를 적용하는 것입니다. 이때 현재시간을 기준으로 seed값을 지정하여 의사난수생성기가 다시 초기화 될 때에는 이전에 처음 초기화될 때 사용되었던 seed값의 시간으로부터 거의 상수에 가까운(난수성향이 아닌) 값을 취하게 됩니다. 설상가상으로 시스템 클럭수가 현저히 낮은 경우 이 차이는 거의 0에 가깝게 되며, 결과적으로 생성기는 같은 순서의 난수 배열을 생성하게 됩니다. 몇몇 경우에 있어서 이는 원하는 결과가 아닐 겁니다.

아래에 설명한 모든 의사 난수 생성기는 CopyConstructible 및 Assignable로부터 상속되었다는 점을 알아두시기 바랍니다. 생성기를 복사하거나 대입하는 것은 내부 상태 모두를 복사한다는 것을 의미하므로, 원본과 복사본 모두 같은 순서의 난수 배열을 생성하게 될 것입니다. 종종 이러한 특징을 원하지 않을 경우도 있습니다. 특히, std::generate와 같은 표준 라이브러리를 채용한 알고리즘에 주의하십시요. 이들은 값에 의한 참조방식의 매개변수로서 함수자(functor)를 가지며, 이는 복사생성자를 호출하는 효과가 있습니다.

다음 표는 생성기들의 몇가지 특징을 요약한 것입니다. 사이클 길이는 생성기 품질을 대략적으로 추정할 수 있는 값입니다. 대략적인 상대 속도는 성능 평가기중이며, 높을수록 더빨리 난수생성처리를 수행한다는 의미입니다.

생성기사이클 길이대략적인 요구 메모리대략적인 상대 실행속도비고
minstd_rand2^31-2sizeof(int32_t)40-
rand482^48-1sizeof(uint64_t)80-
lrand48 (C 라이브러리)2^48-1-20전역함수
ecuyer1988대략 2^612*sizeof(int32_t)20-
kreutzer1986?1368*sizeof(uint32_t)60-
hellekalek19952^31-1sizeof(int32_t)3몇몇 차원에서 좋은 단일 분포(uniform distribution)를 가짐
mt11213b2^11213-1352*sizeof(uint32_t)100350 차원에서 좋은 단일 분포(uniform distribution)를 가짐
mt199372^19937-1625*sizeof(uint32_t)100623 차원에서 좋은 단일 분포(uniform distribution)를 가짐
lagged_fibonacci607대략 2^32000607*sizeof(double)150-
lagged_fibonacci1279대략 2^670001279*sizeof(double)150-
lagged_fibonacci2281대략 2^1200002281*sizeof(double)150-
lagged_fibonacci3217대략 2^1700003217*sizeof(double)150-
lagged_fibonacci4423대략 2^2300004423*sizeof(double)150-
lagged_fibonacci9689대략 2^5100009689*sizeof(double)150-
lagged_fibonacci19937대략 2^105000019937*sizeof(double)150-
lagged_fibonacci23209대략 2^120000023209*sizeof(double)140-
lagged_fibonacci44497대략 2^230000044497*sizeof(double)60-

표를 살펴보면, 난수 생성기를 선택함에 있어서 품질, 성능, 메모리에 관한 trade-off가 존재한다는 것을 알 수 있습니다. The multitude of generators provided in this library allows the application programmer to optimize the trade-off with regard to his application domain. Additionally, employing several fundamentally different random number generators for a given application of Monte Carlo simulation will improve the confidence in the results.

If the names of the generators don't ring any bell and you have no idea which generator to use, it is reasonable to employ mt19937 for a start: It is fast and has acceptable quality.

Note: These random number generators are not intended for use in applications where non-deterministic random numbers are required. See nondet_random.html for a choice of (hopefully) non-deterministic random number generators.

In this description, I have refrained from documenting those members in detail which are already defined in the concept documentation.
 
 


반응형

'메타프로그래밍 > Boost::' 카테고리의 다른 글

boost::variant  (0) 2013.02.13
Boost::foreach  (0) 2013.01.29
Boost::mpl  (0) 2012.12.25
boost::thread  (0) 2012.12.25
boost::weak_ptr  (0) 2012.11.24

+ Recent posts