views:

64

answers:

3

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?

+2  A: 

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.

Stefan Kendall
It's probably cheaper at the end of the day to let the language except (in exceptional circumstances) than jump through hoops trying to cover all the cases that might overflow, as well.
Will A
Unfortunately the old languages don't take this route, and fortunately the newer ones just don't have this issue unless you run out of memory :P
Stefan Kendall
@Stefan : "Unless you run out of memory" is that correct? Overflow exceptions occur when an arithmetic operation produces a result that is outside the range of the data type returned by the operation.
Rohan West
A: 

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.

Douglas
Not all machines have this feature.
Stefan Kendall
A: 

For sum:

MAX_NUMBER - A < B

there will be an overflow

Daniel Moura
If A is negative then you will get an overflow in your test
Paul R
@Paul R You are right, there is a need to check if A>0. And to check if both are negative if will overflow the MIN_NUMBER.
Daniel Moura