Java中浮点数的精度错误

Precision error with floats in Java(Java中浮点数的精度错误)
本文介绍了Java中浮点数的精度错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想知道在 Java 中修复精度错误的最佳方法是什么.正如您在以下示例中看到的那样,存在精度错误:

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("");
    }
  }
}

显示的结果是:

循环值:11

20.789999

循环值:22

41.579998

循环值:44

83.159996

循环值:88

166.31999

循环值:176

332.63998

循环值:352

665.27997

循环值:704

1330.5599

另外,如果有人能解释为什么它只从 11 开始,并且每次都将价值翻倍.我认为所有其他值(或至少其中许多值)都显示了正确的结果.

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.

正如人们所提到的,我可以使用双精度,但在尝试之后,似乎 1.89 作为双倍乘以 792 仍然会输出错误(输出为 1496.8799999999999).

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

我想我会尝试其他解决方案,例如 BigDecimal

I guess I'll try the other solutions such as BigDecimal

推荐答案

如果你真的很在意精度,你应该使用 BigDecimal

If you really care about precision, you should use BigDecimal

https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigDecimal.html

这篇关于Java中浮点数的精度错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)