可被N整除的随机数

时间:2019-05-14 05:50:03

标签: python python-3.x

我想从[a,b]范围中生成一个随机数,该随机数可以除以N(在我的情况下为4)。 我有解决方案,但是有没有更好(更优雅)的方法呢?

frontend.loaner.com

解决方案从这里: Python: Generate random number between x and y which is a multiple of 5 无法回答我的问题,因为我必须实现以下内容:

result = random.randint(a, b)
result = math.ceil(result / 4) * 4

我必须将原始范围除以4,并且比我的原始解决方案难读

4 个答案:

答案 0 :(得分:1)

我想到的第一件事是使用range在给定间隔中创建所有可能选择的列表,然后使用choice随机选择一个值。

因此,在这种情况下,对于给定的ab

random.choice(range(a + 4 - (a%4), b, 4))

如果a是4的完美倍数,则

random.choice(range(a, b, 4))

将为您提供所需的随机数。

因此,在单个通用函数中(如注释中所建议)

def get_num(a, b, x):
    if not a % x:
        return random.choice(range(a, b, x))
    else:
        return random.choice(range(a + x - (a%x), b, x))

其中x是需要倍数的数字。

答案 1 :(得分:1)

使用random.randrange,步长为n,如果a不被n整除,则以a+n-(a%n)作为起点,否则,以a作为起点

import random

def rand_n(a, b,n):

    #If n is bigger than range, return -1
    if n > b-a:
        return -1

    #If a is divisible by n, use a as a start, using n as step size
    if a%n == 0:
        return random.randrange(a,b,n)

    # If a is not divisible by n, use a+n-(a%n) as a start, using n as step size
    else:
        return random.randrange(a+n-(a%n),b, n)

答案 2 :(得分:1)

正如其他人指出的那样,您的解决方案可能会产生超出范围的结果,例如math.ceil(15 / 4) * 4 == 16。另外,请注意,产生的分布可能与均匀分布相差很远。例如,如果a == 0b == 4,则在80%的情况下,生成的数字将为4。 除此之外,这对我来说似乎很好,但是在Python中,您也可以只使用整数除法运算符(实际上是地板除法运算符,因此它不等同于示例):

result = random.randint(a, b)
result = result // 4 * 4

但是,生成具有特定约束的统一随机数(同时保持均匀分布)的效率较低的通用方法是循环生成它们,直到找到一个好的随机数:

result = 1
while result % 4 != 0:
    result = random.randint(a, b)

答案 3 :(得分:1)

通用解决方案和示例

import random

def divisible_random(a,b,n):
    if b-a < n:
      raise Exception('{} is too big'.format(n))
    result = random.randint(a, b)
    while result % n != 0:
      result = random.randint(a, b)
    return result
# get a random int in the range 2 - 12, the number is divisible by 3
print(divisible_random(2,12,3))
相关问题