添加两个双精度值时出现算术错误 [英] Arithmetic error when adding two double values

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

问题描述

可能的重复:
浮点误差示例
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.

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

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