2

So I am using the Wikipedia entry of XORShift Generators to make a PRNG. My code is as follows.

uint32_t xor128(void) {
    static uint32_t x = 123456789;
    static uint32_t y = 362436069;
    static uint32_t z = 521288629;
    static uint32_t w = 88675123;
    uint32_t t;

    t = x ^ (x << 11);
    x = y; y = z; z = w;
    return w = w ^ (w >> 19) ^ t ^ (t >> 8);
}   

My question is, how can I use this to generate double numbers between [0, 1)?

Thanks for any help.

CMilby
  • 624
  • 1
  • 6
  • 23

2 Answers2

2

Just divide the returned uint32_t by the maximum uint32_t (cast as a double). This does have an approximately one in four-billion chance of being 1, though. You could put in a test for the maximum and discard it if you wish.

ooga
  • 15,423
  • 2
  • 20
  • 21
2

Assuming you want a uniform distribution, and aren't too picky about randomising all of the bits for extremely small numbers:

double xor128d(void) {
    return xor128() / 4294967296.0;
}

Since xor128() cannot return 4294967296, the result cannot be exactly 1.0 -- however, if you returned a float, it might still be rounded up to 1.0f.

If you try to add more bits to fill the whole mantissa then you'll face the same rounding headache for doubles.

Do you want the whole mantissa randomised for all possible values? That's a little harder.

sh1
  • 4,324
  • 17
  • 30