Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valid random generation algorithm or not?

Tags:

random

long timeValue = timeInMillis();
int rand = timeValue%100 + 1;

If we execute the above code N times in a loop, it will generate N random numbers between 1 to 100. I know generation of random nos is a tough problem. Just wanted to know is this a good random number generation algorithm? Or is it pseudo random number generator?

Why I think this will produce good estimate of random behavior? 1) all no from 1 to 100 will be uniformly distributed. There is no bias. 2) timeInMillis will show somewhat random behavior because we can never really guess at what time CPU will execute this function. There are so many different tasks running in CPU. So the exact time of execution of timeInMillis() instruction is not predictable in next iteration of loop.

like image 239
Sanjeev Kumar Dangi Avatar asked Nov 22 '25 03:11

Sanjeev Kumar Dangi


1 Answers

No. For a start, on most processors, this will loop many times (probably the full 100) within 1 millisecond, which will result in 100 identical numbers.

Even seeding a random number generator with a timer tick can be dangerous - the timer tick is rarely as "random" as you might expect.

like image 104
winwaed Avatar answered Nov 24 '25 21:11

winwaed