#### Archived

This topic is now archived and is closed to further replies.

# Random floats

This topic is 6441 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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

##### Share on other sites
Well, apart from writing your own random number generator a simple way is to use rand() and convert it to a float.

Or if you want a random number between 0 and 1 a simple way would be:

fRandom = float( rand() & 0x0FFF ) / 0x0FFF;

Of course you can use any number you want and you don''t need to AND the result, you could use mod or whatever takes your fancy.
(Note I''m using a c++ cast there, swap it for a c one if thats your thing )

Hope that helps some...

n!

##### Share on other sites
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

##### Share on other sites
You can do the following:

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

Or, use anon''s above - it''s probably faster.

-Mezz

##### Share on other sites
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

##### Share on other sites
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.

##### Share on other sites
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.

---- --- -- -
---- --- -- -
New York. New York. New York. Texas. Texas. New York. New York. Canada.
---- --- -- -

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 14
• 13
• 9
• 12
• 9
• ### Forum Statistics

• Total Topics
631438
• Total Posts
3000073
×