Java で pow 関数を実装していますが、指数として Integer.MIN_VALUE をどのように処理すればよいのでしょうか? それを特別なケースとして扱いますか?
結果を標準の Java.lang.Math API と比較しようとしたため、いくつかの異なる結果が得られました。以下、比較リスト
//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;
}
したがって、Integer.MIN_VALUE は、それをチェックするために if ステートメントが必要な特殊なケースであるかどうか疑問に思っています。
if(exp == Integer.MIN_VALUE && base > 1) return 0.0;