标签:C++ java JavaScript python 管理
你现在当你增加一个数字的最大值时会发生什么?
最常见和最合乎逻辑的答案:我收到数字溢出异常!
但真正的答案并非总是或可能永远不会!
如果你不知道你的编译器是如何管理的,你可能会用错误的解决方案设计出糟糕的算法。
让我们证明这一点!
C#
在 C# 中,递增最大值时,不会收到数字溢出异常(这是默认行为)。请看下面的代码片段,其中最大整数值 (2147483647) 递增 1。
int count=int.MaxValue;
Console.WriteLine($"count is {++count}");
在这种情况下,输出将是 -2147483648这显然是一个溢出,因为我们在正数增量后得到一个负数。发生这种情况是因为增量上升了数字中最高有效位,即符号位(+/-)。
要触发溢出/下溢异常,我们需要将操作放在选中的块中,如下所示:
int count = int.MaxValue;
checked
{
Console.WriteLine($"count is {++count}");
}
我们开始了,例外已经送达!'System.OverflowException' in overflow-dotnet.dll: 'Arithmetic operation resulted in an overflow.'
在 C# 编译器中,您可以启用选项 CheckForOverflowUnderflow,其中默认上下文是已检查的上下文,并且启用了溢出检查(并且可以使用关键字uncheck来取消选中上下文)。
爪哇岛
在 Java 中,行为与 C# 中发生的行为非常相似,请查看以下代码片段!
Integer count=Integer.MAX_VALUE; // 2147483647
System.out.println(String.format("count is %d",++count));
在这种情况下,输出将为 -2147483648这显然是溢出,如前面的示例所示。
从Java 8开始,数学类提供了一组运算(decrementExact,addExact,multiplyExact等),用于针对数字溢出/下溢的“检查”算术运算。
To trigger an overflow exception we need to use Math.incrementExact that returns the argument incremented by one, throwing an exception if the result overflows an int.
Integer count=Integer.MAX_VALUE; // 2147483647
Math.incrementExact(count);
here we go, the exception is served:
Exception in thread "main" java.lang.ArithmeticException: integer overflow at java.base/java.lang.Math.incrementExact(Math.java:964)
at Main.main(Main.java:12)
JavaScript
In JavaScript too we don't have an overflow exception if we increment a maximum value of a number and, at moment of writing, there is no way to detect a numeric overflow exception unless you write a custom function to reach this goal.
Let's prove that.
let counter=Number.MAX_VALUE;
console.log(++counter);
In the previous snippet we are incrementing by one the maximum value of Number represented by the constant Number.MAX_VALUE. The output of this snippet is 1.7976931348623157e+308 the original value of the variable counter (so the increment has non effect).
But how detect an numeric overflow/underflow JavaScript?
在 algotech.solutions 的这篇文章中,有一些很好的算术考虑因素,可以实现自定义函数来检测数字溢出/下溢。
蟒
在 Python 3 中,整数没有固定大小(本文解释了它们的结构),唯一的限制是可用内存。因此,在内存可用之前,以下代码永远不会停止。
from time import sleep
count=int(0)
step = int(10**10000)
while(True):
count+=step
sleep(0.2)
如果我们想对整数的维度有更多的控制,我们可以使用 NumPy
import sys
import numpy as np
count=np.int64(sys.maxsize)
count+=1
在这里,我们提供了例外:RuntimeWarning: overflow encountered in long_scalars
count+=1
-9223372036854775808
结论
检测数字溢出/下溢是昂贵的,因此许多编程语言的默认行为是忽略它,让程序员决定是选中还是取消选中算术运算。
真正重要的是对问题的认识以及编程语言的实现如何应对这种情况。忽略或忽略问题可能会导致意外结果和安全漏洞(在某些情况下)。
写这篇文章是因为很多年前我写了一个算法来挑战Hackerrank,一个无声的溢出使它失败了(长话短说,我浪费了很多时间来弄清楚问题的本质)。
标签:C++,java,JavaScript,python,管理 来源:
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。