How does seed influence the generation of random numbers?

Asked

Viewed 593 times

5

The doubt is very simple, I would like to know how the class System.Random generates random pseudorandomness numbers from a seed, which I find odd. I know they are not totally random, and so I have my doubts of how they are actually generated. For example,

int x = new Random(123).Next(1, 100);

x will have a random value, but if I always use this seed, it will no longer be random and therefore, this seed will always return the same value in the methods Next, NextDouble and NextBytes?

If yes, how is the algorithm for creating these random numbers based on this seed?

Updating

The core of my question is how the random number is generated based on the seed, and not as this random number is generated. The point was to ask what and how the seed influence in the generation of this number.

1 answer

3


According to the documentation: Pseudo-random numbers are chosen with equal probability from a finite set of numbers. The numbers chosen are not completely random because a mathematical algorithm is used to select them, but are sufficiently random for practical purposes. The current implementation of the Random class is based on a modified version of Donald E. Knuth’s subtractive random number generator algorithm. For more information, see D. E. Knuth. The Art of Computer Programming, Volume 2: Seminumeric Algorithms. To generate an cryptographically secure random number, such as the one that is suitable for creating a random password, use the Rngcryptoserviceprovider class or derive a System.Security.Cryptography.Randomnumbergenerator class.

Basically, this class generates random numbers using as "base" another value, which would be the number of milliseconds that have passed since the operating system was started (Environment.Tickcount). This is the default if you don’t pass any value in the constructor.

If you pass a known number, then yes the values will always be the same.

Example:

var r = new Random(10);
Console.WriteLine(r.Next(1, 100)); //irá sempre retornar 95
Console.WriteLine(r.Next(1, 100)); //irá sempre retornar 75

r = new Random();
Console.WriteLine(r.Next(1, 100)); //retorno aleatório
Console.WriteLine(r.Next(1, 100)); //retorno aleatório

Source: http://referencesource.microsoft.com/#mscorlib/system/Random.Cs

  • So this algorithm for creating random numbers is used in all systems? For example, if I ask for a random number with such a seed in PHP, the value returned will be the same if you do the same procedure in C#?

  • 1

    I cannot say where else it is used. It is worth remembering that the Random class implements a modified version of the algorithm. But obviously, if the same implementation is used in other languages, the same value will be returned yes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.