BigDecimal.divide 期间抛出 ArithmeticException
我认为 java.math.BigDecimal
被认为是解决使用十进制数执行无限精度算术的需要的 The Answer™。
考虑以下代码片段:
import java.math.BigDecimal;
//...
final BigDecimal one = BigDecimal.ONE;
final BigDecimal three = BigDecimal.valueOf(3);
final BigDecimal third = one.divide(three);
assert third.multiply(three).equals(one); // this should pass, right?
我希望 assert
通过,但实际上执行甚至没有到达那里:one.divide(third)
导致 ArithmeticException< /code> 被抛出!
Exception in thread "main" java.lang.ArithmeticException:
Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide
事实证明,此行为已明确记录在 API< /a>:
在
除
的情况下,精确的商可以有无限长的小数展开;例如,1 除以 3。如果商具有非终止小数展开式,并且指定运算返回精确结果,则会引发ArithmeticException
。否则,将返回除法的确切结果,就像其他操作一样。
进一步浏览 API,人们发现实际上有各种 divide
重载来执行不精确除法,即:
final BigDecimal third = one.divide(three, 33, RoundingMode.DOWN);
System.out.println(three.multiply(third));
// prints "0.999999999999999999999999999999999"
当然,现在明显的问题是“有什么意义? ???”。我认为当我们需要精确算术(例如金融计算)时,BigDecimal
是解决方案。如果我们甚至不能精确地除
,那么这有什么用呢?它实际上是否具有通用用途,还是仅在非常小众的应用程序中有用,幸运的是您根本不需要划分
?
如果这不是正确答案,我们可以使用什么来进行财务计算中的精确除法? (我的意思是,我没有金融专业,但他们仍然使用除法,对吧???)。
I thought java.math.BigDecimal
is supposed to be The Answer™ to the need of performing infinite precision arithmetic with decimal numbers.
Consider the following snippet:
import java.math.BigDecimal;
//...
final BigDecimal one = BigDecimal.ONE;
final BigDecimal three = BigDecimal.valueOf(3);
final BigDecimal third = one.divide(three);
assert third.multiply(three).equals(one); // this should pass, right?
I expect the assert
to pass, but in fact the execution doesn't even get there: one.divide(three)
causes ArithmeticException
to be thrown!
Exception in thread "main" java.lang.ArithmeticException:
Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide
It turns out that this behavior is explicitly documented in the API:
In the case of
divide
, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3. If the quotient has a non-terminating decimal expansion and the operation is specified to return an exact result, anArithmeticException
is thrown. Otherwise, the exact result of the division is returned, as done for other operations.
Browsing around the API further, one finds that in fact there are various overloads of divide
that performs inexact division, i.e.:
final BigDecimal third = one.divide(three, 33, RoundingMode.DOWN);
System.out.println(three.multiply(third));
// prints "0.999999999999999999999999999999999"
Of course, the obvious question now is "What's the point???". I thought BigDecimal
is the solution when we need exact arithmetic, e.g. for financial calculations. If we can't even divide
exactly, then how useful can this be? Does it actually serve a general purpose, or is it only useful in a very niche application where you fortunately just don't need to divide
at all?
If this is not the right answer, what CAN we use for exact division in financial calculation? (I mean, I don't have a finance major, but they still use division, right???).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
当时我还在上小学1,他们告诉我,当你除以 1 除以 3 时,你会得到 0.33333...即一个循环小数。以十进制形式表示的数字除法并不精确。事实上,对于任何固定基数,都会有一些分数(一个整数除以另一个整数的结果)无法准确地表示为该基数中的有限精度浮点数。 (该数字将有一个循环部分......)
当您进行涉及除法的财务计算时,您必须考虑如何处理循环分数。您可以将其向上或向下舍入,或到最接近的整数,或其他数字,但基本上您不能就忘记这个问题。
BigDecimal javadoc 是这样说的:
换句话说,您有责任告诉 BigDecimal 如何进行舍入操作。
编辑 - 回应OP的这些后续行动。
它没有明确检测循环小数。它只是检测某些操作的结果无法使用指定的精度精确表示;例如,为了准确表示,小数点后需要太多数字。
我想可以指定
BigDecimal
来准确地表示重复的小数;即作为 BigRational 类。然而,这会使实现更加复杂并且使用起来更加昂贵2。由于大多数人希望数字以十进制显示,因此此时会再次出现小数重复出现的问题。最重要的是,这种额外的复杂性和运行时成本对于 BigDecimal 的典型用例来说是不合适的。这包括财务计算,其中会计惯例不允许您使用循环小数。
1 - 这是一所优秀的小学。您可能在高中就学过这一点。
2 - 要么尝试删除除数和被除数的公因数(计算成本昂贵),要么允许它们无限制地增长(空间使用和计算成本昂贵)对于后续操作来说成本高昂)。
Then I was in primary school1, they taught me that when you divide by 1 by 3 you get a 0.33333... i.e. a recurring decimal. Division of numbers represented in decimal form is NOT exact. In fact for any fixed base there will be fractions (the result of dividing one integer by another) that cannot be represented exactly as a finite precision floating point number in that base. (The number will have a recurring part ...)
When you do financial calculations involving division, you have to consider the what to do with a recurring fraction. You can round it up, or down, or to the nearest whole number, or something else, but basically you cannot just forget about the issue.
The BigDecimal javadoc says this:
In other words, it is your responsibility to tell BigDecimal what to do about rounding.
EDIT - in response to these followups from the OP.
It does not explicitly detect the recurring decimal. It simply detects that the result of some operation cannot be represented exactly using the specified precision; e.g. too many digits are required after the decimal point for an exact representation.
I suppose that
BigDecimal
could have been specified to represent a recurring decimal exactly; i.e. as aBigRational
class. However, this would make the implementation more complicated and more expensive to use2. And since most people expect numbers to be displayed in decimal, and the problem of recurring decimal recurs at that point.The bottom line is that this extra complexity and runtime cost would be inappropriate for typical use-cases for
BigDecimal
. This includes financial calculations, where accounting conventions do not allow you to use recurring decimals.1 - It was an excellent primary school. You may have been taught this in high school.
2 - Either you try to remove common factors of the divisor and dividend (computationally expensive), or allow them to grow without bounds (expensive in space usage and computationally expensive for subsequent operations).
该类是
BigDecimal
而不是BigFractional
。从您的一些评论来看,您似乎只是想抱怨有人没有将所有可能的数字处理算法构建到此类中。金融应用程序不需要无限小数精度;只是达到所需精度的完全准确的值(通常为 0、2、4 或 5 位小数)。实际上我处理过许多使用
double
的金融应用程序。我不喜欢它,但这就是它们的编写方式(也不是用 Java 编写的)。当存在汇率和单位换算时,就可能存在舍入和碰伤问题。BigDecimal
消除了后者,但仍然有前者用于除法。The class is
BigDecimal
notBigFractional
. From some of your comments it sounds like you just want to complain that someone didn't build in all possible number handling algorithms into this class. Financial apps do not need infinite decimal precision; just perfectly accurate values to the precision required (typically 0, 2, 4, or 5 decimal digits).Actually I have dealt with many financial applications that use
double
. I don't like it but that was the way they are written (not in Java either). When there are exchange rates and unit conversions then there are both the potential of rounding and bruising problems.BigDecimal
eliminates the later but there is still the former for division.如果您想使用小数而不是有理数,并且在最终舍入之前需要精确的算术运算(舍入到分或其他值),这里有一个小技巧。
您始终可以操纵您的公式,以便只有一个最终除法。这样您在计算过程中就不会失去精度,并且始终会得到正确舍入的结果。例如
等于
If you want to work with decimals, not rational numbers, and you need exact arithmetics before the final rounding (rounding to cents or something), here's a little trick.
You can always manipulate your formulas so that there's only one final division. That way you won't lose precision during calculations and you'll always get the correctly rounded result. For instance
equals
在财务报告中,我们始终使用规模 = 2 的 BigDecimal 和 ROUND_HALF_UP,因为报告中的所有打印值都必须产生可重现的结果。如果有人使用简单的计算器检查这一点。
在瑞士,他们四舍五入到 0.05,因为他们不再拥有 1 或 2 个 Rappen 硬币。
In financial reports we use alwasy BigDecimal with scale = 2 and ROUND_HALF_UP, since all printed values in a report must be lead to a reproducable result. If someone checks this using a simple calculator.
In switzerland they round to 0.05 since they no longer have 1 or 2 Rappen coins.
您应该更喜欢使用 BigDecimal 进行金融计算。四舍五入应由企业指定。例如,一笔金额(100,00 美元)必须平均分配到三个帐户中。必须有一个业务规则,哪个账户拿走额外的一分钱。
双精度浮点数不适合在金融应用中使用,因为它们无法精确表示 1 的分数(不是 2 的指数)。例如,考虑 0.6 = 6/10 = 1*1/2 + 0*1/4 + 0*1 /8 + 1*1/16 + ... = 0.1001...b
对于数学计算,您可以使用符号数字,例如存储分母和分子甚至整个表达式(例如这个数字是 sqrt(5)+3/ 4)。因为这不是 java api 的主要用例,所以你不会在那里找到它。
You should prefer BigDecimal for finance calculations. Rounding should be specified by the business. E.g. an amount (100,00$) has to be split equally across three accounts. There has to be a business rule which account takes the extra cent.
Double, floats are not approriate for use in financial applications because they can not represent fractions of 1 precisely that are not exponentials of 2. E.g. consider 0.6 = 6/10 = 1*1/2 + 0*1/4 + 0*1/8 + 1*1/16 + ... = 0.1001...b
For mathematic calculations you can use a symbolic number, e.g. storing denominator and numerator or even a whole expression (e.g. this number is sqrt(5)+3/4). As this is not the main use case of the java api you won' find it there.
有必要吗
金融体系 ?我想不是。在金融系统中,定义了在进行计算时必须使用哪种轮次模式和规模。在某些情况下,回合模式和比例在法律中定义。所有组件都可以依赖这样定义的行为。返回 b==1 将失败,因为它无法满足指定的行为。这在计算价格等时非常重要。
它就像用二进制数字表示浮点数的 IEEE 754 规范一样。组件不得在不丢失信息的情况下优化“更好”的表示,因为这会破坏契约。
Is there a need for
in financial systems? I guess not. In financial systems it is defined, which roundmode and scale has to be used, when doing calculations. In some situations, the roundmode and scale is defined in the law. All components can rely on such a defined behaviour. Returning b==1 would be a failure, because it would not fulfill the specified behaviour. This is very important when calculating prices etc.
It is like the IEEE 754 specifications for representing floats in binary digits. A component must not optimize a "better" representation without loss of information, because this will break the contract.
要除法保存,您必须设置 MATHcontext,
BigDecimal bd = new BigDecimal(12.12, MathContext.DECIMAL32).divide(new BigDecimal(2)).setScale(2, RoundingMode.HALF_UP );
To divide save, you have to set the
MATHcontext
,BigDecimal bd = new BigDecimal(12.12, MathContext.DECIMAL32).divide(new BigDecimal(2)).setScale(2, RoundingMode.HALF_UP);
我承认 Java 对分数的表示没有很好的支持,但是您必须意识到,在使用计算机时不可能保持事物完全精确。至少在这种情况下,例外情况是告诉您精度正在丢失。
据我所知,“十进制数的无限精度算术”是不会发生的。如果您必须使用小数,那么您所做的可能没问题,只需捕获异常即可。否则,快速谷歌搜索会发现一些在 Java 中处理分数的有趣资源:
http:// /commons.apache.org/math/userguide/fraction.html
http://www. merriampark.com/fractions.htm
表示Java 中的分数?
I accept that Java doesn't have great support for representing fractions, but you have to realise that it is impossible to keep things entirely precise when working with computers. At least in this case, the exception is telling you that precision is being lost.
As far as I know, "infinite precision arithmetic with decimal numbers" just isn't going to happen. If you have to work with decimals, what you're doing is probably fine, just catch the exceptions. Otherwise, a quick google search finds some interesting resources for working with fractions in Java:
http://commons.apache.org/math/userguide/fraction.html
http://www.merriampark.com/fractions.htm
Best way to represent a fraction in Java?
请注意,我们使用的是计算机...计算机有大量内存,而精度则需要内存。因此,当您想要无限精度时,您需要
(无限 * 无限) ^ (无限 * Integer.MAX_VALUE)
太字节内存...我知道
1 / 3
是0.333333...
并且应该可以将它存储在内存中,就像“一除以三”一样,然后你可以将它相乘,你应该有1
。但我不认为 Java 有这样的东西......也许你必须因为写出这样的东西而赢得诺贝尔奖。 <代码>;-)
Notice we are using a computer... A computer has a lot of ram and precision takes ram. So when you want an infinite precision you need
(infinite * infinite) ^ (infinite * Integer.MAX_VALUE)
terrabyte ram...I know
1 / 3
is0.333333...
and it should be possible to store it in ram like "one divided by three" and then you can multiply it back and you should have1
. But I don't think Java has something like that...Maybe you have to win the Nobel Price for writing something doing that.
;-)