Random floats

Started by
5 comments, last by Denix Linelli 23 years, 5 months ago
How do I generate random floating-point numbers? rand() only does ints.
Advertisement
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!
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
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
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)
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.
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.
---- --- -- -

This topic is closed to new replies.

Advertisement