Wie bereits erwähnt, ermöglicht die Verwendung eines "größeren" Datentyps die Validierung und einfache Berechnung - aber was ist, wenn kein größerer Datentyp ist?
Sie Test mathematisch kann, wenn es zu einem Überlauf führen würde:
Wenn Sie base^power
sind caluclating, bedeutet, dass base^power = result
- es bedeutet auch power-th square of result = base
- das maximale Ergebnis ist Integer.MAX_VALUE
erlaubt - sonst Sie einen Überlauf haben.
Die power-th root
einer beliebigen Anzahl größer als Null wird IMMER innerhalb des Bereichs liegen ]0,number]
- keine Chance Arithmetik überläuft.
Also - wir vergleichen die base
Sie mit dem power-th root
von Integer.MAX_VALUE
verwenden - ist base
GRÖSSER? Dann werden Sie einen Überlauf auftreten - sonst würde es bleiben unten (oder gleich zu) das Ergebnis der Integer.MAX_VALUE
private static double powSafe(double base, int pow){
//this is the p-th root of the maximum integer allowed
double root = Math.pow(Integer.MAX_VALUE, 1.0/pow);
if (root < base){
throw new ArithmeticException("The calculation of " + base + "^" + pow + " would overflow.");
}else{
return Math.pow(base, pow);
}
}
public static void main(String[] argv)
{
double rootOfMaxInt = Math.pow(Integer.MAX_VALUE, 1.0/2);
try{
//that should be INTEGER.MAX_VALUE, so valid.
double d1 = powSafe(rootOfMaxInt, 2);
System.out.println(rootOfMaxInt + "^2 = " + d1);
}catch (ArithmeticException e){
System.out.println(e.getMessage());
}
try{
//this should overflow cause "+1"
double d2 = powSafe(rootOfMaxInt +1, 2);
System.out.println("("rootOfMaxInt + "+ 1)^2 = " + d1);
}catch (ArithmeticException e){
System.out.println(e.getMessage());
}
double the67thRootOfMaxInt = Math.pow(Integer.MAX_VALUE, 1.0/67);
try{
//and so, it continues
double d3 = powSafe(the67thRootOfMaxInt, 67);
System.out.println(the67thRootOfMaxInt + "^67 = " + d3);
double d4 = powSafe(the67thRootOfMaxInt +1, 67);
System.out.println("(" + the67thRootOfMaxInt + " + 1)^67 = " + d3);
}catch (ArithmeticException e){
System.out.println(e.getMessage());
}
}
führt zu
46340.950001051984^2 = 2.147483647E9
The calculation of 46341.950001051984^2 would overflow.
1.3781057199632372^67 = 2.1474836470000062E9
The calculation of 2.378105719963237^67 would overflow.
Hinweis, dass es Unschärfen Ursache doppelt erscheinen nicht unendlich ist Präzision, die bereits den Ausdruck 2nd square of Integer.Max_Value
abschneidet, weil Integer.Max_value
ungerade ist.
können Sie Ihre Basis und Power zu 'BigDecimals' konvertieren, und dann Ergebnis mit' Integer.MAX_VALUE' vergleichen – user902383
@ user902383 während Sie absolut Recht haben für den Fall 'int' (wo Sie' bigint' verwenden können, um zu validieren) es wäre interessant, wie du das dann für 'bigints' handhaben kannst? – dognose
Alternativ können Sie Integer.MAX_VALUE durch Base teilen, und wenn Ihr Ergebnis größer als dieser Wert ist, wird der Rückgabefehler – user902383