产生一个随机数

时间:2018-09-05 09:14:53

标签: python python-3.x

我正在做一个问题,要求我使用random()以相等的概率生成一个介于0到9999之间的数字。我知道我可以通过乘以random()来缩放,但是我主要得到的是4位数字。有人知道该怎么办吗?

4 个答案:

答案 0 :(得分:1)

建议,假设您想要一个随机整数:

from random import randint
print(randint(0,9999))

答案 1 :(得分:1)

使用class Test: def __init__(self, value): self.value = value def __eq__(self, other): """To implement 'in' operator""" # Comparing with int (assuming "value" is int) if isinstance(other, int): return self.value == other # Comparing with another Test object elif isinstance(other, Test): return self.value == other.value import random value = 5 test_list = [Test(random.randint(0,100)) for x in range(1000)] if value in test_list: print "i found it"

randint

答案 2 :(得分:1)

您将获得4位数的数字,因为它们是您范围的90%,因此可以预期。但是,您无需缩放random(),而使用random.randint

答案 3 :(得分:0)

import numpy as np

# retruns n numbers with uniform(equal) propability between a and b
# thus for each x in arr: a <= x < b
arr = np.random.uniform(a, b, n)

如果您希望它们为整数

arr = np.round(arr).astype(int)

另请参见此处:np.random.uniform

相关问题