13

Python 是用 C 编写的,实际上是一个 C 程序,这让我想知道如何处理十进制数字赋值。

C 程序如何实现非常大的十进制数(大于 int 或 long)的 Python 变量赋值?

例如:

a=10000...  # a=(10^1000)

在 python 中运行时,我知道值是如此之大以至于它在内存中占用了很多单词,所以 C 程序显然是这样做的,但是如何呢?

C 中的每个变量都有一个类型,但是 C 编译的代码不知道这个数字会有多大。

(python) C 程序如何处理该分配?(以及对这些变量的操作)

4

2 回答 2

5

这是structCPython 2.7.5 中用于表示长整数的 C:

/* Long integer representation.
   The absolute value of a number is equal to
        SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
   Negative numbers are represented with ob_size < 0;
   zero is represented by ob_size == 0.
   In a normalized number, ob_digit[abs(ob_size)-1] (the most significant
   digit) is never zero.  Also, in all cases, for all valid i,
        0 <= ob_digit[i] <= MASK.
   The allocation function takes care of allocating extra memory
   so that ob_digit[0] ... ob_digit[abs(ob_size)-1] are actually available.

   CAUTION:  Generic code manipulating subtypes of PyVarObject has to
   aware that longs abuse  ob_size's sign bit.
*/

struct _longobject {
        PyObject_VAR_HEAD
        digit ob_digit[1];
};

如果您想进一步探索,请下载源代码并查看以下文件:

./Include/longintrepr.h
./Include/longobject.h
./Objects/longobject.c

这将告诉您您可能想知道的每一个细节。:)

于 2013-10-15T12:56:52.393 回答
-1

出于性能原因,Python 可能有自己的大量实现,但它可以使用任何第三方任意精度库,例如GMP

于 2013-10-15T13:02:13.030 回答