RNG using xorshift

Hi, im trying to generate random numbers in a range 1 - 100 but i only keep getting 1 number each time (at least that is random)
Im using this code i found in wikipedia
1
2
3
4
5
6
7
8
9
10
  #include <stdint.h>
 
/* These state variables must be initialized so that they are not all zero. */
uint32_t x, y, z, w;
 
uint32_t xorshift128(void) {
    uint32_t t = x ^ (x << 11);
    x = y; y = z; z = w;
    return w = w ^ (w >> 19) ^ t ^ (t >> 8);
}


I used this in my code like this

1
2
3
4
5
6
7
8
ofstream ofs{ "random_numbers.txt" };

	for (int i = 0; i < 200; i++){
		uint32_t x = time(0), y = time(0), z = time(0), w = time(0);
		uint32_t t = x ^ (x << 11);
		x = y; y = z; z = w;
		ofs << (w = w ^ (w >> 19) ^ t ^ (t >> 8)) % 100 + 1 << std::endl;
	}


All the numbers i read in my t.tx file are the same. Why is this happening?
It's because you are resetting the values of x, y, z and w for each number you generate. You should instead create and initialize these variables once, before the loop.
Last edited on
time(0) returns seconds. So it's rather likely that you get the same value for x,y,z,w for each iteration.
Ohh yea, now we are talking :) Thanks guys so much so much :)
Topic archived. No new replies allowed.