What are the limits of BigDecimal and BigInteger? [duplicate]
Asked Answered
H

2

2

I was multiplying very two huge BigIntegervalues in a program. It failed. What are the limits of BigInteger and BigDecimal ?

Holcman answered 30/7, 2013 at 11:36 Comment(3)
Are you sure the NumberFormatException occurs during multiplication? Can you show your code? The problem might be elsewhere.Nahshon
multiply does not throw NumberFormatException. Show your code...Breeching
We really should instantly delete questions where someone reports an exception without posting the stacktrace. However, it's still better than just "it failed.".Scalade
W
6

You won't get NumberFormatException multiplying large numbers. If the number produced is too large, you will get a cryptic NegativeArraySizeException as the size of the array overflows.

You are more likely to get an out of memory error.

The limit is 32 * 2^32-1 bits for BigInteger or about 2^(4 billion).

You can get a NumberFormatException if you

  • create a BigInteger from an empty byte[]
  • use a signum < -1 or > +1
  • try to parse a number in base >36 or < 2
  • have a string with illegal digits.

When you get an exception you should also look at the message and the stack trace as this usually gives you the real cause.

Winger answered 30/7, 2013 at 11:37 Comment(1)
Does that mean you actually can have "negative" array indexes? Otherwise, it would be 2^31-1Scalade
E
1

there shouldn't be a limit, except for memory, but maybe there is, according to the implementation of the class (for example, some fields there might be int or long).

Edition answered 30/7, 2013 at 11:48 Comment(4)
As Peter pointed out, the limit is an indirect one, that results from the type for array indexing: Int. Because Big... is backed by int[], you cannot have an index like 8888888888888888888888888888888888. (But you'll likely get OutOfMemory before).Scalade
is it because the max number of items for the array, which is the RAM memory (ok divided by 4, which is the size of int) ? wonder how much RAM is needed to hold this amount.Edition
On a machine with 64bit address space, you could have an int array of size 2^62. (and nothing else) But long before this limit, Java kicks in, because you can't use long to index an array.Scalade
so the implementation limit is what peter has written (and he decreased it by 1 because of negative numbers) ?Edition

© 2022 - 2024 — McMap. All rights reserved.