产生两个数字之间的随机范围

时间:2019-12-18 12:46:05

标签: python random range

在长度[range_length_min, range_length_max]范围内生成长度为[range_start, range_end]的随机范围的pythonic方法(可以使用numpy)是什么?

示例:

  • range_length_min = 5
  • range_length_max = 10
  • range_start = 0
  • range_end = 2000

允许的解决方案:

  • [53, 59]
  • [934, 941]

无效的解决方案:

  • [92, 94],因为范围长度小于range_length_min
  • [92, 104],因为范围的长度大于range_length_max
  • [-4, 3],因为范围的开始小于range_start
  • [1998, 2004],因为范围结尾小于range_end

当前解决方案:

start = np.random.randint(range_start, range_end - (range_max_length - range_min_length))
end = start + np.random.randint(range_min_length, range_max_length)

这将给出正确的结果,但不会进行均匀采样。 range_end - (range_max_length - range_min_length)是骇客。

3 个答案:

答案 0 :(得分:1)

这是一种基于加权长度选择的方法:

import random

def rand_interval(lmin,lmax,a,b):
    """picks random subinterval in [a,b] with length between lmin and lmax inclusive"""
    weights = [b-a - x + 1 for x in range(lmin,lmax+1)]
    length = random.choices(range(lmin,lmax+1),weights)[0]
    start = random.randint(a,b-length)
    return start, start + length

测试:

import collections
print(collections.Counter(rand_interval(1,2,1,3) for _ in range(10000)))

典型输出:

Counter({(1, 2): 3389, (1, 3): 3386, (2, 3): 3225})

答案 1 :(得分:0)

怎么样?

from random import randint

a = randint(range_start, range_end - range_length_max)
b = randint(range_length_min, range_length_max)

r = [a, a+b]

答案 2 :(得分:0)

只需尝试为特定需求创建函数

>>> def foo(range_start, range_end, range_length_min, range_length_max):
...     v = random.randint(range_start, range_end)
...     v1 = random.randint(v + range_length_min, v + range_length_max if range_length_max <= range_end else range_end)
...     return [v, v1]
... 
>>> foo(range_start, range_end, range_length_min, range_length_max)
[1384, 1390]