在 [0, n] 中生成随机
Generate random in [0, n)
本文关键字:随机 更新时间:2023-10-16
使用C++11的标准函数/类/等<random>
如何在这些范围内生成随机数:
- (n,m) - 不包括两端
- (n,m] - 不包括开始
- [n,m) - 不包括结束
以及它们的特殊情况:
- [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";
}
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么 Serial.println(<char[]>);返回随机字符?
- 字符串-C++后显示的随机字符
- 循环中的随机函数
- 在c++构造函数中使用随机字符串生成器
- 使用std::mt19937从字符串中返回一个随机单词
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- 如何在C++中高效地构造随机骰子
- 在类中使用随机生成器时出现性能问题
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 将字符随机转换为大写的函数
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 如何生成一个随机的 n 位数,其中 n 是任意的
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 如何使用要传递给 mt19937 的可选随机种子参数设计函数
- 在C++中随机生成 20 个非重复数字
- GCC:随机构建导致执行期间分段错误
- 如何使用 SML 随机生成八进制元组
- 当我尝试使用它时,Scanf 会抛出一个随机异常(scanf_s 也是如此)
- 将正态随机变量与任意 RHO(corrcoef) 相关联