在Java中浮点数的精度错误 [英] Precision error with floats in Java
问题描述
$ p $
class FloatTest
{
public static void main(String [] args)
{
Float number1 = 1.89f;
(int i = 11; i <800; i * = 2)
{
System.out.println(loop value:+ i);
System.out.println(i * number1);
System.out.println();
$ p $显示的结果是: / p>
循环值:11
20.789999
循环值:22
41.579998
循环值:44
b
$ b 83.159996
循环值:88
166.31999
循环值:176
332.63998
循环值:352
665.27997
循环值:704
1330.5599
另外,如果有人可以解释为什么它只能从11开始,每次翻倍。我认为所有其他值(或至少是其中的许多值)显示正确的结果。
以前的这样的问题使我头痛,我通常使用数字格式化程序或把它们放到一个字符串中。
编辑:正如人们提到的,我可以使用double,但是尝试之后,似乎1.89作为一个双倍的792仍然输出一个错误(输出是1496.8799999999999)。
我想我会尝试其他解决方案,如BigDecimal
$ b $如果你真的关心精度,你应该使用BigDecimal
http://download.oracle.com/javase/1.5.0/docs /api/java/math/BigDecimal.html
I'm wondering what the best way to fix precision errors is in Java. As you can see in the following example, there are precision errors:
class FloatTest
{
public static void main(String[] args)
{
Float number1 = 1.89f;
for(int i = 11; i < 800; i*=2)
{
System.out.println("loop value: " + i);
System.out.println(i*number1);
System.out.println("");
}
}
}
The result displayed is:
loop value: 11
20.789999
loop value: 22
41.579998
loop value: 44
83.159996
loop value: 88
166.31999
loop value: 176
332.63998
loop value: 352
665.27997
loop value: 704
1330.5599
Also, if someone can explain why it only does it starting at 11 and doubling the value every time. I think all other values (or many of them at least) displayed the correct result.
Problems like this have caused me headache in the past and I usually use number formatters or put them into a String.
Edit: As people have mentioned, I could use a double, but after trying it, it seems that 1.89 as a double times 792 still outputs an error (the output is 1496.8799999999999).
I guess I'll try the other solutions such as BigDecimal
解决方案 If you really care about precision, you should use BigDecimal
http://download.oracle.com/javase/1,5.0/docs/api/java/math/BigDecimal.html
这篇关于在Java中浮点数的精度错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!