l开发者_开发问答ong 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.
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.
here is my suggestion to generate random numbers:
1- choose a punch of websites that are as far away from your location as possible. e.g. if you are in US try some websites that have their server IPs in malasia , china , russia , India ..etc . servers with high traffic are better.
2- during times of high internet traffic in your country (in my country it is like 7 to 11 pm) ping those websites many many many times ,take each ping result (use only the integer value) and calculate modulus 2 of it ( i.e from each ping operation you get one bit : either 0 or 1).
3- repeat the process for several days ,recording the results.
4- collect all the bits you got from all your pings (probably you will get hundreds of thousands of bits ) and choose from them your bits . (maybe you wanna choose your bits by using some data from the same method mentioned above :) )
BE CAREFUL : in your code you should check for timeout ..etc
精彩评论