Invalid Random Number

Source: Internet
Author: User
Tags random seed
For a long time, system. Random has been used well, and every random number is almost satisfactory. As follows: Code System. Random R =   New Random ();
Int S = R. Next ();

However, when I am working on a project and suddenly encounter a large number of random numbers, sometimes the random numbers are not random, and the random numbers before and after are often the same. What is going on?

Google has been using the following code for a long time

System. Random R =   New Random (uncheck (( Int ) Datetime. Now. ticks ));
Int S = R. Next ();

The effect is the same. After reading msdn, we found that random () uses time as the seed of the random generator by default. ticks hasn't changed yet when a large number of random numbers are used. As we all know, currently, all of our commonly used random generators are pseudo-random numbers and require seeds. When the seeds are the same, the random sequences are the same, so the random numbers are not random.

After finding the problem, we took the right remedy and paused for a millisecond each time before getting the random number.

System. Threading. thread. Sleep ( 1 );

In this way, each random seed is different, so that the random number is more random.

Complete code:

System. Random random =   New Random ();

System. Threading. thread. Sleep ( 1 );

IntSerial=Random. Next ();

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.