浮点运算不能产生精确的结果

Floating point arithmetic not producing exact results(浮点运算不能产生精确的结果)
本文介绍了浮点运算不能产生精确的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要在Java中做一些浮点运算,如下代码所示:

I need to do some floating point arithmetic in Java as shown in the code below:

public class TestMain {
    private static Map<Integer, Double> ccc = new HashMap<Integer, Double>() {
      { put(1, 0.01); put(2, 0.02); put(3, 0.05); put(4, 0.1); put(6, 0.2);
        put(10, 0.5); put(20, 1.0); put(30, 2.0); put(50, 5.0); put(100, 10.0);
      }
    };

    Double increment(Double i, boolean up) {
        Double inc = null;

        while (inc == null) {
            inc = ccc.get(i.intValue());

            if (up)
                --i;
            else
                ++i;
        }
        return inc;
    }

    public static void main(String[] args) {
        TestMain tt = new TestMain();

        for (double i = 1; i < 1000; i += tt.increment(i, true)) {
            System.out.print(i + ",");
        }
    }
}

这是为了模拟 Betfair 输出的值范围微调器小部件.

Java 中的浮点运算似乎引入了一些意想不到的错误.例如,我得到 2.180000000000001 而不是 2.18.浮点数有什么用,你不能相信对它们执行的算术结果?我该如何解决这个问题?

Floating point arithmetic in Java seems to introduce some unexpected errors. For example, I get 2.180000000000001 instead of 2.18. What use are floating point numbers is you can't trust the results of arithmetic performed on them? How can I get around this issue?

推荐答案

如果你需要精确的十进制值,你应该使用java.math.BigDecimal.然后阅读每个计算机科学家应该了解的浮点运算知识"了解您获得这些结果的背景.

If you need exact decimal values, you should use java.math.BigDecimal. Then read "What Every Computer Scientist Should Know About Floating-Point Arithmetic" for the background of why you're getting those results.

(我有一篇 .NET 中心文章,您可能会发现它更容易阅读- 当然更短.Java 和 .NET 之间的差异对于理解这个问题来说几乎是无关紧要的.)

(I have a .NET-centric article which you may find easier to read - and certainly shorter. The differences between Java and .NET are mostly irrelevant for the purposes of understanding this issue.)

这篇关于浮点运算不能产生精确的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

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 中的默认语言环境设置以使其保持一致?)