overflow detection without try-catch

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

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.
 
AMercer said:
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
///
 
AMercer said:
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
 
Andrew said:
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
 
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.
 
AMercer said:
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
 
Back
Top