是否可以预测数学运算是否会导致溢出?
假设您有 2 个数字,对于每个典型的数学运算,是否可以预测(无需大量开销)这些运算是否会导致这些数字当前表示的类型溢出?
Say you have 2 numbers, for each typical mathematical operation is it possible to predict (without significant overhead) whether those operations would result in an overflow of the type which those numbers are currently represented as?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的。
为简单起见,我们假设溢出发生在 100 处。
a * b >= 100
,我们有溢出因此,对于
a = n
,如果b >= 100 / n
,我们有溢出。如果a
或b
为 0,则不会发生溢出。这不适用于任何需要增加右手常量的数学设置,因为溢出检测会溢出。但是,操作的任何给定步骤都可能溢出,因此您确实需要在机器级别(而不是算法级别)发生之前检查每个加法和乘法。因此,您需要将问题划分为最小的已知数量,才能有效地使用此溢出检测。
我宁愿让语言抛出异常,但这只是我。
Yes.
Let's assume that overflow occurs at 100, for simplicity.
a * b >= 100
, we have overflowTherefore, for
a = n
, ifb >= 100 / n
, we have overflow. Ifa
orb
is 0, you don't have overflow.This won't work for any mathematical setup which needs to increase the right hand constant, as your overflow detection would overflow. However, any given step of an operation can overflow, so you really need to check every addition and multiplication before it happens at the machine level, rather than the algorithm level. Ergo, you'll need to partition your problem into the smallest known quantities to effectively use this overflow detection.
I'd rather just let the language throw an exception, but that's just me.
打开溢出保护,然后应用操作。如果引发溢出异常,或者错误寄存器设置了溢出位,或者您的环境告诉您该问题,那么您就知道如果再次执行此操作,将会发生溢出。
Turn on overflow protection, and then apply the operation. If an overflow exception is thrown, or an error register gets an overflow bit set, or however your environment tells you about the problem, then you know that if you do it again, you'll get an overflow.
对于sum:
会出现溢出
For sum:
there will be an overflow