C ++-根据范围内的正态分布生成随机数 [英] C++ - generate random numbers following normal distribution within range
问题描述
我需要生成一个服从正态分布的随机数,该随机数应介于1000和11000之间,平均值为7000.我想使用
I need to generate random numbers that follow a normal distribution which should lie within the interval of 1000 and 11000 with a mean of 7000. I want to use the c++11 library function but I am not understanding how to generate the numbers within the interval. Can someone help?
推荐答案
您未指定标准差.假设给定间隔的标准偏差为2000,您可以尝试以下操作:
You don't specify the standard deviation. Assuming a standard deviation of 2000 for the given interval you can try this:
#include <iostream>
#include <random>
class Generator {
std::default_random_engine generator;
std::normal_distribution<double> distribution;
double min;
double max;
public:
Generator(double mean, double stddev, double min, double max):
distribution(mean, stddev), min(min), max(max)
{}
double operator ()() {
while (true) {
double number = this->distribution(generator);
if (number >= this->min && number <= this->max)
return number;
}
}
};
int main() {
Generator g(7000.0, 2000.0, 1000.0, 11000.0);
for (int i = 0; i < 10; i++)
std::cout << g() << std::endl;
}
可能的输出:
4520.53
6185.06
10224
7799.54
9765.6
7104.64
5191.71
10741.3
3679.14
5623.84
如果只想指定min
和max
值,那么我们可以假设平均值为(min + max) / 2
.我们还可以假设min
和max
与平均值相差3个标准差.使用这些设置,我们将只丢弃生成值的0.3%.因此,您可以添加以下构造函数:
If you want to specify only the min
and max
values, then we can assume that the mean value is (min + max) / 2
. Also we can assume that min
and max
are 3 standard deviations away from the mean value. With these settings we are going to throw away only 0.3% of the generated values. So you can add the following constructor:
Generator(double min, double max):
distribution((min + max) / 2, (max - min) / 6), min(min), max(max)
{}
并将生成器初始化为:
Generator g(1000.0, 11000.0);
这篇关于C ++-根据范围内的正态分布生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!