在NumPy中获取随机数的最佳方法是什么? [英] What is the best way of getting random numbers in NumPy?

查看:73
本文介绍了在NumPy中获取随机数的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成范围为-1, 1的随机数,并希望每个均具有相同的概率被生成. IE.我不希望出现极端情况的可能性降低.最好的方法是什么?

I want to generate random numbers in the range -1, 1 and want each one to have equal probability of being generated. I.e. I don't want the extremes to be less likely to come up. What is the best way of doing this?

到目前为止,我已经使用过:

So far, I have used:

2 * numpy.random.rand() - 1

还有:

2 * numpy.random.random_sample() - 1

推荐答案

您的方法很好.一种替代方法是使用功能 numpy.random.uniform() :

Your approach is fine. An alternative is to use the function numpy.random.uniform():

>>> numpy.random.uniform(-1, 1, size=10)
array([-0.92592953, -0.6045348 , -0.52860837,  0.00321798,  0.16050848,
       -0.50421058,  0.06754615,  0.46329675, -0.40952318,  0.49804386])

关于极值的概率:如果理想情况下,连续的随机数,得到极值之一的概率将为0.由于浮点数是连续实数的离散化,实际上获得一些极端的积极可能性.这是某种形式的离散化误差,几乎可以肯定,该误差将与模拟中的其他误差相形见war.别担心!

Regarding the probability for the extremes: If it would be idealised, continuous random numbers, the probability to get one of the extremes would be 0. Since floating point numbers are a discretisation of the continuous real numbers, in realitiy there is some positive probability to get some of the extremes. This is some form of discretisation error, and it is almost certain that this error will be dwarved by other errors in your simulation. Stop worrying!

这篇关于在NumPy中获取随机数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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