开发者

Will Random.Next ever stop being random?

I need to create 开发者_开发百科random numbers between 0 and upto 2 so I am using:

//field level
private static Random _random = new Random();

//used in a method
_random.Next(0, 2)

My question is: will the sequence ever repeat / stop been random? Should I recreate (_random = new Random();) every day?


Your code is fine as it is.

You do not need to create a new Random object daily.

Note that Random is not truly random, but produces a pseudo-random result.


If you check the 'remarks' section in the documentation you will find that System.Random is a pseudo-random generator.

This means in theory the sequence does eventually repeat. In practice it very much depends on what you're doing as to how much this matters. For example, the length of the sequence is such that no human will ever notice them repeating. On the otherhand, it's pretty useless for cryptography.

Edit to add: restarting daily won't make much difference. Either the pseudo-randomness is sufficient for you or you need to look into cryptographically secure way of generating random numbers.


Math.Random returns a 32-bit signed integer, it will repeat on the 2^32'nd call if you dont reseed. If you DO reseed it will repeat itself sooner.


Random is not that random. If you need "more" random, you should have a look a cryptographic classes, such as RandomNumberGenerator (abstract), for example: RNGCryptoServiceProvider


If you read this, you'll see that Random is (currently) based on the subtractive lagged Fibonacci generator of (24, 55) which should guarantee the period to be at least 2^55 . BUT if you look at the end of the page, someone has pointed to a possible bug (the comment of ytosa on October 2010)

http://msdn.microsoft.com/en-us/library/system.random(v=vs.100).aspx

Lets say that the period is long enough unless you need to do "special" applications!

I will add that the Wiki http://en.wikipedia.org/wiki/Lagged_Fibonacci_generator tells us there is a paper that shows that the 24, 55 sequence of lagged Fibonacci isn't "random enough" (under Problems with LFG)


If the purpose is to generate cryptographically secure random numbers, you should probably use a better PRNG. If you just want the occasional random number and true randomness isn't critical (which I imagine given the output values range) then your code is most likely just fine as it is.


It worth mention (at list by my experience) that if you have a method when you declare :

 Random myRand=new Random();
 myRand.Next(10);  
 //...doing somthing with that

and then, if you call this method many times (in a loop) , you might ends up with a lot of duplicates results. (that what happend to me).

and the solution I found was to move Random myRand=new Random() to be a class member initiation statment ( instead of a local variable of a method), match like you did.

after that , there were no longer duplicated results

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜