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

冷暖自知 提交于 2021-02-10 06:10:31

问题


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?


回答1:


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:

  • Should I use std::default_random_engine or should I use std::mt19937?
  • Is a Mersenne-twister cryptographically secure if I truncate the output?



回答2:


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).



来源:https://stackoverflow.com/questions/64532780/c-how-to-stop-a-random-engine-from-producing-negative-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!