Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C implements the Python assignment of large numbers

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)

like image 362
izac89 Avatar asked Oct 15 '13 12:10

izac89


People also ask

How do you deal with large numbers in Python?

Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate.

Does C support multiple assignment?

No, C does not support multiple-assignment, nor has it language-level support for tuples.

How do you define a real number in Python?

A real number is a value that represents a quantity along a continuous line, which means that it can have fractions in decimal forms. 4.5 , 1.25 , and 0.75 are all real numbers. In computer science, real numbers are represented as floats. To test if a number is float, we can use the isinstance built-in function.


1 Answers

Here is the C struct that is used in CPython 2.7.5 to represent a long integer:

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

If you'd like to explore this further, download the source code and take a look at the following files:

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

This will tell you every detail you could possibly wish to know. :)

like image 124
NPE Avatar answered Oct 24 '22 06:10

NPE