Reputation: 8473
I am implementing a pow function in Java, and I am wondering how do we deal with Integer.MIN_VALUE as a exponent ? Do we just treat it as a special case ?
Because I tried to compare the result with the standard Java.lang.Math API and I get a couple different result. The following is the list of comparison
//this will print "1.0 vs 0.0"
System.out.println(pow(2,Integer.MIN_VALUE) + " vs " + Math.pow(2,Integer.MIN_VALUE));
//this will print "1.0 vs 1.0"
System.out.println(pow(1,Integer.MIN_VALUE) + " vs " + Math.pow(1,Integer.MIN_VALUE));
public double pow(double base, int exp){
double result = 1.0;
boolean pos = false;
if(exp == 0) return result;
if(exp > 0){
pos = true;
exp *= -1;
}
while(exp > 0){
if((exp & 1) == 1){
result *= base;
}
base *= base;
exp /= 2;
}
if(!pos){
result = 1/result;
}
return result;
}
So I am wondering if Integer.MIN_VALUE is a special case where I have to have a if statement for checking it.
if(exp == Integer.MIN_VALUE && base > 1) return 0.0;
Upvotes: 2
Views: 650
Reputation: 312
Well, the real issue is that, since the sign doesn't flip on the MIN_VALUE, the sign cascades to the exp/2. and the 'negative power' case applies. If we split it, it's easier:
public double myPow(double x, int n) {
double result = 1.00000;
boolean negative = false;
if(n <0) {
negative = true;
n= -n;
}
result=power(x,n);
if(negative) {
result = 1/result;
}
return result;
}
private double power(double a, int n) {
if(n ==0 || a==1) return 1;// a^0 = 1, 1^n = 1
double x=power(a,n/2);
if(n%2 == 0) return x*x;
else return a*x*x;
}
Upvotes: 0
Reputation: 60788
On my system I have
-2147483648
2147483647
For Integer.MIN_VALUE
and Integer.MAX_VALUE
respectively. So you should see the problem in the line
exp *= -1;
Upvotes: 0
Reputation: 198221
Yeah, you've got the problem that Integer.MIN_VALUE * -1 == Integer.MIN_VALUE
. You could either special-case it, or you could deal with it another way. Indeed, one possible solution would be to make exp
negative when it's positive, instead of the other way around; you'd just use -exp
instead of exp
.
Upvotes: 0
Reputation: 18434
Based on this line:
exp *= -1;
it seems that it might have to be a special case. There are certainly ways to implement this without that special case, but because -1 * Integer.MIN_VALUE
cannot be stored in an int, you will get a bug if you do not handle it separately.
Upvotes: 2