____tz_zs
1、OverflowError: integer division result too large for a float
在 Python 3 中,int/int 将返回一个 float。而 Python3 中的 int 类型是长整型,可以在计算中处理任意大的整数,而 float 类型有范围,所以下方例子中,极大整数的除法计算造成了溢出错误。
big_int = 10 ** 400 + 23
print(big_int / 2)
# OverflowError: integer division result too large for a float
2、python3 中的 int 类型是长整型,理论可以是任意大的整数。
用sys.getsizeof()
方法可以看 int 占了几位。如下,使用 400 位数字的输出情况
import sys
# long_int_str = "1111111111111111111111111111111111"
long_int_str = "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"
print(f"字符串长度:{len(long_int_str)}")
print(f"字符串内存使用:{sys.getsizeof(long_int_str)}")
print(f"int内存使用:{sys.getsizeof(int(long_int_str))}")
"""
字符串长度:34
字符串内存使用:83
int内存使用:40
字符串长度:400
字符串内存使用:449
int内存使用:204
"""
3、最大的浮点数 sys.float_info.max
在 Python 3 中,number / 10将尝试返回一个float. 但是,浮点值在 Python 中不能有任意大的大小,如果number很大,OverflowError将会引发。
import sys
print(sys.float_info)
# sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
print(sys.float_info.max) # 1.7976931348623157e+308
4、其他延伸 sys.maxsize
import sys
print(sys.maxsize) # 9223372036854775807
《The Python Standard Library》
An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 231 - 1 on a 32-bit platform and 263 - 1 on a 64-bit platform.
In Python, what is sys.maxsize?
Python3 可以在计算中处理任意大的整数。任何大到不能用 64 位容纳(或任何底层硬件限制)的整数都在软件中处理。因此,Python 3 没有 sys.maxint 常量。
5、用//
将两个整数的相除,获取整数
两个整数的整数除法不会将两个参数都转换为浮点数然后相除,避开了 float 。
big_int = 10 ** 400 + 23
# print(big_int / 2)
# OverflowError: integer division result too large for a float
print(big_int // 2)
# 5000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011
具体见另一篇 https://tzzsmaster.blog.csdn.net/article/details/121020236
参考
Why are the results of integer division and converting to an int after division different for large numbers?
How to manage division of huge numbers in Python?