简体   繁体   中英

C++ how to stop a random engine from producing negative numbers?

I have a function that im trying to produce random numbers between 18 and 5

int randomAge() {
  int random;
  std::random_device rd;
  static std::default_random_engine generator(rd()); //produce a static random engine
  std::normal_distribution<double> distribution(18, 52);  //random age between 18 and 52
  random = distribution(generator);
  return random;
}

However I am recieving negative numbers and even numbers that are higher than 52. How can I fix this so it produces numbers between 18 and 52?

You're using std::normal_distribution which generates random numbers according to the Normal (or Gaussian) random number distribution. You're using this constructor:

explicit normal_distribution( RealType mean, RealType stddev = 1.0 );

What you want is std::uniform_real_distribution . See the reference :

Produces random floating-point values i, uniformly distributed on the interval [a, b)

Do note that your engine and distribution must be thread_local (or static ) and the random device can be a temporary. Otherwise your results are not uniformly distributed. You should also consider getting a random integer instead of double since the return type is int anyway:

#include <random>

int randomAge() {
  thread_local std::mt19937 engine{ std::random_device{}() };
  thread_local std::uniform_int_distribution<int> distribution{ 18, 52 };
  return distribution(engine);
}

Related:

std::normal_distribution<T>(mean,sd) (<-clickable link) produces a normal distribution (<-clickable link) with a mean (middle point) of mean and a standard deviation ('spread') of sd .

If you want a uniform spread between two numbers, you need to use a std::uniform_real_distribution (<-clickable link).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM