乱数を生成する必要がありますが、できるだけ広い範囲 (少なくとも 64 ビット) から生成します。ディストリビューションが完璧かどうかは気にしないのでうまくいきstd::rand()
ますが、int
. c++11 には、任意のサイズの数値を生成できる乱数生成機能があることは理解していますが、使用するのは非常に複雑です。説明されている機能 (64 ビット以上の乱数) を可能な限り単純な方法 (など) で取得するために、できるだけ単純に使用する方法の簡単な例を誰かが投稿できますかstd::rand()
?
3 に答える
これは、この目的で C++11 乱数生成を使用する方法です ( http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distributionから調整):
#include <random>
#include <iostream>
int main()
{
/* Initialise. Do this once (not for every
random number). */
std::random_device rd;
std::mt19937_64 gen(rd());
/* This is where you define the number generator for unsigned long long: */
std::uniform_int_distribution<unsigned long long> dis;
/* A few random numbers: */
for (int n=0; n<10; ++n)
std::cout << dis(gen) << ' ';
std::cout << std::endl;
return 0;
}
の代わりにfromを使用して、(実際の大きな整数ライブラリを使用せずに) 可能な最大の整数範囲を取得unsigned long long
できます。std::uintmax_t
cstdint
次のように、乱数ジェネレータ エンジンを srand/rand のようなメソッドに簡単にラップできます。
#include <random>
#include <iostream>
struct MT19937 {
private:
static std::mt19937_64 rng;
public:
// This is equivalent to srand().
static void seed(uint64_t new_seed = std::mt19937_64::default_seed) {
rng.seed(new_seed);
}
// This is equivalent to rand().
static uint64_t get() {
return rng();
}
};
std::mt19937_64 MT19937::rng;
int main() {
MT19937::seed(/*put your seed here*/);
for (int i = 0; i < 10; ++ i)
std::cout << MT19937::get() << std::endl;
}
( や のようsrand
にrand
、この実装はスレッドセーフを気にしません。)
ラッパー関数は非常に簡単なので、エンジンを直接使用できます。
#include <random>
#include <iostream>
static std::mt19937_64 rng;
int main() {
rng.seed(/*put your seed here*/);
for (int i = 0; i < 10; ++ i)
std::cout << rng() << std::endl;
}
C++11 ではありませんが、十分に簡単です
((unsigned long long)rand() << 32) + rand()
ここでは、int64 の 2 つの部分を int32 として生成します。
JasonD
ご指摘のとおり、32ビット整数を生成することを前提としていますrand()
。xor
rand() << x
、rand() << (2*x)
、rand() << (3*x)
など、x
<= bit は番号による生成でrand()
可能です。それもOKのはずです。