I want to generate random numbers in Numpy using Multiprocessing. Using this this answer I wrote the code at the end of this message, and it seems to work. Because answer I linked to is quite old, I want to make sure that it is still correct. Numpy’s official documentation seems to say that np.random.seed
is deprecated, but I can’t seem to find good documentation about the Generator instance it recommends, and it seems more complicated.
<code>import numpy as np
from multiprocessing import Pool
def generate_random(iproc):
# if then next line is commented then each process produces same random numbers
np.random.seed()
nums = np.random.uniform(size=8)
print(f'{iproc=},{nums=}')
if __name__ == '__main__':
nproc = 8
arglist = []
for iproc in range(nproc):
arglist.append((iproc,))
with Pool(nproc) as p:
p.starmap(generate_random, arglist)
</code>
<code>import numpy as np
from multiprocessing import Pool
def generate_random(iproc):
# if then next line is commented then each process produces same random numbers
np.random.seed()
nums = np.random.uniform(size=8)
print(f'{iproc=},{nums=}')
if __name__ == '__main__':
nproc = 8
arglist = []
for iproc in range(nproc):
arglist.append((iproc,))
with Pool(nproc) as p:
p.starmap(generate_random, arglist)
</code>
import numpy as np
from multiprocessing import Pool
def generate_random(iproc):
# if then next line is commented then each process produces same random numbers
np.random.seed()
nums = np.random.uniform(size=8)
print(f'{iproc=},{nums=}')
if __name__ == '__main__':
nproc = 8
arglist = []
for iproc in range(nproc):
arglist.append((iproc,))
with Pool(nproc) as p:
p.starmap(generate_random, arglist)