[英]How to use numpy.random to generate random numbers from a certain distribution?
I am somewhat confused about how to use numpy.random to generate random values from a give distribution, say, binomial.我对如何使用 numpy.random 从给定分布(例如二项式)生成随机值感到有些困惑。 I thought it would be
我以为会是
import numpy as np
np.random.binomial(10, 0.3, 5)
However, NumPy reference page shows something like但是, NumPy 参考页面显示类似
from numpy.random import default_rng
rg = default_rng()
rg.binomial(10, 0.3, 5)
Both seem to be working well.两者似乎都运行良好。 Which one is the correct or better way?
哪一个是正确的或更好的方法? What is the difference if there is any?
如果有的话有什么区别?
The first block of code uses a numpy.random.*
function.第一个代码块使用
numpy.random.*
函数。 numpy.random.*
functions (including numpy.random.binomial
) make use of a global random generator object which is shared across the application. numpy.random.*
函数(包括numpy.random.binomial
)利用一个在应用程序中共享的全局随机生成器对象。
The second block of code creates a random generator object with default_rng()
and uses that object to generate random numbers without relying on global state.第二个代码块使用
default_rng()
创建一个随机生成器对象,并使用该对象生成随机数,而不依赖于全局状态。
Note that numpy.random.binomial
(in addition to other numpy.random.*
functions) is now a legacy function as of NumPy 1.17;请注意,
numpy.random.binomial
(除了其他numpy.random.*
函数)现在是 NumPy 1.17 的遗留函数; NumPy 1.17 introduces a new random number generation system , which is demonstrated in the second block of code in your question. NumPy 1.17 引入了一个新的随机数生成系统,在您问题的第二个代码块中进行了演示。 It was the result of a proposal to change the RNG policy .
这是改变 RNG 政策的提议的结果。 The desire to avoid global state was one of the reasons for the change in this policy.
避免全局状态的愿望是更改此策略的原因之一。
This does not work in Python2.7 / numpy 1.16 :这在 Python2.7 / numpy 1.16 中不起作用:
>>> from numpy.random import default_rng
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name default_rng
import random
random.choice([2,44,55,66])
A crucial thing to understand about the random choice method is that Python doesn't care about the fundamental nature of the objects that are contained in that list.理解随机选择方法的一个关键点是 Python 并不关心包含在该列表中的对象的基本性质。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.