English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

2006-06-13 18:35:20 · 2 answers · asked by dragongml 3 in Computers & Internet Programming & Design

2 answers

Generating a Pseudo-Random Number Sequence

#include
#include
...
long count, i;
char *keystr;
int elementlen, len;
char c;
...
/* Initial random number generator. */
srand(1);

/* Create keys using only lowercase characters */
len = 0;
for (i=0; i while (len < elementlen) {
c = (char) (rand() % 128);
if (islower(c))
keystr[len++] = c;
}

keystr[len] = '\0';
printf("%s Element%0*ld\n", keystr, elementlen, i);
len = 0;
}


Generating the Same Sequence on Different Machines

static unsigned long next = 1;
int myrand(void) /* RAND_MAX assumed to be 32767. */
{
next = next * 1103515245 + 12345;
return((unsigned)(next/65536) % 32768);
}

void mysrand(unsigned seed)
{
next = seed;
}


RATIONALE

The ISO C standard rand() and srand() functions allow per-process pseudo-random streams shared by all threads. Those two functions need not change, but there has to be mutual-exclusion that prevents interference between two threads concurrently accessing the random number generator.

With regard to rand(), there are two different behaviors that may be wanted in a multi-threaded program:

A single per-process sequence of pseudo-random numbers that is shared by all threads that call rand()

A different sequence of pseudo-random numbers for each thread that calls rand()

This is provided by the modified thread-safe function based on whether the seed value is global to the entire process or local to each thread.

This does not address the known deficiencies of the rand() function implementations, which have been approached by maintaining more state. In effect, this specifies new thread-safe forms of a deficient function.

2006-06-13 18:53:56 · answer #1 · answered by Anonymous · 0 0

rand() returns a pseudo-random integer in the range 0 to RAND_MAX, which is a number defined in the standard C GNU library. RAND_MAX is defined to be the largest int possible represented using 32 bits, in the C standard library it is 32767.
Here is a quick program to find out what your library is using:

#include
#include
using std::cout;
using std::endl;

int main()
{
cout << RAND_MAX << endl;
return 0;
}

2006-06-13 18:46:44 · answer #2 · answered by fatulerror 1 · 0 0

fedest.com, questions and answers