在code处理大数大数、code

2023-09-11 22:38:20 作者:色空

我工作的一个规划问题,我需要处理一些涉及100000位。可蟒蛇手柄数字也是这样吗?

I'm working on a programming problem where I need to handle a number involving 100000 digits. Can python handle numbers like this?

推荐答案

至于其他的答案指出,Python做支持整数由可用内存量只限制。如果你想更快地对他们的支持,请尝试 gmpy (如gmpy的作者和电流共同维护我当然这里有点偏的米; - ):

As other answers indicated, Python does support integer numbers bounded only by the amount of memory available. If you want even faster support for them, try gmpy (as gmpy's author and current co-maintainer I'm of course a little biased here;-):

$ python -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'x+1'
10000 loops, best of 3: 114 usec per loop
$ python -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'y+1'
10000 loops, best of 3: 65.4 usec per loop

通常情况下,算术是不是因为这样的数字工作(虽然 gmpy 瓶颈的直接支持一些组合和一些理论的功能可以帮助,如果这就是你再有这样的数字做)。打开数转换成十进制可能是常见的操作,会觉得最慢...

Typically, arithmetic is not the bottleneck for working with such numbers (although gmpy's direct support for some combinatorial and number-theoretical functions can help if that's what you're doing with such numbers). Turning the numbers into decimal strings is probably the common operation that will feel slowest...:

$ python -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'str(x)'
10 loops, best of 3: 3.11 sec per loop
$ python -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'str(y)'
10 loops, best of 3: 27.3 msec per loop

正如你看到的,即使是在 gmpy 数量巨大的字串可以是几百倍慢于一个简单的加法(唉,这是一个本质上复杂的操作!);但在C时代的比率机Python $ C $可以去字串是数万倍,比简单的加法慢,所以你真的要注意了,特别是如果你决定不下载并安装 gmpy (例如,因为你不能:例如,gmpy目前没有在谷歌应用程序引擎的支持)。

As you see, even in gmpy stringification of huge numbers can be hundreds of times slower than a simple addition (alas, it's an intrinsically complicated operation!); but in native Python code the ratio of times can go to stringification being tens of thousands times slower than a simple addition, so you really want to watch out for that, especially if you decide not to download and install gmpy (for example because you can't: e.g., gmpy is not currently supported on Google App Engine).

最后,中间案例:

$ python2.6 -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'x*x'
10 loops, best of 3: 90 msec per loop
$ python2.6 -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'y*y'
100 loops, best of 3: 5.63 msec per loop
$ python2.6 -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'y*x'
100 loops, best of 3: 8.4 msec per loop

正如你看到的,在本机Python相乘两个巨大的数字code可以比简单加慢近1000倍,而与 gmpy 放缓小于100倍(这不是太糟糕,即使只有一个,如果该号码已经在 gmpy 自己的格式,以便有转换其他的开销)。

As you see, multiplying two huge numbers in native Python code can be almost 1000 times slower than the simple addition, while with gmpy the slowdown is less than 100 times (and it's not too bad even if only one if the numbers is already in gmpy's own format so that there's the overhead of converting the other).