generating random floats in C++

Special K

Diamond Member
Jun 18, 2000
7,098
0
76
How can I use the rand() function to generate random floating point numbers in some arbitrary range, for example [-1,1]? I have searched but all the guides I can find are for integers only and I can't seem to get a range of random floats from that.
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
If the int rand function gives an equal distribution between MIN_INT and MAX_INT, you could scale it down to the range [-1,1]
 

tfinch2

Lifer
Feb 3, 2004
22,114
1
0
Not sure if there is a sure fire way to do it, but you can do this:

Generate two long ints and another to either a zero or 1, cast them to floats then divide, use the 0 or 1 to determine if it's negative or positive:

Example
x = 56453
y = 96213 (y must always be greater than x to keep it between 0 and 1)
z = 0
x/y = .58675023...

rand num = -.58675023...
 

LintMan

Senior member
Apr 19, 2001
474
0
71
Normalize the random int to be from [0,1], then scale/offset it:
int r = rand();
float fn = ((float)r/RAND_MAX); // fn should now be [0,1]
float fr = 2*(fn-0.5); // offset fn to be [-0.5,0.5], scale to [-1,1]

Note that some implementations of rand() stink. Beware if RAND_MAX is something 16-bit tiny like 32767 or 65535. Tiny max rand values like that mean that you'll only get 32767 or 65535 different possible random numbers despite generating a float end result. That may seem like a lot of values, but it's nothing if you're generating millions of values (say for a 1280x1024 random terrain).

You can also find free high quality random number generator source code, which likely would provide int, float, and double versions. I've used the Mersenne Twister rng with excellent results:
http://en.wikipedia.org/wiki/Mersenne_twister
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html