我正在做一些蒙特卡勒模拟。 CSPRNG太昂贵了,所以我改用xoshiro256**生成器,其名称暗示用随机位填充四个64位无符号整数。
在我的用例中,每次只需要一个随机位,但是仅提取最低位似乎是巨大的浪费。
static uint64_t s[4] = { /* SEED */ };
static inline unsigned random_bernoulli(void) {
next(s);
return s[0] & 1U;
}
如何最好以不占用CPU的方式充分利用256位?还是最低位足够随机,所以我目前的方法是好的?
答案 0 :(得分:2)
容易。小心点。
static uint64_t s[4] = { /* SEED */ };
static inline unsigned random_bernoulli(void) {
static uint64_t accum[4];
static int counter = -1;
static int bit = 0;
if (counter < 0) {
next(s);
accum[0] = s[0];
accum[1] = s[1];
accum[2] = s[2];
accum[3] = s[3];
counter = 3;
bit = 63;
}
unsigned value = (accum[counter] >> bit) & 1U;
if (--bit < 0) {
bit = 63;
--counter;
}
return value;
}