我还没有找到一个能够在给定范围内生成指定长度的随机浮点数数组的函数。
我查看了随机抽样,但是没有一个函数似乎可以达到我的需求。
random.uniform接近我的要求,但它只返回单个元素而不是特定数量。
这就是我想要的:
ran_floats = some_function(low=0.5, high=13.3, size=50)
是否有这样的函数?会返回一个由50个随机非唯一浮点数组成的数组(即:允许重复),均匀分布在范围[0.5, 13.3]
内。
这样的函数存在吗?
np.random.uniform
适合您的使用情况:
sampl = np.random.uniform(low=0.5, high=13.3, size=(50,))
2019年10月更新:
虽然语法仍然受支持,但似乎NumPy 1.17的API已更改,以支持更大的随机数生成器控制。今后API已更改,您应该查看https://docs.scipy.org/doc/numpy/reference/random/generated/numpy.random.Generator.uniform.html
some_function(low=0.5, high=13.3, size=50)
。这展示了Python库的出色设计。#厉害 - Saravanabalagi Ramachandran为什么不使用列表推导式?
在Python 2中
ran_floats = [random.uniform(low,high) for _ in xrange(size)]
在Python 3中,range
的工作方式类似于 xrange
(ref)。ran_floats = [random.uniform(low,high) for _ in range(size)]
这是最简单的方法
np.random.uniform(start,stop,(rows,columns))
可能已经有一个可以实现你想要的功能的函数,但我还不知道(现在?)。 同时,我建议使用:
ran_floats = numpy.random.rand(50) * (13.3-0.5) + 0.5
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)
以获取更多信息。
Alternatively you could use SciPy
from scipy import stats
stats.uniform(0.5, 13.3).rvs(50)
randint()
。stats.randint(10, 20).rvs(50)
为什么不把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]
使用列表推导式中的for循环会消耗时间,使程序变慢。更好的方法是使用numpy参数(如low、high、size等)。
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)
或者,如果您可以接受一个实数列表,您可以使用标准的 random.randrange
:
def some_function(low, high, size):
low_int = int(low * 1000)
high_int = int(high *1000)
return [random.randrange(low_int, high_int, size)/1000 for _ in range(size)]
这应该适用于你的示例
sample = (np.random.random([50, ]) * 13.3) - 0.5
np.random.random_sample(size)
会在半开区间 [0.0, 1.0) 中生成随机浮点数。
numpy
,但你没有提到numpy.random.uniform
,尽管它恰好有你想要的调用签名。你是否已经导入了numpy
库? - DSM[random.uniform(low, high) for i in xrange(size)]
- Phylogenesis