Steve2Fish
Steve2Fish

Reputation: 187

Python - randomint() should be equal to C - rand()

I have the following C - Program:

#include <stdio.h>
#include <time.h>
int main(int argc, char *argv[]){
    srand(time(NULL));
    printf("%d", rand());
}

And this Python script:

import random
import time
random.seed(int(time.time()))
print (random.randint(0, 2147483647))

RAND_MAX in the C-program is defined as 2147483647. If I start both programs in the same second, they should print the same "random" number but this is not the case?

Any ideas why? Are there different methods implemented to get a pseudo-random number? The seed is definitely the same.

Upvotes: 0

Views: 6407

Answers (2)

The random number generator of C is not standardized at all. The C11 standard revision notes in the footnote 295 that

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.

Python is one of those applications: Python chose to use the MT19937-32 random number generator, a.k.a. Mersenne Twister. It is very unlikely that a C library would use MT19937-32 for the rand implementation, and with the same seeding routine.

Upvotes: 7

klutt
klutt

Reputation: 31409

The only thing they guarantee is that you will get a pseudo random number. You have basically no guarantees of how it will work.

Even if you compile the same C program on two different compilers, you're not guaranteed the exact same result when calling rand().

You are basically wondering why you don't get the same result when rolling two different dice even if you roll them the exact same way. Well, they are different, and so is the result.

Upvotes: 3

Related Questions