开发者

Arithmetic error when adding two double values [duplicate]

This question already has answers here: Closed 11 years ago.

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 hav开发者_运维百科en't tested it out in other scenarios.


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


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/


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜