Skip to main content
 首页 » 编程设计

python之为什么 2**1024 工作而 2**(2048/2) 导致 OverflowError

2025年05月04日13mfryf

当我运行代码时

a = 2**(2028/2)*1023 
print("a is",a) 
 
b = 2**(2029/2)*1023 
print("b is",b) 
 
c = 2**(2028/2)*1024 
print("c is",c) 
 
d = 2**(1014)*1024 
print("d is",d) 
 
e = 2**(2048) 
print("e is",e) 
 
g = 2**(1024) 
print("g is",g) 
 
h = 2**(2048/2) 
print("h is",h) 

输出是:

a is 1.795937575160302e+308 
b is inf 
c is inf 
d is 179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216 
e is 32317006071311007300714876688669951960444102669715484032130345427524655138867890893197201411522913463688717960921898019494119559150490921095088152386448283120630877367300996091750197750389652106796057638384067568276792218642619756161838094338476170470581645852036305042887575891541065808607552399123930385521914333389668342420684974786564569494856176035326322058077805659331026192708460314150258592864177116725943603718461857357598351152301645904403697613233287231227125684710820209725157101726931323469678542580656697935045997268352998638215525166389437335543602135433229604645318478604952148193555853611059596230656 
g is 179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216 
Traceback (most recent call last): 
  File "newfile.py", line 19, in <module> 
    h = 2**(2048/2) 
OverflowError: (34, 'Result too large') 

c 应该与 d 相同,但实际上不是。 g 和 h 相同。为什么?是否有一种解决方法可以让您准确计算 2**(2048/2) 和 2**(2028/2)*1024?我不认为 2048 太大了,因为 e 计算没有任何错误。

请您参考如下方法:

区别在于 2048/2 是一个 float ,而不是一个整数。因此,结果将被评估为 float ,而 float 的范围有限。

因此:

>>> 2**1024.0 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
OverflowError: (34, 'Result too large') 
 
>>> 2**1024 
179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216 
 
>>> float(2**1024) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
OverflowError: int too large to convert to float 

但是,如果你只使用整数:

>>> 2**(2048//2) 
179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216