在范围之间生成随机浮点数组

问题描述 投票:42回答:7

我无法找到一个函数来生成一定范围内给定长度的随机浮点数组。

我看过Random sampling,但没有任何功能似乎做我需要的。

random.uniform接近但它只返回一个元素,而不是一个特定的数字。

这就是我所追求的:

ran_floats = some_function(low=0.5, high=13.3, size=50)

这将返回一个由50个随机非唯一浮点数组成的数组(即:允许重复)均匀分布在[0.5, 13.3]范围内。

有这样的功能吗?

python arrays random numpy
7个回答
80
投票

np.random.uniform适合您的使用案例:http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html

sampl = np.random.uniform(low=0.5, high=13.3, size=(50,))

12
投票

为什么不使用列表理解?

ran_floats = [random.uniform(low,high) for _ in xrange(size)]

3
投票

为什么不将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]

3
投票

列表理解中的for循环需要时间并使其变慢。最好使用numpy参数(低,高,大小,..等)

import numpy as np
import time
rang = 10000
tic = time.time()
for i in range(rang):
    sampl = np.random.uniform(low=0, high=2, size=(182))
print("it took: ", time.time() - tic)

tic = time.time()
for i in range(rang):
    ran_floats = [np.random.uniform(0,2) for _ in range(182)]
print("it took: ", time.time() - tic)

样本输出:

('花了:',0.06406784057617188)

('花了:',1.7253198623657227)


2
投票

可能已经有了一个功能来完成你正在寻找的东西,但我不知道它(但是?)。与此同时,我会建议使用:

ran_floats = numpy.random.rand(50) * (13.3-0.5) + 0.5

这将产生一个形状(50,)的阵列,其均匀分布在0.5和13.3之间。

您还可以定义一个函数:

def random_uniform_range(shape=[1,],low=0,high=1):
    """
    Random uniform range

    Produces a random uniform distribution of specified shape, with arbitrary max and
    min values. Default shape is [1], and default range is [0,1].
    """
    return numpy.random.rand(shape) * (high - min) + min

编辑:嗯,是的,所以我错过了,有numpy.random.uniform()与你想要的完全相同的电话!试试import numpy; help(numpy.random.uniform)获取更多信息。


1
投票

这是最简单的方法

np.random.uniform(start,stop,(rows,columns))

1
投票

或者你可以使用SciPy

from scipy import stats
stats.uniform(0.5, 13.3).rvs(50)

并且用于记录整数的样本

stats.randint(10, 20).rvs(50)
© www.soinside.com 2019 - 2024. All rights reserved.