How to use numpy.random to generate random numbers from a certain distribution?

半腔热情 提交于 2020-04-16 05:56:04

问题


I am somewhat confused about how to use numpy.random to generate random values from a give distribution, say, binomial. I thought it would be

import numpy as np
np.random.binomial(10, 0.3, 5)

However, NumPy reference page shows something like

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?


回答1:


The first block of code uses a numpy.random.* function. numpy.random.* functions (including numpy.random.binomial) make use of a global random generator object which is shared across the application.

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.

Note that numpy.random.binomial (in addition to other numpy.random.* functions) is now a legacy function as of 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. It was the result of a proposal to change the RNG policy. The desire to avoid global state was one of the reasons for the change in this policy.




回答2:


This does not work in 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



回答3:


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.



来源:https://stackoverflow.com/questions/59728162/how-to-use-numpy-random-to-generate-random-numbers-from-a-certain-distribution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!