Java's Random class, apirandom

Source: Internet
Author: User

Java's Random class, apirandom

In the actual project development process, some random numbers are often required, such as verification numbers during website login, or a certain effect must be achieved at a certain probability, for example, items in a game program are dropped.

In Java APIs, a Random processing-related class is provided in the java. util package. This class is the Random class. Methods related to the generation of random numbers are included in the class.

The Random algorithm implemented in the Random class is pseudo-Random, that is, Random with rules. When a random algorithm is executed, the numbers of the origins of the random algorithm are called seed. A certain number is transformed based on the number of seeds to generate the required random numbers.

For a Random object with the same number of seeds, the Random numbers generated by the same number of times are identical. That is to say, two Random objects with the same number of seeds have identical Random numbers generated for the first time and identical Random numbers generated for the second time. This requires special attention when generating multiple random numbers.

The following describes how to use the Random class and how to generate a Random array of the specified range and the probability of implementing the requirements in the program.

 

1. Generate a Random object

The Random class contains two constructor methods, which are described in sequence below:

 

A. public Random ()

This constructor uses a number related to the relative time of the current system time as the number of seeds, and then uses this number to construct the Random object.

 

B. public Random (long seed)

This constructor can be created by creating a number of seeds.

Sample Code:

 

Random r = new Random ();

Random r1 = new Random (10 );

 

Again, the number of seeds is only the source number of the random algorithm, and is irrelevant to the interval of the generated random number.

 

2. Common methods in the Random class

Methods In the Random class are relatively simple, and the functions of each method are easy to understand. It should be noted that the Random numbers generated by each method in the Random class are evenly distributed, that is, the number generation probability within the range is equal. Below are some basic introductions to these methods:

 

A, public boolean nextBoolean ()

This method is used to generate a random boolean value. The probability of true and false values generated is equal, that is, the probability is 50%.

 

B. public double nextDouble ()

The function of this method is to generate a random double value between [0, 1.0). Here, brackets indicate that the range endpoint is included, and parentheses indicate that the range endpoint is not included, that is, the random decimal number between 0 and 1, which contains 0 and does not contain 1.0.

 

C, public int nextInt ()

The function of this method is to generate a random int value, which is between the int range, that is, between-231 and 231-1.

If you need to generate the int value of the specified range, you need to perform a certain mathematical transformation. For details, see the Code in the following example.

D. public int nextInt (int n)

The function of this method is to generate a random int value, which is an interval between [0, n), that is, a random int value between 0 and n, contains 0, not n.

If you want to generate the int value of the specified range, you also need to perform a certain mathematical transformation. For details, see the Code in the following example.

E. public void setSeed (long seed)

This method is used to reset the number of seeds in the Random object. The Random object after the number of seeds is set is the same as the Random object created with the new keyword for the same number of seeds.

 

3. Random usage example

The Random class is generally used to generate Random numbers for the specified range. The following describes how to generate Random numbers for the corresponding range. The following Random Number Generation Code uses the following Random object r:

Random r = new Random ();

 

A. Generate Decimals in the range [0, 1.0)

Double d1 = r. nextDouble ();

Directly use the nextDouble method.

 

B. Generate Decimals in the range [0, 5.0)

Double d2 = r. nextDouble () * 5;

Because the number range generated by the nextDouble method is [0, 1.0), it is required to increase the range by 5 times.

Similarly, generate a random decimal number in the [0, d) interval. If d is an arbitrary positive decimal number, multiply the return value of nextDouble by d.

C. Generate Decimals in the range [1, 2.5)

Double d3 = r. nextDouble () * 1.5 + 1;

To generate a random decimal number in the range [1, 2.5), you only need to first generate a random number in the range [0, 1.5), and then add 1 to the random number range.

Similarly, to generate random numbers in the range of any decimal range [d1, d2) not starting from 0 (where d1 is not equal to 0), you only need to first generate [0, d2-d1) then add the generated random number range to the d1.

D. generate any integer

Int n1 = r. nextInt ();

Use the nextInt method directly.

E. generate an integer in the range [).

Int n2 = r. nextInt (10 );

N2 = Math. abs (r. nextInt () % 10 );

The above two lines of code can generate an integer in the [0, 10) range.

The first method is directly implemented using the nextInt (int n) method in the Random class.

In the second implementation, call the nextInt () method to generate an arbitrary int number. The value ranges from-10 to 10 ), because according to the mathematical rule, the absolute value of the remainder is smaller than the divisor, and then the absolute value is obtained for this interval, the obtained range is.

Similarly, the following code can be used to generate random integers in any [0, n) range:

Int n2 = r. nextInt (n );

N2 = Math. abs (r. nextInt () % n );

F. generate an integer in the range [0, 10 ].

Int n3 = r. nextInt (11 );

N3 = Math. abs (r. nextInt () % 11 );

The range [] is equivalent to the range [). Therefore, an integer from [) is generated.

G. generate an integer in the range [-).

Int n4 = r. nextInt (18)-3;

N4 = Math. abs (r. nextInt () % 18)-3;

Generate a random integer that is not in the range starting from 0. For details, see the implementation principle of the fractional interval that is not in the range starting from 0.

 

H. Probability implementation

Implementing program logic at a certain probability is also a problem that can be solved by random processing. The following is a simple example of how to use random numbers to implement probability logic.

In the previous method introduction, the numbers generated by the nextInt (int n) method are even, that is, the probability of each number in the interval being generated is the same. If a random integer in the [0,100) interval is generated, the probability of each digit is the same, and because the interval contains a total of 100 integers, therefore, the probability of each number is 1%. According to this theory, the probability problem in the program can be realized.

Example: A Random integer is generated. The integer is generated at a 55% probability of 1, 2 at a 40% probability, and 3 at a 5% probability. The implementation code is as follows:

Int n5 = r. nextInt (100 );

Int m; // result number

If (n5 <55) {// The interval of 55 digits, the probability of 55%

M = 1;

} Else if (n5 <95) {// [40%), 40 digit range, probability

M = 2;

} Else {

M = 3;

}

Because the probability of each number is 1%, the interval probability of any 55 numbers is 55%. For the convenience of code writing, All integers in the [) range will be used here, and the Principles will be the same in the future.

Of course, the code here can be simplified, because the probability is a multiple of 5%, so you only need to control the probability based on 5%. below is the simplified code implementation:

Int n6 = r. nextInt (20 );

Int m1;

If (n6 <11 ){

M1 = 1;

} Else if (n6 <19 ){

M1 = 2;

} Else {

M1 = 3;

}

In the program, the probability logic can be implemented according to the above description.

 

4. Other problems

A. Random objects with the same number of Seeds

As mentioned above, for a Random object with the same number of seeds, the Random numbers generated by the same number of times are identical. The following is the test code:

Random r1 = new Random (10 );

Random r2 = new Random (10 );

For (int I = 0; I <2; I ++ ){

System. out. println (r1.nextInt ());

System. out. println (r2.nextInt ());

}

In this Code, the number of seeds used by the objects r1 and r2 is 10, and the random numbers generated by the two objects with the same number of times are identical.

To avoid the case where Random numbers are the same, you must note that no matter how many Random numbers need to be generated in the project, you can use only one Random object.

B. About the random method in the Math class

In fact, there is also a random method in the Math class. The work of this random method is to generate a random decimal number in the [0, 1.0) range.

By reading the source code of the Math class, we can find that the random method in the Math class is implemented by directly calling the nextDouble method in the Random class.

However, the call to the random method is relatively simple, so many programmers are used to using the random method of the Math class to generate random numbers.

 

Related Article

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.