Cha*_*amé 6 c++ random normal-distribution c++11
我需要生成遵循正态分布的随机数,该随机数应位于 1000 和 11000 的区间内,平均值为 7000。我想使用c++11 库函数,但我不明白如何生成间隔。有人可以帮忙吗?
您没有指定标准差。假设给定间隔的标准差为 2000,您可以尝试以下操作:
#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;
}
Run Code Online (Sandbox Code Playgroud)
可能的输出:
4520.53
6185.06
10224
7799.54
9765.6
7104.64
5191.71
10741.3
3679.14
5623.84
Run Code Online (Sandbox Code Playgroud)
如果您只想指定min
和max
值,那么我们可以假设平均值为(min + max) / 2
。我们还可以假设 和min
与max
平均值相差 3 个标准差。通过这些设置,我们将仅丢弃 0.3% 的生成值。所以你可以添加以下构造函数:
Generator(double min, double max):
distribution((min + max) / 2, (max - min) / 6), min(min), max(max)
{}
Run Code Online (Sandbox Code Playgroud)
并将生成器初始化为:
Generator g(1000.0, 11000.0);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14993 次 |
最近记录: |