2

The normal distribution: std::normal_distribution<T> only accepts a real-valued type such as float or double, why doesn't it accept an integer type?

How can I create a normal integer distribution?

Taryn East
  • 27,486
  • 9
  • 86
  • 108
Moberg
  • 5,253
  • 4
  • 38
  • 54
  • Counter-question: Why would anyone need a discrete distribution if you can easily convert `double` and `float` values to `int`? – Paweł Stawarz Feb 25 '14 at 13:50
  • 2
    The normal distribution is by definition continuous. There are discrete distributions that approximate the normal distribution. – Joseph Mansfield Feb 25 '14 at 13:56
  • I guess they don't! :) – Moberg Feb 25 '14 at 13:56
  • @JosephMansfield, yeah, it's called a binomial distribution. – Z boson Feb 25 '14 at 14:01
  • Why this question was put on hold makes no sense to me. If you want an opinion based question see this one http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc. That question (and especially the answer) is equivalent to (should I use VI instead of Emacs) and yet the question and answer have about 500 votes. – Z boson Feb 25 '14 at 15:34
  • That question was asked 5 years ago. The rules were different back then. We have become more strict over time as we've discovered how the opinion-based questions cause serious detrimental effects on the quality of questions over time. – Taryn East Mar 03 '14 at 03:09
  • That said - you are now asking a specific question... so I'll nominate this question for re-opening. – Taryn East Mar 03 '14 at 03:09
  • @Moberg funny enough that Stroustrup gives an example with `normal_distribution` at http://www.stroustrup.com/C++11FAQ.html#std-random – Alessandro Jacopson Jun 22 '18 at 08:54

2 Answers2

14

I know next to nothing about C++11 but I know a little math (or I did at one point) and a discrete normal distribution is called a Binomial distribution. In fact a normal distribution is the binomial distribution when you let n go to infinity.

So assuming C++11 has a binomial distribution then you have a discrete normal distribution. Why don't you try std::binomial_distribution?

You might also want to read up on the de Moivre–Laplace theorem.

enter image description here

Z boson
  • 32,619
  • 11
  • 123
  • 226
  • 1
    And you are totally right: there is a class named [`std::binomial_distribution`](http://en.cppreference.com/w/cpp/numeric/random/binomial_distribution) in the standard library. – Morwenn Feb 25 '14 at 14:10
  • It's only symmetric for p = 1/2, although you can get away with other p-values when you have sufficiently large n. – pjs Feb 25 '14 at 14:51
  • @pjs, yes, that's why de Moivre–Laplace theorem is a special case of the central limit theorem. – Z boson Feb 25 '14 at 14:53
1

Just cast the generated random value to an integer.

std::normal_distribution<float> noise(0, 2.f);
randomValue = (int) round(noise(engine));
Moberg
  • 5,253
  • 4
  • 38
  • 54