wasp256 wasp256 - 5 months ago 9
Java Question

Figure out if exponent is above long threshold before calculation

I'm using the math library in combination with the JexlEngine to calculate different equations. In this equations I also have the

pow
function. The problem is that when I have huge numbers like
math.pow(99999, 10000)
, jexl tries to evaluate it and that takes a lot of time and CPU usage. The evaluation should not be done if the solution exceeds the max Long value. Is there a way to find out before evaluating the power if it is bigger then a max Long?

Answer

You can compare the exponent to

double base = 99999;
double maxExp = Math.log(Long.MAX_VALUE)/Math.log(base);

if the power is above maxExp, you will get an overflow.