Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the algorithm used in .NET to generate random numbers? [duplicate]

Tags:

c#

.net

random

When I use Random.Next() what's the algorithm used by framework to return to me a "pseudorandom" number?

I read a little bit about Linear congruential generator. Is this the technique used by .NET?

EDIT:

I look the documentation about Random class, but this is a famous technique? this algorithm has a name as the example (Linear congruential generator) ?

like image 798
Only a Curious Mind Avatar asked Mar 20 '23 16:03

Only a Curious Mind


1 Answers

It usually pays to check the documentation for this kind of thing:

The current implementation of the Random class is based on Donald E. Knuth's subtractive random number generator algorithm. For more information, see D. E. Knuth. "The Art of Computer Programming, volume 2: Seminumerical Algorithms". Addison-Wesley, Reading, MA, second edition, 1981.

That brings me to this:

http://rosettacode.org/wiki/Subtractive_generator

Also worth mentioning, from the same MSDN document:

To generate a cryptographically secure random number suitable for creating a random password, for example, use a class derived from System.Security.Cryptography.RandomNumberGenerator such as System.Security.Cryptography.RNGCryptoServiceProvider.

Specifically, the regular Random algorithm is weak because of this statement in the second link:

Anyone who observes i consecutive numbers can predict the next numbers

Where i is not as large as you might think.

like image 125
Joel Coehoorn Avatar answered Mar 22 '23 05:03

Joel Coehoorn