Differences between math. Random () and Java. util. Random () in Java

Source: Internet
Author: User

Today, I suddenly remembered the problem of Random Number Generation in Java. I tried it on the machine and found a difference. Here I will summarize it;

Directly calling math. Random () is to generate a random number between 0 and 1,

If you use

Java. util. random random = new random (); random. nextint () generates a long integer random number and is the same as the previous one. If it is generated later, it will not be the same. For example:

For (INT I = 0; I <10; I ++ ){
Random random = new random ();
Thread. Sleep (100 );
System. Out. Print (INT) random. nextint (100) + "");
}

Is to generate different random long numbers.

If you want to use Java. util. Random () to generate a random number within a specified range, evaluate the modulo operation and perform some processing.

 

you can also use random. nextint (100) to generate a random number less than 100. generally, nextint (range) is recommended. If it is not a large number of operations, math can be used. random now (because it can be relatively slow and rounded up after floating point)

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.