在Python中生成随机的16位数字

时间:2014-08-07 07:21:49

标签: python random uuid

str(uuid.uuid4().int>>64)[0:8] + str(uuid.uuid4().int>>64)[0:8]

我想用上面的代码创建一个16位数的随机数。如果我分两部分生成它,它是否会使它更随机,或者我可以执行以下操作:

str(uuid.uuid4().int>>64)[0:16]

3 个答案:

答案 0 :(得分:4)

我邀请您注意您使用的随机数生成器。 我对生成的数字分布进行了测试。 这是我发现的:

import uuid
import numpy as np
import matplotlib.pyplot as plt

# Generation of 100000 numbers using the [0:8] + [0:8] technique
res1 = np.empty(shape=100000, dtype=int)
for i in xrange(res1.size):
    tmp = str(uuid.uuid4().int>>64)[0:8] + str(uuid.uuid4().int>>64)[0:8]
    res1[i] = int(tmp)

# Generation of 100000 numbers using the [0:16] technique
res2 = np.empty(shape=100000, dtype=int)
for i in xrange(res1.size):
    tmp = str(uuid.uuid4().int>>64)[0:16]
    res2[i] = int(tmp)

# Histogram plot
plt.setp(patches, 'facecolor', 'g', 'alpha', 0.75)
n, bins, patches = plt.hist(res1, 100, normed=1, histtype='stepfilled')
n, bins, patches = plt.hist(res2, 100, normed=1, histtype='stepfilled')

Generation of random numbers as proposed in the question

正如我们注意到的,方法是相同的。 然而,第二个[0:16]可以给0作为第一个数字,它产生15位数字。

为什么不使用随机函数。

# Generation of random numbers using `random` function
res3 = np.random.randint(1e15, 1e16, 100000)
# Plot
n, bins, patches = plt.hist(res3, 100, normed=1, histtype='stepfilled', label='randint')

Generation of random numbers with the function randint

这样,您一定会定期分发16位数字。

答案 1 :(得分:3)

Python中的uuid4实现尝试使用系统提供的uuid生成器(如果可用),然后使用os.urandom()(所谓的" true"随机性),然后如果两者都不可用,则random.randrange()(使用PRNG)。在前两种情况下,随机性"应该"你可以从计算机上随意询问。在PRNG情况下,每个随机字节是单独生成的,因此连接两半实际上不应该有所帮助。

我们可以凭经验检查数字的分布是如何使用这样的代码:

import uuid
digits = [0] * 10
for i in range(100000):
    x = str(uuid.uuid4().int)[-16:]
    for d in x:
        digits[int(d)] += 1
print(digits)

请注意,我更改了您的代码,删除了>>64,因为它可能会使数字太短并且更改切片以取代最后16位数字。数字的分布非常均匀。

[159606, 159916, 160188, 160254, 159815, 159680, 159503, 160015, 160572, 160451]

现在,让我们从分销的角度看看改为str(uuid.uuid4().int)[-8:] + str(uuid.uuid4().int)[-8:]的内容:

[159518, 160205, 159843, 159997, 160493, 160187, 160626, 159665, 159429, 160037]

基本上没什么。

顺便说一下,从字符串开始,不用位移:

[151777, 184443, 184347, 166726, 151925, 152038, 152178, 152192, 151873, 152501]

由于uuid4开头的6个非随机位,偏向1和2。

答案 2 :(得分:1)

只看你的头衔,我应该问,为什么不呢:

from random import randint
s = ''
for i in range(16):
    s = s + str(randint(0,9))

你没有解释使用UUID的原因,对我来说,这似乎很奇怪。