I know that java.lang.Math provides a set of static methods to perform some operations (sum
, difference
, multiply
, increment
, decrement
, negate
, toInt
), throwing an ArithmeticException
on overflow.
Is there something similar for power?
To check for Integer overflow, we need to check the Integer. MAX_VALUE, which is the maximum value of an integer in Java. Let us see an example wherein integers are added and if the sum is more than the Integer. MAX_VALUE, then an exception is thrown.
Write a “C” function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in “result” and returns 0. Otherwise it returns -1. The solution of casting to long and adding to find detecting the overflow is not allowed.
If it overflows, it goes back to the minimum value and continues from there. If it underflows, it goes back to the maximum value and continues from there. If you think that this may occur more than often, then consider using a datatype or object which can store larger values, e.g. long or maybe java. math.
JVM does not throw any exception in case Overflow or underflow occurs, it simply changes the value. Its programmer responsibility to check the possibility of an overflow/underflow condition and act accordingly.
No, there is nothing equivalent for pow
built into Java. (The only pow
methods built into Java are Math.pow
, which accepts doubles and does not overflow in the same way integers do, and BigInteger.pow
, which does not overflow because BigInteger
s can be arbitrarily large.)
If third-party libraries are acceptable, though, Guava has e.g. IntMath.checkedPow
, which does what you're looking for.
As Chirag said, integers throw exceptions when they overflow while doubles don't. Not to get too specific but, basically, doubles in memory are stored very similarly to scientific notation, in that they are some integer * 2^(some power), and thus never really overflow but multiply by such a large or small 2^(some power) that they completely lose their precision. So you can instead think of double overflow as when they completely lose their precision and are printed as either Infinity
or -Infinity
.
So, you will need to manually check that an overflow has occurred by checking if the resulting value is Double.POSITIVE_INFINITY
or Double.NEGATIVE_INFINITY
.
Here is some sample code to show what I mean:
public static void main(String[] args) throws Exception
{
double a = Double.MAX_VALUE; // highest possible double
double b = Double.MAX_VALUE; // highest possible double
if (Math.pow(a, b) == Double.POSITIVE_INFINITY || Math.pow(a, b) == Double.NEGATIVE_INFINITY)
{
throw new ArithmeticException("Double Overflow");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With