You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

The C Standard function rand (available in stdlib.h) does not have good random number properties. The numbers generated by rand have a comparatively short cycle, and the numbers may be predictable.

Non-Compliant Code Example

The following code will generate predictable numbers with limited randomness.

int r;
...
r = rand();
...

Compliant Solution

A better pseudo random number generator is the BSD function random.

int r;
srandom(time(0));  // seed the PRNG with the current time
...
r = random();
...

The rand48 family of functions provides another alternative.

Note. Pseudo random number generators use mathematical algorithms to produce a sequence of numbers with good statistical properties, but the numbers produced are not genuinely random. For true randomness, Linux users can use the character devices /dev/random or /dev/urandom. (The device /dev/random may block for a long time if there are not enough events going on to generate sufficient randomness; /dev/urandom does not block.)

... not yet finished

  • No labels