algorithmrandom

How to use XORShift algorithm to generate random numbers


How to use XORShift algorithm to generate 96-bit random numbers. After run the application, each time I press "Start Button" it returns a different 96-bit number.

Code for XORShift algorithm:

unsigned long xor()
{
  static unsigned long y=2463534242;
  yˆ=(y<<13); y=(y>>17); 
  return (yˆ=(y<<5)); 
}

Solution

  • This code is supposed to result in a different value for each run. Since y is static, it's value is initially 2463534242. But due to the static keyword, the value will remain in memory, until the program terminates (this is a bit of a simplified explanation, but it should do for this problem). So after the first run of the program, the value of y is the same as the result of xor(). This y is the initial value of y (the seed), when xor() is called for the next time, thus xor() produces a different value in the next run.