Arithmetic error when adding two double values [duplicate]

こ雲淡風輕ζ 提交于 2020-01-15 11:13:53

问题


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

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.

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

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.

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.


回答1:


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




回答2:


This is a problem with floating point precision. What you could do is multiply the value by 100 (decmais accuracy of two houses) and make a cast to int or long. So the comparison run perfectly.

If you want to study in depth the subject of the search for Stallings book of computer architecture. link: http://williamstallings.com/




回答3:


You need to define an epsilon or a greatest-acceptable-error.

double result = 0.27 + 0.31;
double expected = 0.58;
double epsilon = 0.000001;
bool areTheyEqual = Math.abs(expected - result) < epsilon


来源:https://stackoverflow.com/questions/7719745/arithmetic-error-when-adding-two-double-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!