如何获得最大的BigDecimal值
如何获得 BigDecimal 变量可以容纳的最大可能值? (最好以编程方式,但硬编码也可以)
编辑
好吧,刚刚意识到没有这样的事情,因为 BigDecimal 是任意精度。所以我最终得到了这个,它对于我的目的来说足够大了:BigDecimal my = BigDecimal.valueOf(Double.MAX_VALUE)
How can I get the largest possible value of a BigDecimal variable can hold? (Preferably programmatically, but hardcoding would be ok too)
EDIT
OK, just realized there is no such thing since BigDecimal is arbitrary precision. So I ended up with this, which is sufficiently big for my purpose:BigDecimal my = BigDecimal.valueOf(Double.MAX_VALUE)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它是一个任意的精度等级,它会变得像你想要的那样大,直到你的计算机耗尽内存。
Its an arbitrary precision class, it will get as large as you'd like until your computer runs out of memory.
查看源 BigDecimal 将其存储为带有基数的 BigInteger,
并且从 BigInteger
所以最大的 BigDecimal 将是,
您可以弄清楚如何设置它。 :P
[编辑]所以只是为了计算一下,
在二进制中,
(2^35)-2 1(我认为?)
在2的补码
01111111111111111...直到你的RAM填满。
Looking at the source BigDecimal stores it as a BigInteger with a radix,
and from BigInteger
So the Largest BigDecimal would be,
You can figure out how to set that. :P
[Edit] So just to calculate that,
In binary that's,
(2^35)-2 1's (I think?)
in 2's complement
01111111111111111...until your RAM fills up.
如果有足够的 RAM,该值大约为:
2240*10232
(这绝对是一个几个数量级,但相对而言,这是一个非常精确的估计。)
Given enough RAM, the value is approximately:
2240*10232
(It's definitely out by a few orders of magnitude but in relative terms it's a very precise estimate.)
您可以表示 2^2147483647-1,但是在此值之后,某些方法将无法按预期工作。它有 646456993 位数字。
打印
但是
是
因为位数溢出。
BigDecimal.MAX_VALUE 足够大,您不需要检查它。
You can represent 2^2147483647-1 however after this value some methods do not work as expected. It has 646456993 digits.
prints
however
prints
as there is an overflow in the number of bits.
BigDecimal.MAX_VALUE is large enough that you shouldn't need to check for it.
您可以在大小中存储 Integer.MAX_VALUE + 1 个整数,因为数组从零开始计数。所有这些整数都是 32 位,因为它们都是无符号处理的。所以位精度是
32*2147483648 = 68719476736 位(=8589934592Byte=8GiB=8,6GB)。
要获得小数精度,您必须将位精度乘以 log10(2),这样您将获得 20686623783 个完整的十进制数字,比字符串可以存储的多 4 倍多。
现在,您可以将 10 与此位数相减,然后减去 1 以获得最大 BigDecimal 值,但不要尝试使用 BigDecimal 本身来计算它。 ;)
但现在的问题是……什么是第一位的?方法 . precision() 仅限于 Integer.MAX_VALUE 或我计算的精度?
You can store Integer.MAX_VALUE + 1 integers in the magnitude, because arrays count from zero. All those integers got 32 bits, because they're all handled unsigned. So the precision in bits is
32*2147483648 = 68719476736 Bits (=8589934592Byte=8GiB=8,6GB).
To get the precision in Decimals, you'll have to multiply the precision in Bits with log10(2) so you'll get 20686623783 full decimal digits, way over 4 times more, than a String can store.
Now you can pow 10 with this amount of digits and subtract 1 to get the maximal BigDecimal value, but don't try to calculate it with BigDecimal itself. ;)
But now the question is... What comes first? The method .precision(), which is limited to Integer.MAX_VALUE or my calculated precision?