How do I generate random floats in C++?
I thought I could take the integer rand and divide it by something, would that be adequate enough?
On some systems (Windows with VC springs to mind, currently), RAND_MAX
is ridiculously small, i. e. only 15 bit. When dividing by RAND_MAX
you are only generating a mantissa of 15 bit instead of the 23 possible bits. This may or may not be a problem for you, but you're missing out some values in that case.
Oh, just noticed that there was already a comment for that problem. Anyway, here's some code that might solve this for you:
float r = (float)((rand() << 15 + rand()) & ((1 << 24) - 1)) / (1 << 24);
Untested, but might work :-)