Randomness

Hi.
I created a function that generates random number.
I want to know is its randomness comparable to rand() function?
How about performance?
1
2
3
4
5
6
7
8
9
10
11
12
unsigned long Random()
{
	unsigned long rem;
	unsigned long rnd;
	
	for(int i = 0; i < sizeof(long) * 8; i++)
	{
		rem = rand() % 2;
		rnd = rnd & ( ~(rem << i) );
	}
	return rnd;
}

It iterates all bits of rnd and may or may not change that bit.
Note that I did not initialize rnd with 0 or a random number, does it matter?
Since it is based on rand() (and uninitialized stack space) it will have at best equal randomness to rand. Likely its randomness and distribution will be worse.

In terms of performance, since you are calling rand at least 32 times, it will be at least 32x slower than rand.

Basically you're better off just using rand().

If you don't like rand, here's another rng you can use:

1
2
3
4
5
6
7
8
9
10
11
12
unsigned long rand_state = 0;

void my_srand(unsigned long seed)
{
  rand_state = seed;
}

unsigned long my_rand()
{
  rand_state = (rand_state * 69069) + 362437;
  return rand_state;
}
Last edited on
Since it is based on rand() (and uninitialized stack space) it will have at best equal randomness to rand. Likely its randomness and distribution will be worse.

Why? I read somewhere that in generating random integer, every bit should have same probability of 0.5
I think this algorithm can meet that condition.
Your algorithm for generating random number is predictable because you used constant numbers.
Of course it's predictable. Its pseudo-random, not truly random. Both rand() and Disch's method are, I believe, this:
http://en.wikipedia.org/wiki/Linear_congruential_generator

In any case, you are using uninitialized stack space (as Disch pointed out), which is likely even less random than the results of the generator.
I read somewhere that in generating random integer, every bit should have same probability of 0.5


I don't know where you read that, but that's not how randomness is generally determined.

You want 2 things from a random number generator:

1) a full period. IE, if you generate numbers between [0..0xFFFFFFFF] as you are, one would expect every one of those numbers to be produced (an equal amount of times). Failure to do this means your generator has bias towards certain numbers.

2) even distribution. IE, you won't see a lot of similar numbers in a row. Failure to do this makes your generator not appear random.


I don't think your generator does either of those.


Your algorithm for generating random number is predictable because you used constant numbers.


As Zhuge pointed out, all pRNGs are predictable.

But really, unless you're doing crypto work, I wouldn't worry about it too much.
Last edited on
Thank you guys. I got it.
Topic archived. No new replies allowed.