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

Min*_*nnR 1 python random uuid

str(uuid.uuid4().int>>64)[0:8] + str(uuid.uuid4().int>>64)[0:8]
Run Code Online (Sandbox Code Playgroud)

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

str(uuid.uuid4().int>>64)[0:16]
Run Code Online (Sandbox Code Playgroud)

Tah*_*aha 5

我邀请你小心你正在使用的随机数生成器。我对生成的数字分布进行了测试。这是我发现的:

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')
Run Code Online (Sandbox Code Playgroud)

问题中提出的随机数的生成

正如我们注意到的,方法是相同的。尽管如此,第二个 [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')
Run Code Online (Sandbox Code Playgroud)

使用 randint 函数生成随机数

这样,您肯定会定期分配 16 位数字。