【问题标题】:Check if python int is too large to convert to float检查python int是否太大而无法转换为float
【发布时间】:2011-03-14 07:13:05
【问题描述】:

有没有办法检查长整数是否太大而无法在python中转换为浮点数?

【问题讨论】:

    标签: python floating-point integer


    【解决方案1】:
    >>> import sys
    >>> sys.float_info.max
    1.7976931348623157e+308
    

    实际上,如果您尝试将太大的整数转换为浮点数,则会引发异常。

    >>> float(2 * 10**308)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    OverflowError: Python int too large to convert to C double
    

    【讨论】:

    • 对于学究:如果你关心边缘情况,那么第二种方法('试试看')更可靠一些。有大于 sys.float_info.max 的整数(虽然只有很小的量)仍然可以安全地转换为浮点数。在典型的机器上,int(sys.float_info.max)2**1024 - 2**971,但可以转换直到并包括 2**1024 - 2**970 - 1 的整数,而无需提高 OverflowError
    猜你喜欢
    • 1970-01-01
    • 2019-10-27
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多