[英]std::normal_distribution<int> runtime error “Integer division by zero”
// construct a trivial random generator engine from a time-based seed:
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator (seed);
std::normal_distribution<int> distribution (132,20);
std::cout << "some Normal-distributed results:" << std::endl;
for (int i=0; i<10; ++i)
std::cout << distribution(generator) << std::endl;
From this code example from cplusplus I get the runtime error "Integer division by zero". 从cplusplus的这个代码示例中我得到运行时错误“整数除零”。 The only thing I changed is the type of normal_distribution from
double
to int
and its mean and standard deviation. 我唯一改变的是从
double
到int
的normal_distribution类型及其均值和标准差。
Any suggetsions? 任何建议?
The template parameter to std::normal_distribution
must be a floating-point type ( float
, double
, or long double
). std::normal_distribution
的模板参数必须是浮点类型( float
, double
或long double
)。 Using anything else will result in undefined behavior. 使用其他任何东西都会导致未定义的行为。
Since normal distribution is a continuous distribution, it isn't really clear what you expect it to do when using an int
type. 由于正态分布是连续分布,因此在使用
int
类型时,您不希望它做什么。 Maybe you can get the result you want by using normal_distribution<double>
and rounding the result to int
. 也许你可以通过使用
normal_distribution<double>
并将结果舍入为int
来获得所需的结果。
You can use binomial_distribution
with default probability value of 0.5. 您可以使用
binomial_distribution
,默认概率值为0.5。 link 链接
It will return integer values in range [0,t], with mean at t/2 ( in case t is even else (t+1)/2, (t-1)/2 have equal prob.). 它将返回范围[0,t]中的整数值,平均值为t / 2(如果t为偶数(t + 1)/ 2,则(t-1)/ 2具有相等的概率)。 You can set the value of t accordingly and shift by adding a constant to the result if needed.
您可以相应地设置t的值,并根据需要在结果中添加常量来进行移位。
Binomial distribution is discrete approximation of normal distribution ( link ). 二项分布是正态分布( 链接 )的离散近似。 Normal distributions theoretically have no lower/upper limits.
正态分布理论上没有下限/上限。
I prefer to use following thin wrapper over the original: 我更喜欢使用以下的薄包装:
template <typename T>
class NormalDistribution {
private:
std::mt19937 mt;
std::normal_distribution<T> dis;
public:
NormalDistribution(T mu, T sigma):dis(mu, sigma) {
std::random_device rd;
mt.seed(rd());
}
NormalDistribution(T mu, T sigma, unsigned seed ):dis(mu, sigma) {
mt.seed(seed);
}
T random() {
return dis(mt);
}
};
template <>
class NormalDistribution<int> {
private:
std::mt19937 mt;
std::binomial_distribution<int> dis;
int _min;
public:
NormalDistribution(int min, int max):dis(max-min) {
std::random_device rd;
mt.seed(rd());
}
NormalDistribution(int min, int max, unsigned seed):dis(max-min), _min(min) {
mt.seed(seed);
}
int random() {
return dis(mt)+_min;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.