DuckQueen -4 years ago 205

C++ Question

I have a simple code sample:

`#include <iostream>`

#include <random>

using namespace std;

int main() {

minstd_rand0 gen(1);

uniform_real_distribution<double> dist(0.0, 1.0);

for(int i = 0; i < 10; ++i) {

cout << "1 " << dist(gen) << endl;

}

normal_distribution<double> dist2(0.0, 1.0);

minstd_rand0 gen2(1);

for(int i = 0; i < 10; ++i) {

cout << "2 " << dist2(gen2) << endl;

}

return 0;

}

Which I compile on gcc and msvc. I get diferent results on std code!(

So why GCC and MSVC

`std::normal_distribution`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

It's problematic, but the standard unfortunately does not specify in detail what algorithm to use when constructing (many) of the randomly distributed numbers, and there are several valid alternatives, with different benefits.

26.6.8.5 Normal distributions [rand.dist.norm] 26.6.8.5.1 Class template normal_distribution [rand.dist.norm.normal]

A normal_distribution random number distribution produces random numbers x distributed according to the probability density function

parameters μ and are also known as this distribution’s mean and standard deviation .

The most common algorithm for generating normally distributed numbers is *Box-Muller*, but even with that algorithm there are options and variations.

The freedom is even explicitly mentioned in the standard:

26.6.8 Random number distribution class templates [rand.dist] . . .

3 The algorithms for producing each of the specified distributions are implementation-defined.

A goto options for this is boost random

By the way, as @Hurkyl points out: It seems that the two implementations are actually the same: For example box-muller generates pairs of values, of which one is returned and once is cached. The two implementations differ only in which of the values is returned.

Further, the random number *engines* are completely specified and will give the same sequence between implementations, but care does need to be taken since the different *distributions* can also *consume* different amounts of random data in order to produce their results, which will put the engines out of sync.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**

Latest added