是否可以预测数学运算是否会导致溢出?

发布于 2024-09-15 08:35:55 字数 67 浏览 2 评论 0原文

假设您有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

习惯成性 2024-09-22 08:35:55

是的。

为简单起见,我们假设溢出发生在 100 处。

a * b >= 100,我们有溢出

因此,对于a = n,如果b >= 100 / n,我们有溢出。如果 ab 为 0,则不会发生溢出。

这不适用于任何需要增加右手常量的数学设置,因为溢出检测会溢出。但是,操作的任何给定步骤都可能溢出,因此您确实需要在机器级别(而不是算法级别)发生之前检查每个加法和乘法。因此,您需要将问题划分为最小的已知数量,才能有效地使用此溢出检测。

我宁愿让语言抛出异常,但这只是我。

Yes.

Let's assume that overflow occurs at 100, for simplicity.

a * b >= 100, we have overflow

Therefore, for a = n, if b >= 100 / n, we have overflow. If a or b 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.

回忆那么伤 2024-09-22 08:35:55

打开溢出保护,然后应用操作。如果引发溢出异常,或者错误寄存器设置了溢出位,或者您的环境告诉您该问题,那么您就知道如果再次执行此操作,将会发生溢出。

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.

起风了 2024-09-22 08:35:55

对于sum:

MAX_NUMBER - A < B

会出现溢出

For sum:

MAX_NUMBER - A < B

there will be an overflow

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文