Discussion:
[Clanlib-devel] Random Number Generator
Ben Chambers
2006-12-20 22:16:01 UTC
Permalink
This patch implements a PRNG for ClanLib.

Multiple independent and unique RN streams may be created by instancing
the class. Personally, I use this feature for procedural content
generation, where you want the random placement to remain static across
multiple executions despite other uses of the PRNG.

I feel that this is an essential component for a game engine, which
unfortunately few people pay attention to, but which would benefit
ClanLib and its users immensely.

Class use is simple:

CL_Random r( SEED );

will instantiate the class, using a 32bit integer seed (it is possible
to implement this with 64bit integers, but I didn't bother).


unsigned int x=r.rand();

will assign a random value to x in the range of 0x0 .. 0xffffffff (any
32bit unsigned integer value). In addition to this, however, it has
several other functions which are useful for random generation:

even() returns either true or false, with a good distribution between
the two.
normalized() returns a float in the range of 0..1 inclusive, with an
even distribution.
ranged(min, max) returns a float in the range of min..max with an even
distribution.

distributed(mean, deviation) is special :) It returns potentially any
float value. Approximately 50% of all the values return lie within 1
deviation from the mean (note: This is NOT a Standard Deviation, and the
resulting curve is NOT a normal bell curve!). Approximately 75% of all
values lie within 2 deviations from the mean. If you want to know what
percentage P of all values will lie within X deviations from the mean,
it is:

P = 1-1/(2^x)

I don't know a better way to explain this; if someone comes up with one,
I'd appreciate hearing how they put it!

And that's just about it :) The code is not yet thread-safe; if you
will be accessing the same instance from multiple threads, it needs to
be wrapped in a mutex. However, independent instances may be used in
independent threads quite safely.

...Chambers

Loading...