V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
SystemLight
V2EX  ›  Python

Python 中整型最大问题?

  •  
  •   SystemLight ·
    SystemLight · 2020-06-01 11:42:18 +08:00 · 2542 次点击
    这是一个创建于 1396 天前的主题,其中的信息可能已经有所发展或是发生改变。

    使用 sys.maxsize 获取到最大值是:9223372036854775807

    但是当我创建一个更大的整型时:print(int("46804033442370000000640975")) python 对此没有任何错误,而是正常的执行,这是为什么?

    import sys
    
    MAX_INT = sys.maxsize
    print(MAX_INT)
    print(int("46804033442370000000640975"))
    
    输出:
    9223372036854775807
    46804033442370000000640975
    
    4 条回复    2020-06-01 15:24:52 +08:00
    ipwx
        1
    ipwx  
       2020-06-01 11:46:42 +08:00
    因为 sys.maxsize 这个数字是 2**64-1 。是普通编程语言里面最大的整数。

    Python 如果大于这个普通整数大小,就会自动切换到大数运算库。所以 Python 整数多大都能算。
    ----

    P.S. 所以其实可以看出,Python 从根源上就没考虑太多运行时性能优化,一切先保证易用性。别的语言调大数运算库都挺麻烦的。
    aloxaf
        2
    aloxaf  
       2020-06-01 11:49:16 +08:00
    sys.maxsize
    An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 2**31 - 1 on a 32-bit platform and 2**63 - 1 on a 64-bit platform.

    以上摘自 Python 文档,可以看这玩意儿和 INT_MAX 根本没关系。
    Python 的整形是无限长整型,没有最大值
    InkStone
        3
    InkStone  
       2020-06-01 12:40:26 +08:00
    @aloxaf Python2 和 3 在这里行为不一样

    Python2 里,int 的上限就是这么大,在超出上限时会隐式转换为无上限的 long 类型。虽然对用户透明,但看类型是可以看出来区别的。
    Python3 里的 int 是真·无上限。内部肯定也有一个类似的机制,但不会产生类型转换
    Fasion
        4
    Fasion  
       2020-06-01 15:24:52 +08:00
    Python 整数对象底层通过一个整数数组实现大整数运算,因此,只要你有足够的内存,Python 可以表示非常非常大的整数,具体可以参考这篇文章: https://www.imooc.com/read/76/article/1903
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3322 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 13:30 · PVG 21:30 · LAX 06:30 · JFK 09:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.