#include <iostream>
#include <random>
#include <vector>
std::normal_distribution<double> norm_double_dist_0_9{4.5 /*mean*/,
2.0 /* sd */};
std::default_random_engine random_engine{};
const int NbrOfBins = 10;
const int NbrOfSamples = 100;
int main()
{
std::vector<int> histogram(NbrOfBins);
int sampleValue;
for (int sample = 0; sample < NbrOfSamples; ++sample)
{
sampleValue = (int)norm_double_dist_0_9(random_engine);
if (sampleValue < 0) sampleValue = 0;
if (sampleValue > 9) sampleValue = 9;
++histogram[sampleValue];
}
for (int bin = 0; bin < NbrOfBins; ++bin)
{
std::cout << histogram[bin] << std::endl;
}
return 0;
}
/* Output:
8
6
8
15
19
18
14
8
3
1
*/
Reference: https://isocpp.org/wiki/faq/cpp11-library#std-random
Friday, September 1, 2017
C++11: Random Numbers: Normal Distribution
You can easily create normally distributed numbers. Here is an example:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment