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

查看:535
本文介绍了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中查看实现的详细信息. h longobject.c :

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

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天全站免登陆