Home All Groups Group Topic Archive Search About

overflow detection without try-catch

Author
27 Sep 2006 1:43 PM
AMercer
I want to detect if multiplying two integers or two longs will cause an
overflow without using a try-catch block.  I know how to do it with
try-catch, but the performance hit is too much.  I want an efficient test so
I can program like

if CausesOverflow(x,y) then
  ' do one thing
else
  ' do something else
endif

I am using VB and FW 1.1.  I'll be upgrading from 1.1 soon.

Author
27 Sep 2006 1:59 PM
Herfried K. Wagner [MVP]
Show quote Hide quote
"AMercer" <AMer***@discussions.microsoft.com> schrieb:
>I want to detect if multiplying two integers or two longs will cause an
> overflow without using a try-catch block.  I know how to do it with
> try-catch, but the performance hit is too much.  I want an efficient test
> so
> I can program like
>
> if CausesOverflow(x,y) then
>  ' do one thing
> else
>  ' do something else
> endif
>
> I am using VB and FW 1.1.  I'll be upgrading from 1.1 soon.

Pseudo code:

\\\
If y > Double.MaxValue / x Then
    MsgBox("Overflow")
End If
///

--
M S   Herfried K. Wagner
M V P  <URL:http://dotnet.mvps.org/>
V B   <URL:http://dotnet.mvps.org/dotnet/faqs/>
Author
27 Sep 2006 2:41 PM
AMercer
> If y > Double.MaxValue / x Then
>     MsgBox("Overflow")
> End If

Thanks Herfried, very sharp.  I've adapted it to long and integer which is
my problem area.  Thanks also to Andrew Morton, but Herfried's approach seems
better.
Author
27 Sep 2006 3:19 PM
Andrew Morton
AMercer wrote:
>> If y > Double.MaxValue / x Then
>>     MsgBox("Overflow")
>> End If
>
> Thanks Herfried, very sharp.  I've adapted it to long and integer
> which is my problem area.  Thanks also to Andrew Morton, but
> Herfried's approach seems better.

Don't forget you also have to check for x > Double.MaxValue / y and also for
the case where either x or y (but not both) is negative and then reverse the
inequality check. Or use the Math.Abs() values.

And check for zero before attempting to divide by it.

Andrew
Author
27 Sep 2006 1:59 PM
Andrew Morton
AMercer wrote:
> I want to detect if multiplying two integers or two longs will cause
> an overflow without using a try-catch block.  I know how to do it with
> try-catch, but the performance hit is too much.  I want an efficient
> test so

if log(a)+log(b)>precalculatedLogOfBiggestNumber then
    ' too big
else
    ' OK
end if

As for efficiency, you'll have to test it.

Andrew
Author
27 Sep 2006 2:08 PM
Andrew Morton
Andrew Morton wrote:
> AMercer wrote:
>> I want to detect if multiplying two integers or two longs will cause
>> an overflow without using a try-catch block.  I know how to do it
>> with try-catch, but the performance hit is too much.  I want an
>> efficient test so
>
> if log(a)+log(b)>precalculatedLogOfBiggestNumber then
>    ' too big
> else
>    ' OK
> end if

Oops!

if log(abs(a))+log(abs(b))>precalculatedLogOfBiggestNumber then
    ' too big
else
    ' OK
end if

Andrew