gpt4 book ai didi

java - BigDecimal.divide(...) - 适合具有非终止扩展的商的比例

转载 作者:行者123 更新时间:2023-11-29 06:05:46 26 4
gpt4 key购买 nike

我正在使用 BigDecimal 进行一些浮点运算。如果将 5 除以 4.2,您将得到一个异常(因为结果有一个不能用 BigDecimal 表示的非终止扩展) )即

BigDecimal five = new BigDecimal("5");
BigDecimal fourPointTwo = new BigDecimal("4.2");
five.divide(fourPointTwo) // ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

我准备在这种情况下失去一些精度,所以我将使用 divide(...) 方法,它允许提供结果的比例:

five.divide(fourPointTwo, 2, RoundingMode.HALF_UP); //Fine, but obviously not 100% accurate

我应该将多大的比例传递给此方法,以便结果与我使用两个 double 执行计算一样准确?

最佳答案

来自javadocs of the BigDecimal class :

If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. The value of the number represented by the BigDecimal is therefore (unscaledValue × 10-scale).

double 的精度根据值的数量级而变化。根据this ,它使用 52 位来存储无符号尾数,因此任何可以用 52 位表示的整数都可以。这大约是 18 位十进制数字。

此外,double 使用 11 位来存储指数。所以,像小数点后 4 位这样的精度就可以了。这样,可以表示最多 52 位的任何整数乘以 2 的正幂或负幂,最多 10 位(一位是指数的符号)。除此之外,您开始失去精度。

double 的额外位存储符号。

这样,比例 18 + 4 = 22 将至少与 double 一样精确。

关于java - BigDecimal.divide(...) - 适合具有非终止扩展的商的比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8561433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com