[ Previous | Next | Contents | Glossary | Home | Search ]
AIX Version 4.3 Base Operating System and Extensions Technical Reference, Volume 2

rand or srand Subroutine

Purpose

Generates pseudo-random numbers.

Library

Standard C Library (libc.a)

Syntax

#include <stdlib.h> 
int rand
void srand (Seed)
unsigned int Seed;

Description

Attention: Do not use the rand subroutine in a multithreaded environment. See the multithread alternative in the rand_r subroutine article.

The rand subroutine generates a pseudo-random number using a multiplicative congruential algorithm. The random-number generator has a period of 2**32, and it returns successive pseudo-random numbers in the range from 0 through (2**15) -1.

The srand subroutine resets the random-number generator to a new starting point. It uses the Seed parameter as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to the rand subroutine. If you then call the srand subroutine with the same seed value, the rand subroutine repeats the sequence of pseudo-random numbers. When you call the rand subroutine before making any calls to the srand subroutine, it generates the same sequence of numbers that it would if you first called the srand subroutine with a seed value of 1.

Note: The rand subroutine is a simple random-number generator. Its spectral properties, a mathematical measurement of randomness, are somewhat limited. See the drand48 subroutine or the random subroutine for more elaborate random-number generators that have greater spectral properties.

Parameter

Seed Specifies an initial seed value.

Return Values

Upon successful completion, the rand subroutine returns the next random number in sequence. The srand subroutine returns no value.

There are better random number generators, as noted above; however, the rand and srand subroutines are the interfaces defined for the ANSI C library.

Example

The following functions define the semantics of the rand and srand subroutines, and are included here to facilitate porting applications from different implementations:

static unsigned int next = 1;
int rand( )
{
next = next 
*
 1103515245 + 12345;
return ((next >>16) & 32767);
}
void srand (Seed)


unsigned 
int Seed;
{
next = Seed;
}

Implementation Specifics

These subroutines are part of Base Operating System (BOS) Runtime.

Related Information

The drand48, erand48, lrand48, nrand48, mrand48, jrand48, srand48, seed48, or lcong48 subroutine, random, srandom, initstate, or setstate subroutine.

Subroutines Overview in AIX Version 4.3 General Programming Concepts: Writing and Debugging Programs.


[ Previous | Next | Contents | Glossary | Home | Search ]