[英]Using std::random_device can I set a range of floating point numbers but not include certain numbers?
As mentioned in the title I want to generate a random floating-point number between -10 and 10 but I want to make it so that it can't generate a number between -1.99 and 1.99.正如标题中提到的,我想生成一个介于 -10 和 10 之间的随机浮点数,但我想让它不能生成介于 -1.99 和 1.99 之间的数字。
My code for randomly generating numbers:我的随机生成数字的代码:
std::random_device random;
std::mt19937 gen(random());
std::uniform_real_distribution<float> dis(-10.0f, 10.0f);
for (int n = 0; n < 10; ++n)
{
std::cout << dis(gen); << std::endl;
}
you can use std::piecewise_constant_distribution
:您可以使用
std::piecewise_constant_distribution
:
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
// 50% of the time, generate a random number between -10.0f and -1.99f
// 50% of the time, generate a random number between 1.99f and 10.0f
std::vector<float> i{-10.0f, -1.99f, 1.99, 10.0f};
std::vector<float> w{1, 0, 1};
std::piecewise_constant_distribution<float> dis(i.begin(), i.end(), w.begin());
for (int n = 0; n < 10; ++n)
std::cout << dis(gen) << std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.