Random number problem

Source: Internet
Author: User
Tags generator

When you see the word "random" in the title of the stack Overflow website, you can basically determine that this is the same basic problem with countless similar problems. This article takes you through the question of why randomness can cause so many problems and how to solve them.

The problem with Stack Overflow (or newsgroup, or mailing list etc) is usually this:

I use Random.next to generate random numbers, but it always gives me the same number. It keeps running, but every time it produces the same number of times.

This is because of this code:

Bad code! Do not use!
    
         for (int i = 0; i < i++)
    
         {Console.WriteLine (
    
                   generatedigit ());
    
         }
    
         ....
    
         static int Generatedigit ()
    
         {
    
                   Random rng = new Random ();
    
                   Assume there ' d be more logic this really return
    
                   rng. Next (a);
    
         }

So, what's wrong with this procedure?

1. Interpretation

This random class is not a real random number generator, it is a pseudo random number generator. Any random instance has a certain amount of state, and when you call next (or nextdouble or nextbytes), it uses that state to return to seemingly random data, altering its internal state accordingly to make it easier for you to get another pseudo random number when the next call is made.

All of this is OK if you start a random instance with the same initial state (available through the seed) and use the same sequence method to invoke it, then you will get the same result.

So what exactly is wrong with our sample code? A new random instance that we use is also in the loop iteration. Random parameterless constructors take the current date and time as seeds-you can usually execute a lot of code before the internal timer works, and the current date and time change. Therefore, we repeat the same seed and repeat the same result.

2. What can we do about it?

There are many solutions to this problem, some of which are better than others. Let's first pick out one of these methods, because it's different from the other methods.

3. Using an encrypted random number generator

. NET has a RandomNumberGenerator class should be an abstract class derived from all cryptographic random number generators. The framework itself comes with one such derived class: RNGCryptoServiceProvider. The idea of a cryptographic random number generator is that even though it may still be a pseudo random generator, it is hard to predict. Built-in implementations require multiple entropy sources to effectively present "noise" in your computer and are unpredictable. It can use this noise not only to compute a seed, but also to let you know the current state when generating the next number, which may not be enough to predict the next result (or those that have been generated), depending largely on the specific implementation. Windows can also take advantage of the randomness of professional hardware resources (such as a piece of hardware to observe radioisotope decay), making the random number generator more secure.

Compared to this random, if you see (say) 10 results call Random.next (100) and put in a lot of computational resource tasks, you may work out the original seed and predict that the next result will be ... It's possible to know what the results were. This would be disastrous if this random number were applied to the purposes of securities or finance. Cryptographic random number generators are usually slower than random, but they do a better job of empowering numbers to be unpredictable and independent.

In many cases, the performance of the random number generator is not a problem-but there is a problem with an appropriate API. The design foundation of a random number generator This is only used to generate random bytes. Compare the randomness of this API, which allows you to request a random integer, or a random double, or a random set of bytes. I often find that I need a range of integers, and it is important to get a reliable and uniformly random byte array. It's not impossible, but at least you might want an adapter class on a random number generator. In most cases, if you can avoid the traps described above, pseudo random random is acceptable.

Let's see how this can be done.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.