How can I get a random float value from /dev/urandom?
If I simply use a cast, by saying:
int fd = ::open("/dev/urandom", O_RDONLY);
uint32_t n;
read(fd, &n, sizeof(n));
float f = n;
…I’m not sure if I have a guarantee of portability, because I don’t know if large values of n will necessarily be representable as f? Is MAXUINT guaranteed to be representable as a float?
You get random bytes from /dev/urandom, but those bytes won’t necessarily form a) uniformly distributed floating point values or b) even legal representations of whatever object you treat them as. For example on a platform that has trapping representations of floats or ints then there’ll be the possibility that the values you create will be trapping representations, and you won’t be able to actually use the random values you create.
You should simply verify that your library’s implementation of
std::random_device()allows access to /dev/urandom (either by default or by taking a string argument like:std::random_device("/dev/urandom"). Then you have a random number engine that can be used with, for example,std::uniform_real_distribution<float>()in order to get the random number distribution you want.✓ libstdc++ uses /dev/urandom by default:
✓ libc++ does as well:
✗ Visual Studio’s implementation is not even using a non-deterministic RNG:✓ As of VS2012 MSDN states “the values produced by default are non-deterministic and cryptographically secure,” probably via Windows’ Cryptographic Services.