我还没能找到一个函数来生成一个在某个范围内给定长度的随机浮点数组。
我看过Random sampling,但似乎没有一个函数能满足我的需求。
random.uniform很接近,但它只返回一个元素,而不是一个特定的数字。
这就是我想要的:
ran_floats = some_function(low=0.5, high=13.3, size=50)
这将返回均匀分布在范围[0.5, 13.3]
中的50个随机非唯一浮点数(即,允许重复)的数组。
有这样的函数吗?
发布于 2014-02-27 22:57:06
为什么不使用列表理解呢?
在Python 2中
ran_floats = [random.uniform(low,high) for _ in xrange(size)]
在Python3中,range
的工作方式类似于xrange
(ref)
ran_floats = [random.uniform(low,high) for _ in range(size)]
发布于 2018-08-19 09:48:28
或者,您可以使用SciPy
from scipy import stats
stats.uniform(0.5, 13.3).rvs(50)
对于采样整数的记录,它是
stats.randint(10, 20).rvs(50)
发布于 2014-02-27 22:58:24
为什么不把random.uniform和列表理解结合起来呢?
>>> def random_floats(low, high, size):
... return [random.uniform(low, high) for _ in xrange(size)]
...
>>> random_floats(0.5, 2.8, 5)
[2.366910411506704, 1.878800401620107, 1.0145196974227986, 2.332600336488709, 1.945869474662082]
https://stackoverflow.com/questions/22071987
复制相似问题