在 Java 中使用 BigDecimal(或另一个 class)获得更高的精度

Getting much higher precision with BigDecimal (or another class) in Java

我想计算具有任意长十进制值的数字(假设我想为特定数字取 100 位十进制数字)。

//Take the square root of 2 for 100 digits in total.
public class Main {
    public static void main(String[] args) {
        BigDecimal root2 = new BigDecimal(Math.pow(2, 0.5));
        root2 = root2.setScale(99, BigDecimal.ROUND_HALF_UP);
        System.out.println(root2);
    }
}

这个程序输出:

1.414213562373095145474621858738828450441360473632812500000000000000000000000000000000000000000000000

在字节存储方面有初学者背景,我意识到这里的问题要么是输出格式,要么是我仍然没有得到我正在寻找的精度,因为它没有使用我期待它的记忆。有什么建议么?精度能达到这么高吗?我不反对转向 Mathematica。

澄清一下:我正在尝试获得 100 位数字的完整精度(零不属于此处)。

这里解释了为什么您正在做的事情不起作用。

Math.pow()returns一个double。因此,您的代码使用 double 提供的精度计算值,然后从该 double 创建一个 BigDecimal。设置大小数的精度为时已晚,因为它只有双精度作为输入。

所以您不能将 Math.pow() 用于您的目的。相反,您需要找到另一个进行任意精度计算的库。

参考这个问题了解更多:Java's BigDecimal.power(BigDecimal exponent): Is there a Java library that does it?