C ++ 11 난수 라이브러리를 사용하여 난수 생성
제목에서 알 수 있듯이 새로운 C ++ 11 <random>
라이브러리를 사용하여 난수를 생성하는 방법을 찾으려고합니다 . 이 코드로 시도했습니다.
std::default_random_engine generator;
std::uniform_real_distribution<double> uniform_distance(1, 10.001);
내가 가진 코드의 문제점은 컴파일하고 실행할 때마다 항상 같은 숫자를 생성한다는 것입니다. 그래서 내 질문은 무작위 라이브러리의 다른 함수가 실제로 무작위 인 동안 이것을 달성 할 수있는 것입니다.
내 특정 유스 케이스의 경우 범위 내에서 값을 얻으려고했습니다. [1, 10]
Microsoft의 Stephan T. Lavavej (stl)는 Going Native에서 새로운 C ++ 11 임의 함수를 사용하는 방법과 사용하지 않는 이유에 대해 이야기했습니다 rand()
. 여기에는 기본적으로 질문을 해결하는 슬라이드가 포함되어 있습니다. 아래 슬라이드에서 코드를 복사했습니다.
그의 전체 연설은 여기에서 볼 수 있습니다 : http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
#include <random>
#include <iostream>
int main() {
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> dist(1.0, 10.0);
for (int i=0; i<16; ++i)
std::cout << dist(mt) << "\n";
}
우리는 random_device
이라는 이름의 난수 생성기를 시드하기 위해 한 번 사용 mt
합니다. random_device()
보다 느리지 만 mt19937
운영 체제에서 임의의 데이터를 요청하기 때문에 시드 할 필요가 없습니다 ( 예 : RdRand 와 같은 다양한 위치에서 소스 제공 ).
보면 이 질문 / 답변 , 그 표시 uniform_real_distribution
되돌 범위의 수를 [a, b)
당신이 원하는, [a, b]
. 그렇게하려면 uniform_real_distibution
실제로 다음과 같아야합니다.
std::uniform_real_distribution<double> dist(1, std::nextafter(10, DBL_MAX));
내 '무작위'라이브러리는 C ++ 11 임의 클래스 주위에 매우 편리한 래퍼를 제공합니다. 간단한 'get'방법으로 거의 모든 작업을 수행 할 수 있습니다.
예 :
범위의 난수
auto val = Random::get(-10, 10); // Integer auto val = Random::get(10.f, -10.f); // Float point
임의의 부울
auto val = Random::get<bool>( ) // 50% to generate true auto val = Random::get<bool>( 0.7 ) // 70% to generate true
std :: initilizer_list의 임의 값
auto val = Random::get( { 1, 3, 5, 7, 9 } ); // val = 1 or 3 or...
반복자 범위 또는 모든 컨테이너의 임의 반복자
auto it = Random::get( vec.begin(), vec.end() ); // it = random iterator auto it = Random::get( vec ); // return random iterator
그리고 더 많은 것들! github 페이지를 확인하십시오.
https://github.com/effolkronium/random
다음은 그 라인을 따라 작성한 것입니다.
#include <random>
#include <chrono>
#include <thread>
using namespace std;
//==============================================================
// RANDOM BACKOFF TIME
//==============================================================
class backoff_time_t {
public:
random_device rd;
mt19937 mt;
uniform_real_distribution<double> dist;
backoff_time_t() : rd{}, mt{rd()}, dist{0.5, 1.5} {}
double rand() {
return dist(mt);
}
};
thread_local backoff_time_t backoff_time;
int main(int argc, char** argv) {
double x1 = backoff_time.rand();
double x2 = backoff_time.rand();
double x3 = backoff_time.rand();
double x4 = backoff_time.rand();
return 0;
}
~
여기 의사 난수 생성기에 대해 읽을 수있는 자료가 있습니다.
https://en.wikipedia.org/wiki/Pseudorandom_number_generator
기본적으로 컴퓨터의 난수에는 시드가 필요합니다 (이 숫자는 현재 시스템 시간 일 수 있음).
바꾸다
std::default_random_engine generator;
으로
std::default_random_engine generator(<some seed number>);
두 가지 일반적인 상황이 있습니다. 첫 번째는 난수를 원하고 품질이나 실행 속도에 대해 너무 소중하지 않다는 것입니다. 이 경우 다음 매크로를 사용하십시오.
#define uniform() (rand()/(RAND_MAX + 1.0))
RAND_MAX가 double의 정밀도보다 크지 않은 경우 p에서 0-1-epsilon 범위의 p를 제공하지만 올 때 걱정할 필요는 없습니다.
int x = (int) (uniform () * N);
Now gives a random integer on 0 to N -1.
If you need other distributions, you have to transform p. Or sometimes it's easier to call uniform() several times.
If you want repeatable behaviour, seed with a constant, otherwise seed with a call to time().
Now if you are bothered about quality or run time performance, rewrite uniform(). But otherwise don't touch the code. Always keep uniform() on 0 to 1 minus epsilon. Now you can wrap the C++ random number library to create a better uniform(), but that's a sort of medium-level option. If you are bothered about the characteristics of the RNG, then it's also worth investing a bit of time to understand how the underlying methods work, then provide one. So you've got complete control of the code, and you can guarantee that with the same seed, the sequence will always be exactly the same, regardless of platform or which version of C++ you are linking to.
참고URL : https://stackoverflow.com/questions/19665818/generate-random-numbers-using-c11-random-library
'Programing' 카테고리의 다른 글
Eclipse 디버거에서 되돌아가는 방법? (0) | 2020.07.05 |
---|---|
node.js 자식 프로세스-스폰과 포크의 차이점 (0) | 2020.07.05 |
chrome-devtools가 실제로 모든 JS 소스를 검색하도록 할 수 있습니까? (0) | 2020.07.05 |
'npm start'는 언제 사용하고 'ng serve'는 언제 사용합니까? (0) | 2020.07.05 |
SQL Server 인덱스-오름차순 또는 내림차순으로 어떤 차이가 있습니까? (0) | 2020.07.05 |