将两个double值相加时的算术错误 [英] Arithmetic error when adding two double values

查看:156
本文介绍了将两个double值相加时的算术错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
浮点错误示例
Java中的双重算术和相等性

Possible Duplicate:
Floating point inaccuracy examples
double arithmetic and equality in Java

在尝试调试检查两个值是否相等的排序例程时,我遇到了此问题.获得值只是对两个双变量进行了加法运算:0.31 + 0.27.

I caught this issue while trying to debug a sorting routine that checked if two values were equal. Getting the values was simply doing some addition on two double variables: 0.31 + 0.27.

当排序将这两个对象的总和与另一个对象的总和也等于0.58进行比较时,它告诉我该比较不相等.查看第一个对象的总和,我看到它列出为0.58000000000000007.想知道我的代码是否有用,我创建了一个简单的控制台应用程序对其进行测试:

When the sort compared the sum of those two against the some of another objects, whose sum also equaled 0.58, it told me the comparison was not equal. Looking at the first object's sum, I saw it was listing it as 0.58000000000000007. Wondering if it was something with my code, I created a simple console app to test it out:

static void Main(string[] args)
    {
        double val1 = .31;
        double val2 = .27;

        Console.WriteLine("Value 1: " + val1);
        Console.WriteLine("Value 2: " + val2);

        double added = val1 + val2;

        if (!added.Equals(.58))
            Console.WriteLine("Added value is not .58!");
        else
            Console.WriteLine("Added value is .58");


        Console.WriteLine("Press any key to exit.");
        Console.ReadLine();
    }

在我的机器上运行它,然后再次是0.58000000000000007.我有一个同事做同样的事情,并得出了相同的结果.

Ran it on my machine, and it was 0.58000000000000007 again. I had a co-worker do the same and came up with the same output.

有没有人遇到过这个?我们都在运行64位Windows 7,并且是在C#中完成的-我还没有在其他情况下对其进行过测试.

Has anyone come across this before? We are both running 64-bit Windows 7, and this was done in C# - I haven't tested it out in other scenarios.

推荐答案

这与.31.27没有确切的二进制表示形式有关.我发现这篇文章有用.

This has to do with the fact that .31 and .27 do not have exact binary representations. I found this article useful.

这篇关于将两个double值相加时的算术错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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