Summary of implementation methods of generating random numbers in Java

Random numbers are often used in practical development. For example, in some systems, the user will be given a random initialization password after creating the user. Because the password is random, only the user knows it. After they get the random password, they need to change it in the system immediately. This is the principle of using random numbers. In short, random numbers are often used in daily development work. The methods and skills of generating random numbers in different development languages are different. The author here takes Java language as an example to talk about the methods and some skills of random number generation.

I. random method is used to generate random numbers. Generating random numbers in the Java language is relatively simple because there is a ready-made method to use. In the math class, the Java language provides a method called random. Through this method, the system can generate random numbers. However, by default, the range of random numbers generated is relatively small, which is a double random number greater than or equal to 0 to less than 1. Although the range of random numbers is relatively small, it can not meet the daily needs. For example, it may be necessary to generate integer random numbers in daily work. In fact, as long as some flexible processing is carried out on this method, random numbers in any range can be obtained. For example, we can first generate a random number through the random method, and then multiply the result by 10. At this time, the generated random number is a number greater than or equal to 0 and less than 10. Then use the int method for conversion (it will remove the number after the decimal, that is, only get the integer part, not rounding). Finally, you can obtain an integer random number from 0 to 9. The implementation method is very simple, which is to modify the original random method according to the following format: (int) (math. Random() * 10). In fact, we can also extend this method to generate random numbers in any range. To replace this 10 with N, such as (int) (math. Random() * n). At this point, the application will generate a random number greater than or equal to 0 and between small and n. If n is set to 5, it will produce an integer random number between 0 and 5. If this is written as a method with parameters, as long as the user inputs the maximum value of the random number to be generated, this method can be used to generate the random number in the specified range. Define your own tool library in Java. Sometimes programmers may need to generate a random even or odd number within a specified range. Can this be achieved by this method? The answer is yes. For example, the program needs to generate an even number in the range of 1-100. How to achieve this? First of all, you need to generate a random number from 0 to 99 (as for why it is 99 here, you can see the reason patiently). To realize this requirement, it is very simple. It can be realized by the following statement: I = 1 + (int) (math. Random() * 100). Where (int) (math. Random() * 99) generates an integer random number from 0 to 99. Then add 1 to produce a random integer between 1 and 100. The generated random number is then assigned to variable I. But at this time, the random number generated by it has both even and odd numbers. Now programmers need a random even number. Then we can add an if judgment statement after it. Divide the random number by 2. If there is no remainder (or the remainder is 0), it indicates that the random number is even and can be returned directly. If the remainder returned is not zero, it indicates that it is an odd number. As long as we add 1, it becomes an even number and return. Note that in the above random number generation, the range used by the author is 0 to 99, and then add 1 to make it a random number from 1 to 100. The final result is a random even number between 1 and 100. In fact, if you want to range random odd numbers, you need to modify the above statement slightly. Java: change your world and my world. Suppose that users want to generate an odd or even number in any range, can it be realized? Suppose that the user wants to realize an arbitrary even number from m to n (where m is visible). Although the random number generated by random method has strict range restrictions, as long as it is reasonably converted, the programmer can still use this method to generate the random data required by the user.

2. Generate random numbers through random class. In the Java language, in addition to generating random numbers through the random method, random numbers can also be generated through a random class. Program developers can create a random number generator by instantiating a random object. For example, random I = new random(). Through this statement, a random number generator is created by using the random class. However, when creating random numbers in this way, the mechanism is different from that of random method. When instantiating an object in this way, the java compiler takes the current time of the system as the seed of the random number generator. Because time is changing all the time. If this time is used as the seed of the generator, it can ensure that the generated random number is really random, and the repetition rate of the generated random number will be greatly reduced. It is more convenient to use this method. For example, you can use the provided keywords to let the program return a random integer (int nextint (10)) and so on. However, its return control is a little more difficult than the random method. If the system needs to provide a random odd number between 10 and 50, it cannot be completed by using this random class. In other words, this random class is used to generate random numbers, which can only control the upper limit, not the lower limit. In other words, it can specify the maximum range of random numbers, but not the minimum range of random numbers. Therefore, it is slightly less flexible than the random method. In addition, to implement this method, you must first create an object. That is, use the randow class to create objects. This is different from randow's method. In the above example, the randow method itself is a method in the math class, which can be called directly, eliminating the method of object creation. Therefore, the author suggests that readers and program developers should use random method to create random numbers. The random class is used only when generating some special random numbers. If it is necessary to generate a double precision random number with Gaussian probability density, it is relatively simple to create a random number by using the random class method.

3、 Generate random characters. The two methods described above generate random numerical data. But sometimes users may also need to generate random characters. In fact, random method can also be used to generate random characters. For example, a random lowercase character can be generated by code: (char) ('a '+ Math. Random() * ('z' -'a '+ 1)). In fact, this is similar to generating random numbers between any two numbers. Through the above code, any random character within a range can be generated. By properly trimming this code, you can also generate random characters between any two characters and random characters of any uppercase characters. The conversion method is similar to the random number in any range mentioned above. If you are interested, you can test it yourself. The master leads you to the door and practices in yourself. If I tell you all the answers here, you won't be very impressed. If you go back and try it yourself, it will be easier to remember. Here I give you a hint. Just adjust the code of (char) ('a '+ Math. Random() * ('z' -'a '+ 1)) according to the statement m + (int) (math. Random() * (n-m)).

4、 Advanced by reading math Random () source code, or simply use the automatic completion function of the IDE, which can be easily found by developers, Java lang.Math. Random () uses an internal randomly generated object - a powerful object that can be flexibly generated randomly: Boolean values, all number types, and even Gaussian distributions. For example:

It has a disadvantage that it is an object. Its method must be called through an instance, which means that its constructor must be called first. If the memory is sufficient, the above expression is acceptable; But when there is not enough memory, it will cause problems.

A simple solution can avoid creating a new instance every time you need to generate a random number, that is, using a static class. Guess you might think of Java Lang. math, good. We just improved Java Initialization of lang.math. Although the amount of work is low, you also have to do some simple unit tests to ensure that it will not make mistakes.

Assuming that the program needs to generate a random number to store, the problem comes again. For example, sometimes it is necessary to operate or protect the seed. An internal number is used to store the state and calculate the next random number. In these special cases, it is not appropriate to share randomly generated objects.

Concurrency in the environment of Java EE multithreaded applications, randomly generated instance objects can still be stored in classes or other implementation classes as a static attribute. Fortunately, Java util. Random is thread safe, so there is no risk that multiple thread calls will destroy seeds.

Another thing worth considering is multithreaded Java An instance of lang.threadlocal. The lazy way is to implement a single instance through the Java API. Of course, you can also ensure that each thread has its own instance object.

Although Java does not provide a good way to manage Java util. A single instance of random. However, the long-awaited Java 7 provides a new way to generate random numbers:

This new API combines the advantages of two other methods: single instance / static access, like math As flexible as random (). Threadlocalrandom is also faster than any other method for handling high concurrency.

Experience Chris marasti Georg points out:

Make the distribution unbalanced, for example: 0.0 - 0.499999 will round to 0, and 0.5 to 1.499999 will round to 1. Then, how to use the old syntax to achieve the correct balanced distribution is as follows:

Fortunately, if we use Java util. Random or Java util. concurrent. Threadlocalrandom doesn't have to worry about the above problems.

Java actual combat project introduces some incorrect use of Java util. Harm of random API. This lesson tells us not to use:

Instead, use:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>