如何在Java中将BigInteger除以双倍? [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

标题说明了一切:如何在Java中将BigInteger除以浮点数?我不需要除法的小数部分,可以将其舍入或截断(但我会感兴趣的是哪一个适用)。

“显而易见”甚至无法编译:

BigInteger x = BigInteger.valueOf(73).pow(42);
BigInteger y = x.divide(Math.PI); // The method divide(BigInteger) in the type BigInteger is
                                  // not applicable for the arguments (double)
System.out.println(y);

我希望这个工作:

BigInteger y = new BigDecimal(x).divide(BigDecimal.valueOf(Math.PI)).toBigInteger();

不幸的是,它给出了ArithmeticException:非终止十进制扩展;没有确切的可表示的小数结果。这对π来说是正确的,当然......

当然,这个有用,但是太慢了......

BigInteger y = BigInteger.valueOf(-1);
BigDecimal σ = BigDecimal.ZERO;
while(σ.compareTo(new BigDecimal(x)) < 0) {
    y = y.add(BigInteger.ONE);
    σ = σ.add(BigDecimal.valueOf(Math.PI));
}

什么是正确的,规范的方式?

java math biginteger
1个回答
3
投票

你必须添加RoundingMode分割功能,否则java不知道如何围绕分区并给你ArithmeticException

BigInteger y = new BigDecimal(y).divide(BigDecimal.valueOf(Math.PI), RoundingMode.HALF_UP).toBigInteger();

所有Rounding类型都在上面的文档链接中得到了很好的解释。

© www.soinside.com 2019 - 2024. All rights reserved.