浮点运算不能产生确切的结果 [英] Floating point arithmetic not producing exact results

查看:94
本文介绍了浮点运算不能产生确切的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

双重增量(Double i,布尔值){
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 +,);





这是模拟范围由必发微调控件输出的值。在Java中的浮点算法似乎引入了一些意想不到的错误。例如,我得到了2.180000000000001而不是2.18。浮点数的用途是什么?你不能相信在它们上执行的算术结果?如何解决这个问题?

解决方案

如果您需要精确的十进制 java.math.BigDecimal中。然后阅读每位计算机科学家应该了解的浮点算术为什么你会得到这些结果的背景。

(我有一个 p>

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

This is to simulate the range of values given as output by the Betfair spinner widget.

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?

解决方案

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.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆