Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use the random number library of Category 11

Shulou Source: shulou.com Published: 2022-06-01 20:48:02 10月04日 Update

This article mainly explains "how to use C++11 random number library", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "how to use C++11 random number library"!

Previous random numbers

Before C++11, both C and C++ used the same method to generate random numbers. The code is roughly as follows:

Since rand() generates pseudo-random numbers, you need to seed the rand function. Different seeds produce different random number sequences. The usual way to do this is to call srand(time(0)), because time returns the system time, which varies from second to second, so the probability of generating the same random number becomes very small.

One difficulty with this approach is that it is not easy to control the range of output results. Especially if you don't want it to be evenly distributed.

Random Number Library

C++11 provides a library of random numbers, including random-number engines and random-number distributions. Both are generally used together.

random number engine

The standard library provides multiple random number engines, illustrated here with the default_random_engine class.

So far, there is no essential difference from the previous method, only the form is different. Hold on, keep looking.

random number distribution class

C++11 controls the distribution of random numbers generated by the random number engine through random number distribution classes.

Generates evenly distributed integers

The code uses uniform_int_distribution to control the random number engine to generate integers between 0 and 10.

Real numbers that generate an average distribution

The code uses uniform_real_distribution to control the random number engine to generate real numbers between 0 and 10.

Real numbers that generate normal distributions

The code uses normal_distribution to control the random number engine to generate normally distributed data with a mean of 2 and a standard deviation of 0.25.

Generating Boolean Values with Controllable Probability

Bernoulli_distribution is used in the code to control the random number engine to generate Boolean random numbers, where the probability of 1 is 0.3.

output result

At this point, I believe everyone has a deeper understanding of "how to use C++11 random number library," so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Tags: Random number generation engine control code different real number way same between content Boolean integer standard probability normal distribution seed result learning output Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker MySQL Xiaomi OPPO Reno macOS