Summary of how to generate random Numbers in Java

  • 2020-04-01 04:25:27
  • OfStack

Random Numbers are often used in actual development work. For example, some systems will give the user a random initialization password after the user is created. The password is so random that only the user knows it. After they get the random password, they need to change it in the system immediately. That's how we use random Numbers. In short, random Numbers are often used in daily development work. Different development languages have different methods and techniques for generating random Numbers. Here I take the Java language as an example to talk about the method of random number generation and some tips.

1. Use random method 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. This method allows the system to generate random Numbers. By default, however, it produces a small range of random Numbers, ranging from greater than or equal to 0 to less than 1. Although its random number generation range is relatively small, can not meet the daily needs. Such as the daily work may need to generate integer random Numbers. In fact, with some flexibility in this method, you can get random Numbers in any range.
For example, we can first generate a random number through the random method, and then multiply the result by 10. The random Numbers generated are Numbers greater than or equal to 0 and less than 10. The Int method is then used for the conversion (which removes the decimal and drops the following number, i.e., gets only the integer part, not the rounded part). Finally, we can get a random integer number from 0 to 9. Its implementation method is very simple, is the original random method in the following format :(int)(math.random ()*10). In fact, we can extend this method to generate random Numbers in any range. Change this 10 to n, such as (int)(math.random ()*n). At this point, the application will generate a random number greater than or equal to 0 and n. If n is set to 5, it will generate a random number of integer type between 0 and 5. If you write this as a method with parameters, you can use this method to generate a range of random Numbers as long as the user enters the maximum number that needs to be generated. Define your own library of tools in Java
Sometimes a programmer may need to generate a random even or odd number in a specified range. Is it possible to do it this way? The answer is yes. Now the program needs to generate an even number between 1 and 100. How to implement at this point ? First, you need to generate a random number between 0 and 99. To implement this requirement is as simple as: I =1+(int)(math.random ()*100). Where (int)(math.random ()*99) generates integer Random Numbers from 0 to 99. And then plus 1 is going to produce a random integer between 1 and 100. The generated random number is then assigned to the variable I. But the random Numbers it produces are both even and odd. Now what the programmer needs is a random even number. So we can put an if statement after that. Divide the random number by 2. If there is no remainder (or remainder of 0), the random number is even. If it doesn't return a remainder of zero, that means it's odd, and we just add 1 to make it even, and we return. Note that in the above random number generation, the author used a range of 0 to 99 and then added 1 to make it a random number from 1 to 100. The end result is a random even number between 1 and 100. In fact, if you want to range random odd Numbers, to the above statement needs to be slightly modified. Java: change your world and mine
Suppose the user now wants to generate an odd or even number in any range. Suppose the user now wants to implement any even number between m and n (where m is
It can be seen that although the random method itself produces random Numbers, it has a relatively strict range limit. But with proper translation, the programmer can still use this method to generate the random data the user needs.

2. Generate Random Numbers through the Random class.
In the Java language, in addition to generating random Numbers through the random method, you can also generate random Numbers through a random class. A program developer can create a generator of Random Numbers by instantiating a Random object. So Random I equals new Random(). This statement takes advantage of the Random class to create a Random number generator. However, when creating Random Numbers in this way, the mechanism is different from the Random method to generate Random Numbers. When instantiating an object this way, the Java compiler USES the current system time as the seed for the random number generator. Because time is changing all the time. If this time is used as the seed of the generator, the generated random Numbers can be guaranteed to be really random, and the repetition rate of the generated random Numbers will be greatly reduced.
It is convenient to use this method. You can use the provided keyword to have the program return a random integer (int nextInt(10)), and so on. But its return control is a little more difficult than the Random method. If the system now needs to provide a Random odd number between 10 and 50, the use of this Random class cannot be completed. In other words, using this Random class to generate Random Numbers, it can only control the upper limit, but not the lower limit. In other words, it can specify the largest range of random Numbers, but not the smallest range. So, it's a little bit less flexible than the Random method.
In addition, to implement this method, you must first create an object. That is, using the Randow class to create objects. This is different from the Randow method. In the example above, the Randow method itself is a method in the math class that can be called directly, eliminating the need for object creation. For this reason, I recommend that readers and developers use the Random method to create Random Numbers. The Random class is used only when generating some relatively special Random Numbers. If now it is necessary to generate a Random number with double precision value with probability density of gaussian distribution, it is relatively simple to use the method of Random class to create Random Numbers.

              Generate random characters.
Both methods described above produce random numerical data. But sometimes the user may also need to generate random characters. You can also use the random method to generate random characters. If can use the code to generate a random lowercase characters: (char) (' a '+ Math. The random () * (' z' - 'a' + 1)). This is similar to generating random Numbers between any two Numbers. The above code can generate a range of arbitrary random characters. By trimming this code appropriately, you can also generate random characters between any two characters and random characters for any uppercase character. The transformation is similar to the random Numbers in any range mentioned above. If you are interested, you can test it yourself. Master lead the door, practice in their own. If the author here will all the answers to tell you, everyone's impression will not be very deep. It's easier to remember if you go back and try it yourself.
The author here to give you a hint, only need according to the m + (int) (Math. The Random () * (n - m)) this statement to adjust (char) (' a '+ Math. The Random () * (' z' - 'a' + 1)) this code.

              Fourth, advanced
              By reading the source code for math.random (), or simply taking advantage of the IDE's auto-complete capabilities, developers can easily see that java.lang.math.random () USES an internal random-generated object -- a powerful object that can be generated flexibly at random: Boolean values, all number types, even gaussian distributions. Such as:


new java.util.Random().nextInt(10)

It has the disadvantage that it is an object. Its methods must be called through an instance, which means its constructor must be called first. If memory is sufficient, the above expression is acceptable. But when you run out of memory, you have a problem.

A simple solution that avoids the need to create a new instance every time a random number is generated is to use a static class. Guess you might think of java.lang.math, good, we just improved the initialization of java.lang.math. Although this is a low volume project, you should also do some simple unit tests to make sure it doesn't go wrong.

Assuming the program needs to generate a random number to store, the problem arises again. For example, sometimes you need to manipulate or protect a seed, an internal number to store state and calculate the next random number. In these special cases, sharing randomly generated objects is not appropriate.

concurrent
In the context of a Java EE multithreaded application, a randomly generated instance object can still be stored in a class or other implementation class as a static property. Fortunately, java.util.Random is thread-safe, so there is no risk that multiple thread calls will break the seed.

Another example worth considering is an instance of multithreaded java.lang.threadlocal. The lazy way is to implement singletons through the Java API itself, and of course you can make sure that each thread has its own instance object.

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


java.util.concurrent.ThreadLocalRandom.current().nextInt(10)

This new API combines the advantages of the other two approaches: single instance/static access, which is as flexible as math.random (). ThreadLocalRandom is also faster than any other method for dealing with high concurrency.

experience
Chris marasti-georg points out:


Math.round(Math.random() * 10)

Make the distribution unbalanced, for example: 0.0-0.499999 rounds to 0, and 0.5 to 1.499999 rounds to 1. So how to use the old syntax to achieve the correct equilibrium distribution, as follows:


Math.floor(Math.random() * 11 ) 

Fortunately, if we use the Java util. Random or Java. Util. Concurrent. ThreadLocalRandom do not have to worry about these problems.

The Java live project introduces some of the hazards of using the java.util.Random API incorrectly. This lesson teaches us not to use:


Math.abs(rnd.nextInt())%n

To use:


rnd.nextInt(n)


Related articles: