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?
views:
64answers:
3Yes.
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.