如何使用numpy.random从某个分布生成随机数? [英] How to use numpy.random to generate random numbers from a certain distribution?

查看:400
本文介绍了如何使用numpy.random从某个分布生成随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于如何使用numpy.random从给定分布(例如二项式)中生成随机值,我有些困惑.我以为会

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)

但是, 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?

推荐答案

第一段代码使用numpy.random.*函数. numpy.random.*函数(包括numpy.random.binomial)利用了在应用程序之间共享的全局随机生成器对象.

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.

第二个代码块使用default_rng()创建一个随机生成器对象,并使用该对象生成随机数,而无需依赖全局状态.

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.

请注意,从NumPy 1.17开始,numpy.random.binomial(除了其他numpy.random.*函数之外)现在是旧版函数; NumPy 1.17引入了新的随机数生成系统,该方法将在第二篇中进行演示您问题中的代码块.这是建议更改RNG政策.避开全球国家的愿望是这一政策改变的原因之一.

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.

这篇关于如何使用numpy.random从某个分布生成随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆