开发者

Is it possible to predict if a mathematical operation would result in an overflow?

Say you have 2 numbers, for each typical mathematical operation is it possible to predict (without significant overh开发者_JS百科ead) whether those operations would result in an overflow of the type which those numbers are currently represented as?


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.


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.


For sum:

MAX_NUMBER - A < B

there will be an overflow

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜