'How does numpy initialize its random seed? [duplicate]

When I use multiprocessing to create some processes, it seems that processes have the same state. How does it work?

I want each process has different state, so that the data created by numpy.random is indepenedent. One way is to use pid as seed, is there a more elegent approach?

from multiprocessing import Pool

import numpy as np
import os


def f(x):
    print(f'{os.getpid()}: {np.random.get_state()}')
    print(f'{os.getpid()}: {np.random.rand(5)}')


if __name__ == '__main__':
    with Pool(5) as p:
        p.map(f, [None] * 5)



Solution 1:[1]

Given that you are seeding from global state, you can consider using generator, that can be instantiated, rather that generating from global state.

Take a look into Generator that can be used for such purpose.

From example:

import numpy as np
rng = np.random.default_rng(12345)
rints = rng.integers(low=0, high=10, size=3)
print(rints)
-----
array([6, 2, 7])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Luka Rahne