问题描述
这不可能吗?应该简化分数以避免不终止小数扩展"公共类方法{
Is this not possible? Should the fraction be simplified to avoid 'non terminating decimal expansion'public class method {
BigDecimal a = new BigDecimal("1");
BigDecimal b = new BigDecimal ("22140");
BigDecimal c;
void cal () {
System.out.println(c=a.divide(b));
}
推荐答案
我假设您正在询问是否可以将1/22140完全表示为 BigDecimal
.答案是否定的. BigDecimal
类不能表示具有非终止十进制扩展数的值,并且也没有简化允许它的方程式.
I assume you are asking if it is possible to represent 1 / 22140 exactly as a BigDecimal
. The answer to that is No. The BigDecimal
class cannot represent values with a non-terminating decimal expansion, and there is no simplification of the equation that will allow it.
问:为什么?
A:基本上是数学.1/22140不能表示为m * 10 ,其中m和s是有限整数.
A: Basically, mathematics. 1 / 22140 cannot be represented as m * 10 where m and s are finite integers.
有两种实用的替代方法:
There are two practical alternative approaches:
-
进行除法运算时,可以使用
MathContext
自变量来指定如何对数字取整以及保持多少精度;例如
You can use a
MathContext
argument when you do the division to specify how to round the number and how much precision to keep; e.g.
c = a.divide(b, new MathContext(100, RoundingMode.HALF_UP));
这将计算精度为100个十进制数字的结果,并四舍五入(以传统方式)到最接近的可表示值.
This will compute the result with 100 decimal digits of precision, rounding (in the conventional way) to the nearest representable value.
请注意,这种方法为您提供 inexact 结果;例如(1/3)* 3将不完全是1,无论您在 MathContext
中将精度设置为什么.
Note that this approach gives you inexact results; e.g. (1 / 3) * 3 won't be exactly 1, no matter what you set the precision to in the MathContext
.
您可以找到并使用第三方的 Rational
或 Fraction
类,或者编写自己的类.
You can find and use a 3rd-party Rational
or Fraction
class, or write your own.
请注意,Java SE不提供此类.
Note that Java SE doesn't provide such a class.
这篇关于使用无理数.返回1/22140.简化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!