Re: how to use recursive algorithm to determine all of the arrangements?
- From: Patricia Shanahan <pats@xxxxxxx>
- Date: Tue, 09 May 2006 15:44:16 GMT
Oliver Wong wrote:
<opalpa@xxxxxxxxx> wrote in message news:1147153506.499376.122360@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
btw, How do I check for overflow on multiplication in Java (or any
other arithmetic operation)?
The simplest way is to check for integer overflow is to do the multiplication in floating point precision, and check if the result is larger than what would fit in whatever primitive type you're trying to store the value in.
e.g.
<pseudocode>
int a, b, result;
double temp = (double)a * (double)b;
if (temp > max_int_value) {
handleOverFlow();
} else {
result = (int)temp;
}
</pseudocode>
In the case of int, you could use long instead of double.
- Oliver
Note that this should only be used, as written, for int and smaller
types, not long. It depends on all int values being exactly
representable as doubles, so that if there is no overflow temp does
contain the exact answer.
This program:
public class TestMult {
public static void main(String[] args) {
long a = 0x0fffffffffffffffL;
long b = 3;
long result=0;
double temp = (double)a * (double)b;
if (temp > Long.MAX_VALUE) {
handleOverFlow();
System.exit(3);
} else {
result = (long)temp;
}
System.out.println("result="+result+" correct answer="+a*b);
}
private static void handleOverFlow() {
System.out.println("Overflow detected");
}
}
prints:
result=3458764513820540928 correct answer=3458764513820540925
For long, using BigInteger instead of double would be slower but more
reliable.
Patricia
.
- Follow-Ups:
- Re: how to use recursive algorithm to determine all of the arrangements?
- From: Chris Uppal
- Re: how to use recursive algorithm to determine all of the arrangements?
- References:
- how to use recursive algorithm to determine all of the arrangements?
- From: index
- Re: how to use recursive algorithm to determine all of the arrangements?
- From: opalpa@xxxxxxxxx opalinski from opalpaweb
- Re: how to use recursive algorithm to determine all of the arrangements?
- From: Oliver Wong
- how to use recursive algorithm to determine all of the arrangements?
- Prev by Date: Re: java with native GUI appearance?
- Next by Date: Re: Catching Throwable
- Previous by thread: Re: how to use recursive algorithm to determine all of the arrangements?
- Next by thread: Re: how to use recursive algorithm to determine all of the arrangements?
- Index(es):
Relevant Pages
|
|