cstatic

How does XorShift32 works?


I have this homework where i need to implement xorshift32(i can t use anything else) so i can generate some numbers but i don t understand how the algorithm works or how to implement it.

I am trying to print the generated number but i don t know how to call the xorshift32 function because of the state[static 1] argument.

uint32_t xorshift32(uint32_t state[static 1])
{
    uint32_t x = state[0];
    x ^= x << 13;
    x ^= x >> 17;
    x ^= x << 5;
    state[0] = x;
    return x;
}

I do not have much information on xorshft32 other that what is on wikipedia(en.wikipedia.org/wiki/Xorshift).


Solution

  • The C code in the wikipedia article is somewhat misleading:

    Here is a working example that uses both the 32 bit and the 64 bit versions:

    #include <inttypes.h>
    #include <stdio.h>
    #include <stdint.h>
    
    /* The state word must be initialized to non-zero */
    uint32_t xorshift32(uint32_t state[])
    {
      /* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */
      uint32_t x = state[0];
      x ^= x << 13;
      x ^= x >> 17;
      x ^= x << 5;
      state[0] = x;
      return x;
    }
    
    uint64_t xorshift64(uint64_t state[])
    {
      uint64_t x = state[0];
      x ^= x << 13;
      x ^= x >> 7;
      x ^= x << 17;
      state[0] = x;
      return x;
    }
    
    int main()
    {
      uint32_t state[1] = {1234};  // "seed" (can be anthing but 0)
    
      for (int i = 0; i < 50; i++)
      {
        printf("%" PRIu32 "\n", xorshift32(state));
      }
    
      uint64_t state64[1] = { 1234 };  // "seed" (can be anthing but 0)
    
      for (int i = 0; i < 50; i++)
      {
        printf("%" PRIu64 "\n", xorshift64(state64));
      }
    }
    

    The mathematical aspects are explained in the wikipedia article and in it's footnotes.

    The rest is basic C language knowledge, ^ is the C bitwise XOR operator.