BigDecimal.divide 期间抛出 ArithmeticException

发布于 2024-08-31 03:43:25 字数 1609 浏览 13 评论 0原文

我认为 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, an ArithmeticException 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

做个ˇ局外人 2024-09-07 03:43:25

如果这不是正确答案,我们可以用什么来进行财务计算中的精确除法? (我的意思是,我没有金融专业,但他们仍然使用除法,对吧???)。

当时我还在上小学1,他们告诉我,当你除以 1 除以 3 时,你会得到 0.33333...即一个循环小数。以十进制形式表示的数字除法并不精确。事实上,对于任何固定基数,都会有一些分数(一个整数除以另一个整数的结果)无法准确地表示为该基数中的有限精度浮点数。 (该数字将有一个循环部分......)

当您进行涉及除法的财务计算时,您必须考虑如何处理循环分数。您可以将其向上或向下舍入,或到最接近的整数,或其他数字,但基本上您不能就忘记这个问题。

BigDecimal javadoc 是这样说的:

BigDecimal 类使用户能够完全控制舍入行为。如果没有指定舍入模式,无法表示准确的结果,则抛出异常;否则,可以通过向运算提供适当的 MathContext 对象来执行所选精度和舍入模式的计算。

换句话说,您有责任告诉 BigDecimal 如何进行舍入操作。

编辑 - 回应OP的这些后续行动。

BigDecimal 如何检测无限循环小数?

它没有明确检测循环小数。它只是检测某些操作的结果无法使用指定的精度精确表示;例如,为了准确表示,小数点后需要太多数字。

它必须跟踪并检测股息周期。它可以选择以另一种方式处理这个问题,通过标记重复部分的位置等。

我想可以指定 BigDecimal 来准确地表示重复的小数;即作为 BigRational 类。然而,这会使实现更加复杂并且使用起来更加昂贵2。由于大多数人希望数字以十进制显示,因此此时会再次出现小数重复出现的问题。

最重要的是,这种额外的复杂性和运行时成本对于 BigDecimal 的典型用例来说是不合适的。这包括财务计算,其中会计惯例不允许您使用循环小数。


1 - 这是一所优秀的小学。您可能在高中就学过这一点。

2 - 要么尝试删除除数和被除数的公因数(计算成本昂贵),要么允许它们无限制地增长(空间使用和计算成本昂贵)对于后续操作来说成本高昂)。

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???).

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:

The BigDecimal class gives its user complete control over rounding behavior. If no rounding mode is specified and the exact result cannot be represented, an exception is thrown; otherwise, calculations can be carried out to a chosen precision and rounding mode by supplying an appropriate MathContext object to the operation.

In other words, it is your responsibility to tell BigDecimal what to do about rounding.

EDIT - in response to these followups from the OP.

How does BigDecimal detect infinite recurring decimal?

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.

It must keep track of and detect a cycle in the dividend. It COULD HAVE chosen to handle this another way, by marking where the recurring portion is, etc.

I suppose that BigDecimal could have been specified to represent a recurring decimal exactly; i.e. as a BigRational 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).

下壹個目標 2024-09-07 03:43:25

该类是 BigDecimal 而不是 BigFractional。从您的一些评论来看,您似乎只是想抱怨有人没有将所有可能的数字处理算法构建到此类中。金融应用程序不需要无限小数精度;只是达到所需精度的完全准确的值(通常为 0、2、4 或 5 位小数)。

实际上我处理过许多使用double的金融应用程序。我不喜欢它,但这就是它们的编写方式(也不是用 Java 编写的)。当存在汇率和单位换算时,就可能存在舍入和碰伤问题。 BigDecimal 消除了后者,但仍然有前者用于除法。

The class is BigDecimal not BigFractional. 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.

薔薇婲 2024-09-07 03:43:25

如果您想使用小数而不是有理数,并且在最终舍入之前需要精确的算术运算(舍入到分或其他值),这里有一个小技巧。

您始终可以操纵您的公式,以便只有一个最终除法。这样您在计算过程中就不会失去精度,并且始终会得到正确舍入的结果。例如

a/b + c

等于

(a + bc) / b.

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

a/b + c

equals

(a + bc) / b.
白鸥掠海 2024-09-07 03:43:25

顺便说一句,我真的很感激
来自合作过的人的见解
财务软件。我经常听到
BigDecimal 比 double 更受提倡

在财务报告中,我们始终使用规模 = 2 的 BigDecimal 和 ROUND_HALF_UP,因为报告中的所有打印值都必须产生可重现的结果。如果有人使用简单的计算器检查这一点。

在瑞士,他们四舍五入到 0.05,因为他们不再拥有 1 或 2 个 Rappen 硬币。

By the way, I'd really appreciate
insight from people who've worked with
financial software. I often heard
BigDecimal being advocated over double

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.

薆情海 2024-09-07 03:43:25

您应该更喜欢使用 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.

作妖 2024-09-07 03:43:25

有必要吗

a=1/3;
b=a*3;

resulting in

b==1;

金融体系 ?我想不是。在金融系统中,定义了在进行计算时必须使用哪种轮次模式和规模。在某些情况下,回合模式和比例在法律中定义。所有组件都可以依赖这样定义的行为。返回 b==1 将失败,因为它无法满足指定的行为。这在计算价格等时非常重要。

它就像用二进制数字表示浮点数的 IEEE 754 规范一样。组件不得在不丢失信息的情况下优化“更好”的表示,因为这会破坏契约。

Is there a need for

a=1/3;
b=a*3;

resulting in

b==1;

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.

一念一轮回 2024-09-07 03:43:25

要除法保存,您必须设置 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);

萌无敌 2024-09-07 03:43:25

我承认 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?

半仙 2024-09-07 03:43:25

请注意,我们使用的是计算机...计算机有大量内存,而精度则需要内存。因此,当您想要无限精度时,您需要
(无限 * 无限) ^ (无限 * Integer.MAX_VALUE) 太字节内存...

我知道 1 / 30.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 is 0.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 have 1. But I don't think Java has something like that...
Maybe you have to win the Nobel Price for writing something doing that. ;-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文