How do I create a random number of some distribution in Visual C++?

I haven't found any clear and concise information on this specific topic, so I'd like to ask this relatively simple question for myself and anyone else who comes across this.

Using Visual C++, how would I create a random number with a, say, normal distribution?

There is a seemingly thorough discussion of this here:

http://www.codeguru.com/forum/showthread.php?t=378879

although I'd like to make use of the avaiable VC++ classes. These are described here:

http://msdn.microsoft.com/en-us/library/bb982398.aspx

but I don't understand the lingo and would really appreicate instructions on how to generate a random, normally distributed number in a thread-safe manner.

Thanks in advance :)
Last edited on
Just use normal_distribution (it's not just VC++, it's a standard C++ class). It takes a mean (default 0.0) and a standard deviation (default 1.0) as arguments:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <random>
int main()
{
    std::random_device rd;
    std::mt19937 eng(rd());
    std::normal_distribution<> dist(0.0, 3.0);

    for(int n=0; n<20; ++n)
       std::cout << dist(eng) << ' ';
}
demo: http://ideone.com/b3C0V
So for thread safety I'd need an instance of random_device, mt19937 and normal_distribution<> for each thread?
That is one possibility. This would give normally distributed random values for each thread.

If the requirement is for normally distributed random values across all threads in the program, create just one instance of the engine and protect it with mutual exclusion. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <random>
#include <mutex>

double rand_val()
{
    static std::random_device rd;
    static std::mt19937 eng(rd());
    static std::normal_distribution<> dist( 0.0, 3.0 ) ;
    static std::mutex mutex ;

    std::lock_guard<std::mutex> lock ;
    return dist(eng) ;
}


It is highly recommended that you use rand_s() Microsoft extension function which is thread-safe (internally calls RtlGenRandom API and is available on windows xp or higher).
Highly recommended by whom? The existing answer directly addresses the OP's requirements, whereas rand_s() isn't even a standard function. That, and it is a terribly simple RNG, with a pseudo-random distribution.
Thanks :)

RE rand_s(); I have it on good authority that the Visual C++ variant of the rand() function is itself already thread safe, so using rand_s() in VC++ isn't necessary. I've been using rand() for generating random integers in multiple threads without any issues.
Last edited on
Topic archived. No new replies allowed.