gpt4 book ai didi

python - python如何表示这么大的整数?

转载 作者:太空狗 更新时间:2023-10-30 02:20:28 25 4
gpt4 key购买 nike

在 C、C++ 和 Java 中,整数具有一定的范围。我在 Python 中意识到的一件事是我可以计算非常大的整数,例如 pow(2, 100)。同样的等效代码,在 C 中,pow(2, 100) 显然会导致溢出,因为在 32 位体系结构中,无符号整数类型的范围为 0 到 2^32-1。 Python 是如何计算这些大数的?

最佳答案

基本上,Python 中的大数字存储在“数字”数组中。这是引用的,对,因为每个“数字”本身实际上可能是一个很大的数字。 )

您可以在longintrepr.h中查看实现细节。和 longobject.c :

There are two different sets of parameters: one set for 30-bit digits, stored in an unsigned 32-bit integer type, and one set for 15-bit digits with each digit stored in an unsigned short. The value of PYLONG_BITS_IN_DIGIT, defined either at configure time or in pyport.h, is used to decide which digit size to use.

/* 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.

*/

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

关于python - python如何表示这么大的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22875067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com