Python 中的 random.randint(1,n)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2597444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
random.randint(1,n) in Python
提问by Arkapravo
Most of us know that the command random.randint(1,n)
in Python (2.X.X) would generate a number in random (pseudo-random) between 1 and n. I am interested in knowing what is the upper limit for n ?
我们大多数人都知道random.randint(1,n)
Python (2.XX)中的命令会生成一个介于 1 和 n 之间的随机数(伪随机数)。我有兴趣知道 n 的上限是多少?
回答by sth
randint()
works with long integers, so there is no upper limit:
randint()
适用于长整数,因此没有上限:
>>> random.randint(1,123456789012345678901234567890)
113144971884331658209492153398L
回答by Alex Martelli
No doubt you have a bounded amount of memory, and address space, on your machine; for example, for a good 64-bit machine, 64 GB of RAM [[about 2**36
bytes]] and a couple of TB of disk (usable as swap space for virtual memory) [[about 2**41
bytes]]. So, the "upper bound" of a Python long integer will be the largest one representable in the available memory -- a bit less than 256**(2**40)
if you are in absolutelyno hurry and can swap like crazy, a bit more than 256**(2*36)
(with just a little swapping but not toomuch) in practical terms.
毫无疑问,您的机器上有一定数量的内存和地址空间;例如,对于一台好的 64 位机器,64 GB 的 RAM [[大约2**36
字节]] 和几 TB 的磁盘(可用作虚拟内存的交换空间)[[大约2**41
字节]]。因此,Python 长整数的“上限”将是可用内存中可表示的最大一个——比256**(2**40)
如果你绝对不着急并且可以疯狂交换256**(2*36)
的情况下要少一点,多一点(只有一点点)实际上交换但不要太多)。
Unfortunately it would take quite a bit of time andspace to represent these ridiculously humongous numbers in decimal, so, instead of showing them, let me check back with you -- why would you even careabout such a ridiculous succession of digits as to constitute the "upper bound" you're inquiring about? I think it's more practical to put it this way: especially on a 64-bit machine with decent amounts of RAM and disk, upper bounds of long integers are waybigger than anything you'll ever compute. Technically, a mathematician would insist, they're notinfinity, of course... but practically, they might as well be!-)
不幸的是,用十进制表示这些可笑的庞大数字需要相当多的时间和空间,因此,与其展示它们,不如让我和你核实一下——你为什么还要关心这样一个可笑的数字序列来构成你要问的“上限”是什么?我认为这是更实际的把它这种方式:尤其是在64位机体面数量的RAM和磁盘上,长整数的上限是这样比你永远不会计算什么更大。从技术上讲,数学家会坚持认为,它们当然不是无穷大……但实际上,它们也可能是无穷大!-)