Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the sequence of random numbers generated by rand, in C, guaranteed to always be the same, for the same seed? [duplicate]

Tags:

c

random

I was just wondering if the rand (http://www.cplusplus.com/reference/cstdlib/rand/) function will generate the same sequence of random numbers, while using the same seed, when run on different libc implementations, and even different compilers and operating systems (win, linux).

I did some tests using various compilers( g++4.8, g++5.1 and clang) and it seems that the answer is yes, however I did not find any "official" mention of the PRNG algorithm used in the C's random number generation (http://pubs.opengroup.org/onlinepubs/009604599/functions/rand.html), or whether these should be mentioned in the standards ...

like image 870
Ferenc Deak Avatar asked May 23 '16 11:05

Ferenc Deak


People also ask

Does rand function generate same value?

The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.

Why is rand () giving me the same number?

Code. In the code below, the rand() function is used without seeding. Therefore, every time you press the run button, ​it generates the same number.

What does rand () generate in C?

In the C programming language, the rand() function is a library function that generates the random number in the range [0, RAND_MAX]. When we use the rand() function in a program, we need to implement the stdlib. h header file because rand() function is defined in the stdlib header file.

How do rands generate random numbers?

Thus using the two functions, rand () and srand () we can generate random numbers in C++. The function srand () is used to provide seed for generating random numbers while rand () function generates the next random number in the sequence.


1 Answers

There is no guarantee in the standard about what will be generated:

From the standard:

There are no guarantees as to the quality of the random sequence produced and some implementations are known to produce sequences with distressingly non-random low-order bits. Applications with particular requirements should use a generator that is known to be sufficient for their needs.

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

like image 147
Serve Laurijssen Avatar answered Oct 13 '22 11:10

Serve Laurijssen