Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate multiple independent random streams in python

I want to generate multiple streams of random numbers in python. I am writing a program for simulating queues system and want one stream for the inter-arrival time and another stream for the service time and so on.

numpy.random() generates random numbers from a global stream.

In matlab there is something called RandStream which enables me to create multiple streams.

Is there any way to create something like RandStream in Python

like image 680
Mina Edward Avatar asked Jun 13 '14 11:06

Mina Edward


2 Answers

For the sake of reproducibility you can pass a seed directly to random.Random() and then call variables from there. Each initiated instance would then run independently from the other. For example, if you run:

import random
rg1 = random.Random(1)
rg2 = random.Random(2)
rg3 = random.Random(1)
for i in range(5): print(rg1.random())
print('')
for i in range(5): print(rg2.random())
print('')
for i in range(5): print(rg3.random())

You'll get:

0.134364244112
0.847433736937
0.763774618977
0.255069025739
0.495435087092

0.956034271889
0.947827487059
0.0565513677268
0.0848719951589
0.835498878129

0.134364244112
0.847433736937
0.763774618977
0.255069025739
0.495435087092
like image 50
Cão Avatar answered Oct 13 '22 01:10

Cão


Both Numpy and the internal random generators have instantiatable classes.

For just random:

import random
random_generator = random.Random()
random_generator.random()
#>>> 0.9493959884174072

And for Numpy:

import numpy
random_generator = numpy.random.RandomState()
random_generator.uniform(0, 1, 10)
#>>> array([ 0.98992857,  0.83503764,  0.00337241,  0.76597264,  0.61333436,
#>>>         0.0916262 ,  0.52129459,  0.44857548,  0.86692693,  0.21150068])
like image 21
Veedrac Avatar answered Oct 13 '22 00:10

Veedrac