python - 在 Python 中生成随机 16 位数字

标签 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]

最佳答案

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

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 位数字。

关于python - 在 Python 中生成随机 16 位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25176447/

相关文章:

reactjs - 使用 useRef(uuid()) 的目的是什么?

python - 预测下一个数字

Python:访问使用变量生成的字典键的值

php - 在 PHP/Mysql 中生成随机数作为主键

algorithm - 在二叉树上实现随机过程

C++ 随机数生成 : Generate cos squared function

ruby-on-rails - 如何迁移复杂的 Rails 数据库以使用 UUID 主键 Postgresql

python - 用于与 SQL 数据库交互的 python 中最好的库是什么?

多处理中的 Python 日志记录

java - Oracle 中是否不推荐使用 RAW 类型?