I am trying to perform a Math.pow() operation to find 10 to the power of a long number. The result is expected to be quite large, and therefore, I am storing it in a BigInteger. I tried the below:
tempBigInt = java.math.BigDecimal.valueOf(Math.pow(10, i)).toBigInteger();
I am running this through a loop where 'i' keeps increasing until a certain condition is met. This code works fine, except when it calculates Math.pow(10, 23). Strangely, this is the only value that comes out wrong, thereby making my final result to be incorrect.
I tried verifying this through my IDE as well, and it seems like Java doesn't like Math.pow(10, 23). Could be a bug. If anyone knows what's causing this unusual behavior, could you please explain, and probably provide a better and bug-free way of implementing this line of code? [tempBigInt is a BigInteger, and i is a long]
Math.pow
returns a double
. A double
is only 64 bits in size. It can represent big numbers, but not accurately. Converting that to a BigDecimal and then to a BigInteger is not going to make it more accurate.
Use the pow
method on BigInteger
itself to do what you want:
BigInteger goodOne = BigInteger.TEN.pow(23);