4

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) ?

Only a Curious Mind
  • 2,807
  • 23
  • 39
  • 1
    That has nothing to do with C#. It's part of .NET, and can be used from any managed programming language. – John Saunders May 05 '14 at 20:25
  • 4
    Take a look: http://referencesource.microsoft.com/#mscorlib/system/random.cs – Jeroen Vannevel May 05 '14 at 20:26
  • @JohnSaunders Yeah, sorry, thanks by edit. – Only a Curious Mind May 05 '14 at 20:26
  • 1
    @JeroenVannevel this algorithm have a name? its a famous technique? – Only a Curious Mind May 05 '14 at 20:27
  • 1
    Have you looked at the documentation? *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.* – Jeroen Vannevel May 05 '14 at 20:28
  • Note that it looks like there is a bug in the implementation of the algorithm: https://connect.microsoft.com/VisualStudio/feedback/details/634761/system-random-serious-bug – fuglede Aug 17 '17 at 21:22

1 Answers1

7

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.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794