如何获得最大的BigDecimal值

Can*_*ner 38 java math bigdecimal

如何获得BigDecimal变量的最大可能值?(最好是以编程方式,但硬编码也可以)

编辑
好了,刚才意识到没有这样的东西,因为BigDecimal是任意精度.所以我最终得到了这个,这对我的目的来说足够好了:
BigDecimal my = BigDecimal.valueOf(Double.MAX_VALUE)

ale*_*lum 39

它是一个任意的精度类,它会变得你想要的大,直到你的计算机内存不足.

  • 不正确,它仅限于Integer.MAX_VALUE字. (40认同)
  • @Adio,它使用一个int数组存储数字.在Java中,数组由int编制索引,因此最多可以包含Integer.MAX_VALUE条目.因此,最大可能的BigInteger消耗大约8GB的RAM(4个字节,一个int*2GB条目).在64位JVM中,堆大小可能是堆大小的很多倍,因此可用内存并不总是最大可能BigInteger或BigDecimal的限制因素. (24认同)
  • 安德烈,你能解释还是给我链接?“仅限于Integer.MAX_VALUE个字”是什么意思?谢谢 (2认同)

And*_*rew 13

查看源代码BigDecimal将其存储为具有基数的BigInteger,

private BigInteger intVal;
private int scale;
Run Code Online (Sandbox Code Playgroud)

来自BigInteger

/** All integers are stored in 2's-complement form.
63:    * If words == null, the ival is the value of this BigInteger.
64:    * Otherwise, the first ival elements of words make the value
65:    * of this BigInteger, stored in little-endian order, 2's-complement form. */
66:   private transient int ival;
67:   private transient int[] words;
Run Code Online (Sandbox Code Playgroud)

所以最大的BigDecimal会是,

ival = Integer.MAX_VALUE;
words = new int[Integer.MAX_VALUE]; 
scale = 0;
Run Code Online (Sandbox Code Playgroud)

你可以弄清楚如何设置它.:P

[编辑]所以只是为了计算,在二进制文件中,

(2 ^ 35)-2 1(我觉得?)

在2的补充

01111111111111111 ...直到你的RAM填满.


biz*_*lop 9

给定足够的RAM,值大约为:

2 2 40*10 2 32

(这绝对是几个数量级,但相对而言,这是一个非常精确的估计.)


Pet*_*rey 7

您可以表示 2^2147483647-1 但是在此值之后,某些方法无法按预期工作。它有 646456993 位数字。

System.out.println(BigInteger.ONE.shiftLeft(Integer.MAX_VALUE)
                                 .subtract(BigInteger.ONE).bitLength());
Run Code Online (Sandbox Code Playgroud)

印刷

2147483647
Run Code Online (Sandbox Code Playgroud)

然而

System.out.println(BigInteger.ONE.shiftLeft(Integer.MAX_VALUE).bitLength());
Run Code Online (Sandbox Code Playgroud)

印刷

-2147483648
Run Code Online (Sandbox Code Playgroud)

因为位数溢出。

BigDecimal.MAX_VALUE 足够大,您不需要检查它。