在 [0, n] 中生成随机

Generate random in [0, n)

本文关键字:随机      更新时间:2023-10-16

使用C++11的标准函数/类/等<random>如何在这些范围内生成随机数:

  • (nm) - 不包括两端
  • (nm] - 不包括开始
  • [nm) - 不包括结束

以及它们的特殊情况:

  • [0,n)
  • [0, 1)

或者可能有任何文档,例如<random>备忘单?

均匀实数分布

uniform_real_distribution将给出[a, b)范围内的值。我们可以使用std::nextafter在开放和封闭范围之间进行转换。

int main() {
std::random_device rd;
std::mt19937 mt(rd());
// [1, 10]
std::uniform_real_distribution<> dist_a(1, std::nextafter(10, std::numeric_limits<double>::max));
// [1, 10)
std::uniform_real_distribution<> dist_b(1, 10);
// (1, 10)
std::uniform_real_distribution<> dist_c(std::nextafter(1, std::numeric_limits<double>::max), 10);
// (1, 10]
std::uniform_real_distribution<> dist_d(std::nextafter(1, std::numeric_limits<double>::max), std::nextafter(10, std::numeric_limits<double>::max));
// Random Number Generators are used like this:
for (int i=0; i<16; ++i)
std::cout << dist_d(mt) << "n";
}

均匀国际分布

uniform_int_distribution将给出[a, b]范围内的值。我们只需加减1即可在开放和封闭范围之间切换。

int main() {
std::random_device rd;
std::mt19937 mt(rd());
// [1, 10]
std::uniform_int_distribution<> dist_a(1, 10);    
// [1, 10)
std::uniform_int_distribution<> dist_b(1, 10 - 1); 
// (1, 10)
std::uniform_int_distribution<> dist_c(1 + 1, 10 - 1); 
// (1, 10]
std::uniform_int_distribution<> dist_d(1 + 1, 10);
// Random Number Generators are used like this:
for (int i=0; i<16; ++i)
std::cout << dist_d(mt) << "n";
}