在某些情况下,我需要在 Java 中进行非常精确的计算,但它总是会出现一些意想不到的错误。我怎样才能避免它们或将错误保持在可接受的范围内?
例如
public static void main(String[] args) throws Exception {
double x = 0.0;
while (x <= 1.0){
System.out.println(x);
x += 0.1;
System.out.println("add 0.1");
}
}
- the result will be
0.0 add 0.1
0.1 add 0.1
0.2 add 0.1
0.30000000000000004 add 0.1
0.4 add 0.1
0.5 add 0.1
0.6 add 0.1
0.7 add 0.1
0.7999999999999999 add 0.1
0.8999999999999999 add 0.1
0.9999999999999999 add 0.1
这不是预期的。
提前致谢
最佳答案
在这些情况下,您应该使用 BigDecimal
。它避免了使用 float
或 double
时出现的各种偏差。
欲了解更多信息,Double vs. BigDecimal?
http://www.opentaps.org/docs/index.php/How_to_Use_Java_BigDecimal:_A_Tutorial
关于java - 如何提高Java计算的准确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31022498/