codekiddy
codekiddy

Reputation: 6137

Normal distribution of random numbers hangs the program?

When I run this code is just hangs in for loop, can you explan why?

#include<iostream>
#include<random>
#include<ctime>

int main()
{
    using std::cout;
    using std::endl;
    using std::cin;
    using std::mt19937;
    using std::minstd_rand;
    using std::uniform_int;
    using std::normal_distribution;

    // engines
    mt19937 rng;
    minstd_rand gen;

    // distributions
    uniform_int<int> dist(0, 37);
    normal_distribution<short> norm(4, 3);

    // initializaiton
    rng.seed(static_cast<unsigned int>(time(false)));
    gen.seed(static_cast<unsigned short>(time(false)));



    // generate numbers
    for(int i = 0; i < 10; ++i)
        std::cout << dist(rng) << "     " << norm(gen) << endl; // This is as far as this code goes

    cin.get();
    return 0;
}

Upvotes: 3

Views: 1635

Answers (3)

Jive Dadson
Jive Dadson

Reputation: 17036

I think I can guess. You are supposed to give the normal-distribution generator an engine that produces floating point numbers in the range 0..1. Instead, it is mistakenly being fed a diet of integers. A common algorithm for the normal distribution consumes those numbers in pairs, and loops until it finds a pair which, considered as point in 2-space, has a Cartesian norm that is less than one and not equal to zero. Since the algorithm is being fed nothing but integers, that never happens. But it never gives up.

Upvotes: 0

James Custer
James Custer

Reputation: 847

std::uniform_int is not C++11. You should use std::uniform_int_distribution. And std::normal_distribution<T> requires T to be floating point type (C++11 standard 26.5.8.5.1).

In fact, if you have gcc >= 4.5 you should get an error saying something like:

/opt/local/include/gcc47/c++/bits/random.h: In instantiation of 'class std::normal_distribution<short int>':
my_random.cpp:21:36:   required from here
/opt/local/include/gcc47/c++/bits/random.h:1982:7: error: static assertion failed: template argument not a floating point type

Upvotes: 6

dwurf
dwurf

Reputation: 12769

It works for me.

These functions could be trying to source random data from /dev/random, which blocks if no high-quality random data is available. I've noticed this is quite common on cheap VPS hosting providers.

Edit: Perhaps it will help if we share details of our dev environments. Works for me on:

  • Ubuntu 10.10
  • g++ 4.4.5
  • boost 1.40
  • compiled with g++ main.cpp -std=c++0x -o tst

Upvotes: 0

Related Questions