Skip to main content
gamedev.net
🔒 Locked

Random floats

Started by Denix Linelli Nov 4, 2000 at 2:31 PM 5 replies 1.2k views
Original Post
Denix Linelli
Denix Linelli
How do I generate random floating-point numbers? rand() only does ints.
BeamMeUp
BeamMeUp
That''s a complex solution - I''d never even considered it before. I''d always used rand () * x / RAND_MAX, where x is a float or double, and is the upper limit. RAND_MAX is a constant that defines the maximum number returned from rand (), and I think it''s contained in stdlib.h.

The post above mine is probably faster, but this method is easier to understand.

-----------

C++ is the language of the not-so-ancients.
Learn to speak it well.


BeamMeUp
-----------C++ is the language of the not-so-ancients.Learn to speak it well.BeamMeUp
Mezz
Mezz
You can do the following:

x = ((float)rand()) / RAND_MAX) * rand();

if that takes your fancy.
Or, use anon''s above - it''s probably faster.

-Mezz
D
D
Hrm, from another previous post I have heard that rand() uses a multiplication and an addition to generate the random number like so:

rand = (largeprimenumber) * (seed / current randvalue) + (prime number)...

perhaps you could create your own random floating point number generator somehow?

Dæmin
(Dominik Grabiec)
sdgrab@eisa.net.au
Daemin(Dominik Grabiec)
Denix Linelli
Denix Linelli
I looked this up from the sourcecode:

return(((holdrand = holdrand * 214013L + 2531011L) >> 16) & 0x7fff);

holdrand is the seed or the last number generated. I wonder why its shifted and ANDed? Is this thing intentionally clamped to a short or something?

I''ll have to experiment with it.
mossmoss
mossmoss
quote:
Original post by Denix Linelli

How do I generate random floating-point numbers? rand() only does ints.



Nifty neato floating-point random number function coming right up:

    
float random(float low, float high)
{
return (low + (high - low) * (rand() / float(RAND_MAX)));
}


Keep in mind that any compiler that''s not brain-dead will optimize things for you. Since RAND_MAX is a literal, the conversion to floatint-point and the division will be optimized to a simple multiplication. There is one slow bit (converting rand()''s result to a float) but otherwise it''s a simple and fast solution.



---- --- -- -
Blue programmer needs food badly. Blue programmer is about to die!
---- --- -- -
New York. New York. New York. Texas. Texas. New York. New York. Canada.
---- --- -- -

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.