First time here? Check out the FAQ!

Ask Your Question
3

Random numbers in parallel calculations

asked 10 years ago

Eugene gravatar image

Assume I have a function that requires random number (noise) like:

@parallel
def foo(i):
    print np.random.random()

4 sequential runs yield desired output:

for i in range(4):
    foo(i)
0.961718217227
0.909042125122
0.736138778296
0.149902522071

But the parallel run calculates only one random value:

list(foo(range(4)))
0.633760965726
0.633760965726
0.633760965726
0.633760965726
[(((0),{}),None),(((2),{}),None),(((1),{}),None),(((3),{}),None)]

How do I properly generate random values from within parallel function?

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
3

answered 10 years ago

tmonteil gravatar image

updated 10 years ago

This is because numpy uses the same random seed that was computed before (and given in each subprocess). You can reset the seed in each process, so that they will behave independently:

sage: @parallel
....: def foo(i):
....:     np.random.seed()
....:     print np.random.random()
sage: list(foo(range(4)))       
0.0290924047484
0.491286471752
0.0812252231074
0.055948998056
[(((0,), {}), None),
 (((1,), {}), None),
 (((2,), {}), None),
 (((3,), {}), None)]
Preview: (hide)
link

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 10 years ago

Seen: 1,197 times

Last updated: Mar 06 '15