[Solved] Random generation of numbers? [closed]


Edit: Original supposition on the problem completely wrong. The cause of you getting all zeros is that the state is not seeded. You need to fill state with something ‘random’.

This code work. Note that the function seed() is in absolutely no way scientifically proven to be good – in fact, I just made it up as I went along, trying to get as much “bits” as possible varying as much as possible in the seed. You should do some research on “seeding random numbers”. (I also tried seeding with just state[i] = i;, and that also seems to work fairly well, but you get quite similar numbers in the first couple of iterations).

#include <iostream>
#include <cstdint>

/* initialize state to random bits */
static uint32_t state[16];
/* init should also reset this to 0 */
static unsigned int index = 0;
/* return 32 bit random number */
uint32_t WELLRNG512(void)
{
    uint32_t a, b, c, d;
    a = state[index];
    c = state[(index+13)&15];
    b = a^c^(a<<16)^(c<<15);
    c = state[(index+9)&15];
    c ^= (c>>11);
    a = state[index] = b^c;
    d = a^((a<<5)&0xDA442D24UL);

    index = (index + 15)&15;
    a = state[index];
    state[index] = a^b^d^(a<<2)^(b<<18)^(c<<28);
    return state[index];
}

void seed()
{
    for(size_t i = 0; i < sizeof(state)/sizeof(state[0]); i++)
    {
    state[i] = (i << (24 + (i & 5))) ^ (i << 7) ^ (i << 6) ^ (i >> 2);
    }
}    

int main()
{
    using namespace std;
    seed();
    for(int i = 0; i < 50; i++)
    {
    cout << WELLRNG512() << endl;
    }
    return 0;
}

1

solved Random generation of numbers? [closed]