2^30
0から2^10の範囲の乱数を生成したい。rand()
関数はこれほど多くの数には適さないと聞きましたが、ほぼ均等に分布して生成する別の方法はありますか?
6 に答える
C ++<random>
ライブラリは優れたオプションであり、PRNGエンジンとディストリビューションの多くの選択肢があります。
#include <random>
#include <cstdint>
#include <iostream>
int main() {
std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937_64 eng(seed);
std::uniform_int_distribution<> dist(0, 1<<10);
for (std::uint32_t i = 0; i< (1<<30); ++i) {
int value = dist(eng);
std::cout << value << ' ';
}
}
また、random_deviceはそれ自体がエンジンであり、実装によっては、非決定論的または暗号化されたRNGへのアクセスを提供する場合があります。
std::random_device eng;
std::cout << dist(eng) << '\n';
たとえば、libc ++では、デフォルトで/ dev / urandomを使用します。これは、OSXではYarrow暗号化RNGアルゴリズムを使用します。
Javaでは、2^48の値の後に繰り返されるランダムを使用できます。
Random rand = new Random();
for(int i = 0; i < (1<<30); i++) {
int n = rand.nextInt(1 << 10);
}
これは、興味深いRNGが多数含まれている古いUsenetの投稿です。すべて非常に簡単に実装できます。
http://www.cse.yorku.ca/~oz/marsaglia-rng.html
それらはメルセンヌツイスターと完全には一致しないかもしれませんが、私はそれらのいくつかをうまく利用しており、それらは確かにデフォルトのrand()実装のいくつかよりも優れています。それらはランダム性のDIEHARDテストに合格し、含まれている最大の周期ジェネレーターの周期は2 ^ 7700を超え、実装にかかる行数はわずか2行です。
g_random_int()は、[0..2^32-1]の範囲に均等に分散されたランダムなguint32を返します。
#include <glib.h>
int
main(void)
{
g_print("%d\n", g_random_int());
return 0;
}
gccを使用:
gcc -o rand rand.c `pkg-config --cflags --libs glib-2.0`
編集:
/ dev / random(移植性が低い)から直接読み取り、通常どおりにコンパイルします。
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
int
main(void)
{
int fd;
unsigned int number;
fd = open("/dev/random", O_RDONLY);
read(fd, &number, sizeof(number));
printf("%u\n", number);
close(fd);
return 0;
}
PS:エラーを確認してください。
ランダム性と期間を増やす簡単な方法:
public class Random2 {
private static int LEN = 64;
private final int[] buf = new int[LEN];
private Random r;
private final int maxInt = 1 << 10;
public Random2() {
r = new Random();
for (int i = 0; i < LEN; i++)
buf[i] = r.nextInt(maxInt);
}
public int nextInt() {
int i = r.nextInt(LEN);
int x = buf[i];
buf[i] = r.nextInt(maxInt);
return x;
}
}
Mark A. Overtonは、2011年5月24日に、Dr。Dobbsに関するかなりシンプルで高品質のRNGに関する素晴らしい記事を掲載しました。