Python是用C编写的,实际上是C程序,这使我想知道如何处理小数点赋值。

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

例如:

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

当在python中运行时,我知道该值太大,以至于它需要占用内存中的许多单词,因此C程序显然可以做到这一点,但是如何呢?

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

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

最佳答案

这是CPython 2.7.5中用来表示长整数的C struct:

/* 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];
};

如果您想进一步探索,请访问download the source code并查看以下文件:

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

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

10-05 21:21
查看更多