python是如何表示这么大的整数的? [英] How does python represent such large integers?

查看:27
本文介绍了python是如何表示这么大的整数的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In C, C++, and Java, an integer has a certain range. One thing I realized in Python is that I can calculate really large integers such as pow(2, 100). The same equivalent code, in C, pow(2, 100) would clearly cause an overflow since in 32-bit architecture, the unsigned integer type ranges from 0 to 2^32-1. How is it possible for Python to calculate these large numbers?

推荐答案

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

Basically, big numbers in Python are stored in arrays of 'digits'. That's quoted, right, because each 'digit' could actually be quite a big number on its own. )

你可以在longintrepr查看实现细节.hlongobject.c:

有两组不同的参数:一组用于 30 位数字,以无符号 32 位整数类型存储,一组用于 15 位数字,每个数字都存储在无符号短整型中.的价值PYLONG_BITS_IN_DIGIT,在配置时或在 pyport.h 中定义,用于决定使用哪种数字大小.

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是如何表示这么大的整数的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆