str(uuid.uuid4().int>>64)[0:8] + str(uuid.uuid4().int>>64)[0:8]
我想用上面的代码创建一个 16 位的随机数。如果我分两部分生成它,它会使其更加随机还是我可以只执行以下操作:
str(uuid.uuid4().int>>64)[0:16]
最佳答案
我请您小心使用的随机数生成器。 我对生成的数字分布进行了测试。 这是我发现的:
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')
我们注意到,方法是相同的。 然而,第二个 [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')
这样,您肯定会定期分配 16 位数字。
关于python - 在 Python 中生成随机 16 位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25176447/