[Previous] [Contents] [Next]

initstate()

Initialize a pseudo-random number generator

Synopsis:

#include <stdlib.h>

char* initstate( unsigned int seed,
                 char* state,
                 size_t size );

Library:

libc

Description:

The initstate() function allows a state array, pointed to by the state argument, to be initialized for future use. The size argument, which specifies the size in bytes of the state array, is used by initstate() to decide what type of random-number generator to use; the larger the state array, the more random the numbers. Values for the amount of state information are 8, 32, 64, 128, and 256 bytes. Other values greater than 8 bytes are rounded down to the nearest one of these values. For values smaller than 8, random() uses a simple linear congruential random number generator. The seed argument specifies a starting point for the random-number sequence and provides for restarting at the same point. The initstate() function returns a pointer to the previous state information array.

This function is used in conjunction with the following:

random()
Generate a pseudo-random number using a default state.
setstate()
Specify the state of the pseudo-random number generator.
srandom()
Set the seed used by the pseudo-random number generator.

If initstate() hasn't been called, random() behaves as though initstate() had been called with seed=1 and size=128.

If initstate() is called with size less than 8, random() uses a simple linear congruential random number generator.

After initialization, you can restart a state array at a different point in one of two ways:

Returns:

A pointer to the previous state array, or NULL if an error occurred.

Examples:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

static char state1[32];

int main() {
   initstate( time(NULL), state1, sizeof(state1));
   setstate(state1);
   printf("%d0\n", random());
   return EXIT_SUCCESS;
}

Classification:

Standard Unix

Safety:
Cancellation point Yes
Interrupt handler No
Signal handler No
Thread No

See also:

drand48(), rand(), random(), setstate(), srand(), srandom()


[Previous] [Contents] [Next]