This is the 30th day of my participation in the August Text Challenge.More challenges in August

Every day a practical tips, how to choose random number generation

Java has a special Random class for Random number generation. In addition, there is a lot of Math. Random

1. Math.random

The JDK provides a basic tool class called Math that encapsulates some common basic methods, such as generating random numbers, in today’s topic, using the following pose

double val = Math.random();
Copy the code

It’s relatively simple to use and generates floating-point numbers between 0 and 1, but don’t assume that it really only generates random numbers between 0 and 1, as shown in the following example

If you want to use it to generate a [120, 500] range of random number, how to complete?

int ans = Double.valueOf(Math.ceil(Math.random() * 381 + 120)).intValue();
Copy the code

Why does this work?

Translate the above code, the value range is as follows

Math.random() * 381 + 120 Values range as follows

  • [0, 1] times 381 plus 120
  • [0, 381) + 120
  • [120, 501)

Math.ceil takes only the integer part of a floating-point number, so our value range is [120, 500], as expected

Finally, how does math.random () implement random numbers

private static final class RandomNumberGeneratorHolder {
    static final Random randomNumberGenerator = new Random();
}

public static double random(a) {
    return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
}
Copy the code

Please pay attention to the above implementation. Random class is still used at the bottom layer to generate Random numbers, and the above writing method belongs to the classic singleton mode (different from the common double determination method, this is an inner class gameplay, and why it can be used in this way will be explained later).

2. Random

In addition to using math. random above to get random numbers, it is also common to use the random class directly; Next, take a brief look at Random’s usage posture

Create a Random object

// Use the current timestamp as a random seed
Random random = new Random();
// Use a fixed number as a random seed. The advantage is that the random number generated each time is consistent, which facilitates the scene repetition
Random random2 = new Random(10);
Copy the code

Random number generation

// A random integer between [0, Max)
random.nextInt(max);

// Randomly return true /false
random.nextBoolean()

// Random long integer
random.nextLong()

// Random floating point number
random.nextFloat()
random.nextDouble()
Copy the code

Pseudo random Gaussian distribution double precision number

random.nextGaussian()
Copy the code

The nextGaussian() method of the random class returns the next pseudo-random number, that is, a Gaussian(normal) distribution double value with an average value of 0.0 and standard deviation of 1.0 from the random number generator sequence

This usage scenario may be used in more professional scenarios, at least in the business development I have been exposed to, without this 😂

3. Math. Random and random

The above two can be used to generate random numbers, so in actual use, how to choose?

As can be seen from the previous description, there is no essential difference between them. The bottom layer is Random class. In the actual application process, if we hope to reproduce the scene, for example, in the scenario of winning the lottery probability test, it may be more friendly to select Random class and specify Random seeds. For simple random number generation, select Math.random and use at least one line of code

Series of blog posts:

  • Practical tip 1: String placeholder replacement -JDK version
  • Practice Tip 2: Array and list are rotated
  • Practice Tip 3: String and container transfer
  • Practical tip 4: Elegant string concatenation implementation
  • Practice tip 5: Hump and underline turn each other
  • Practice Tip 6: Special use of enumeration
  • Practice Tip 7: Sort carefully
  • Practice tip 8: Specify the initial size of the container
  • List. SubList is used incorrectly StackOverflowError
  • Practice Tip # 10: Immutable containers
  • Practice Tip 11: Array copy
  • Practice Tip 12: Number formatting
  • Practice Tip 13: Base conversion is easy
  • Practice Tip 14: Configure file Properties

II. The other

1. A gray Blog:liuyueyi.github.io/hexblog

A gray personal blog, recording all the study and work in the blog, welcome everyone to go to stroll

2. Statement

As far as the letter is not as good, the above content is purely one’s opinion, due to the limited personal ability, it is inevitable that there are omissions and mistakes, if you find bugs or have better suggestions, welcome criticism and correction, don’t hesitate to appreciate

  • Micro Blog address: Small Gray Blog
  • QQ: a gray /3302797840
  • Wechat official account: One Grey Blog