gpt4 book ai didi

c++ - 在 [0, n) 中生成随机数

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:25:49 24 4
gpt4 key购买 nike

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

  • (n, m) - 不包括两端
  • (n, m] - 不包括开头
  • [n, m) - 不包括结尾

以及它们的特例:

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

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

最佳答案

Uniform Real Distribution

A 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 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";
}

关于c++ - 在 [0, n) 中生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30103792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com