Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

python - What is the difference between numpy.random's Generator class and np.random methods?

I have been using numpy's random functionality for a while, by calling methods such as np.random.choice() or np.random.randint() etc. I just now found about the ability to create a default_rng object, or other Generator objects:

from numpy.random import default_rng
gen = default_rng()
random_number = gen.integers(10)

So far I would have always used

np.random.randint(10)

instead, and I am wondering what the difference between both ways is.

The only benefit I can think of would be keeping track of multiple seeds, or wanting to use specific PRNGs, but maybe there are also differences for a more generic use-case?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

numpy.random.* functions (including numpy.random.binomial) make use of a global pseudorandom number generator (PRNG) object which is shared across the application. On the other hand, default_rng() is a self-contained Generator object that doesn't rely on global state.

If you don't care about reproducible "randomness" in your application, these two approaches are equivalent for the time being. Although NumPy's new RNG policy discourages the use of global state in general, it did not deprecate any numpy.random.* functions in version 1.17, although a future version of NumPy might.

Note also that because numpy.random.* functions rely on a global PRNG object that isn't thread-safe, these functions can cause race conditions if your application uses multiple threads. (Generator objects are not thread-safe, either, but there are ways to generate pseudorandom numbers via multithreading, without the need to share PRNG objects across threads.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...