当你只需要1位时,充分利用256个随机位

问题描述 投票:0回答:1

我正在做一些蒙特卡尔模拟。 CSPRNG太贵了,所以我使用xoshiro256**生成器,顾名思义用随机位填充四个64位无符号整数。

在我的用例中,每次只需要一个随机位,但只提取最低位似乎是一个巨大的浪费。

static uint64_t s[4] = { /* SEED */ };

static inline unsigned random_bernoulli(void) {
    next(s);
    return s[0] & 1U;
}

如何充分利用256位,最好是以不那么CPU密集的方式?或者,最低位是否足够随机,所以我目前的方法是好的?

c performance optimization random scientific-computing
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.