This is actually an interesting question.
First, you can potentially get the same result from consecutive calls to time.time()
but mainly due to precision.
In [36]: a=time.time(); b=time.time()
In [37]: b-a
Out[37]: 0.0
Now let's jump into the questions:
- It does not produce the same output because of how the initial seed is generated. If you look at the random.py source code for
seed()
you'll see it specifies
def seed(self, a=None, version=2):
"""Initialize internal state from a seed.
The only supported seed types are None, int, float,
str, bytes, and bytearray.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
Because there is no reference to time.time()
you can't assume it uses it. In fact, you can look at the source for the CPython implementation (if you understand C). One of the ways it helps guarantee a random seed if necessary is this:
static void
random_seed_time_pid(RandomObject *self)
{
_PyTime_t now;
uint32_t key[5];
now = _PyTime_GetSystemClock();
key[0] = (uint32_t)(now & 0xffffffffU);
key[1] = (uint32_t)(now >> 32);
key[2] = (uint32_t)getpid();
now = _PyTime_GetMonotonicClock();
key[3] = (uint32_t)(now & 0xffffffffU);
key[4] = (uint32_t)(now >> 32);
init_by_array(self, key, Py_ARRAY_LENGTH(key));
}
There are multiple calls to different clocks AND a process ID. Nothing about time.time()
. And because of how the seed is generated there, it's pretty impossible for two consecutive seeds to be the same.
- If you want something to produce the same output, you need to seed it the same.
In [42]: import random
In [43]: a = time.time()
In [44]: random.seed(a)
In [45]: random.randrange(100)
Out[45]: 98
In [46]: random.randrange(100)
Out[46]: 94
In [47]: random.seed(a) # Reset
In [48]: random.randrange(100)
Out[48]: 98
It doesn't need to be a number, though. You can seed with a lot of different options.
- Hopefully the source code provided above address that.