13

The fact that Python is written in C and is actually a C program made me wonder about how decimal numbers assignment are handled.

How does a C program implement the Python variable assignment of a very large decimal number (bigger than int or long)?

For example:

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

when running in python I know that the value is so big that it takes many words in the memory, so the C program obviously does that, but how?

Every variable in C has a type, but the C compiled code does not know how big the number will be.

How does the (python) C program handles that assignment? (and operations on such variables)

4

2 に答える 2

5

struct長整数を表すために CPython 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 に答える