I recently wrote some code that required a large number of draws from a gamma distribution. I implemented this using the standard gamma_distribution method, but am finding that occasionally (once in a blue moon) this returns a value of 1.#INF for no apparent reason.
Below is a minimal example that I find exhibits this problem. In my tests I have found that the problem usually occurs around the billionth iteration or so.
#include "stdafx.h"
#include <iostream>
#include <random>
std::random_device rd;
std::default_random_engine generator(rd());
int _tmain(int argc, _TCHAR* argv[])
{
// create gamma distribution and random variable x
std::gamma_distribution<double> rgamma(2.0,1.0);
double x;
// loop through a large number of iterations
for (unsigned long int i=0; i<int(4e9); i++) {
// print update to console every million iterations
if ((i+1)%int(1e6)==0)
std::cout << "iteration: " << (i+1)/1e6 << " million\n";
// draw new value of x from gamma distribution
x = rgamma(generator);
// if x==infinity then break
if ((1.0/x)==0) {
std::cout << "Error at iteration " << (i+1) << ": x=" << x << "\n";
std::cin.get();
exit(1);
}
}
// print message if reach end of loop
std::cout << "end\n";
std::cin.get();
return 0;
}
I'd be very interested to know if others can replicate this problem. I don't know it this is relevant, but the program above was written as a Win32 application in Visual Studio 2010 and run on a Windows machine with 8 core Intel processor.
For the time being I've patched over this problem by just catching infinite values and making them large numbers instead. But if anyone has any insight into why/how this is occurring it would be greatly appreciated!