如何生成Python3中0到无穷大之间的N个随机数

How to Generate N random numbers in Python 3 between 0 to infinity

如何在python3中生成n个随机数? n为待​​定变量。最好是自然数(整数 > 0), 我发现的所有答案都采用一个范围内的随机整数,但我不想从一个范围内生成数字。 (除非范围是 0 到无穷大)

套用维特根斯坦的话,你的机器的极限就是你的语言的极限。即在 computers/computation 世界中没有无穷大这样的东西。你可以使用sys.maxsize(python中的sys.maxint 2)得到你的机器支持的最大正整数,并将它传递给random.randint函数:

>>> import sys
>>> sys.maxsize
9223372036854775807
>>> random.randint(0,sys.maxsize)
7512061515276834201

要生成多个随机数,您可以使用如下列表推导式:

>>> N = 10
>>> [random.randint(0,sys.maxsize) for _ in range(N)]
[3275729488497352533, 7487884953907275260, 36555221619119354, 1813061054215861082, 619640952660975257, 9041692448390670491, 5863449945569266108, 8061742194513906273, 1435436865777681895, 8761466112930659544]

有关 python 2.X and 3.Xsys.maxintsys.maxsize 的区别的更多信息:

The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).

我认为您可能需要重新考虑您要用您想要的随机数做什么。特别是,您从什么分布中抽取数字? 如果你希望你的随机数均匀分布(每个数字被选中的概率相等),你不能:你需要无限量的内存(或时间,或两者)。

当然,如果您允许非均匀分布,这里有一些介于 1 和(大致)我的系统允许的最大 float 之间的随机数,但由于这些数字的方式存在差距有代表。您可能会觉得 "large" 个数字被选中的概率下降得比您希望的要快......

In [254]: [int(1./random.random()) for i in range(10)]
Out[254]: [1, 1, 2, 1, 1, 117, 1, 3, 2, 6]

这里我们有内存限制,所以我们可以得到系统可以达到的最大随机数。只需将您想要的 n 位数字放在条件中,您就可以获得所需的结果。例如,我尝试了 6 位随机 numbers.One 可以根据要求尝试。希望这能在一定程度上解决您的问题。

导入系统

来自随机导入 *

我在范围内(sys.maxsize): 打印(randint(0,9),randint(0,9),randint(0,9),randint(0,9),randint(0,9),randint(0,9),sep ='')