Comparing two double values

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pooppp
    New Member
    • May 2008
    • 2

    Comparing two double values

    Is it Possible to compare two double datatype values?
  • arnaudk
    Contributor
    • Sep 2007
    • 425

    #2
    yes, indeed it certainly is.

    Comment

    • Ganon11
      Recognized Expert Specialist
      • Oct 2006
      • 3651

      #3
      It's tricky - floating point arithmetic means that comparisons aren't always going to give you exactly what you want. For example, comparing 5.0/3.0 to 1.66666... may or may not work as you expect.

      In general, it is a bad idea to use == to see if two floating point numbers are equal. Instead, write a small function that checks if two floating point numbers are within E of each other, where E is some small difference you can decide on yourself (about 1/10000 might work). If they are 'close enough', you can consider them equal.

      Comment

      • sicarie
        Recognized Expert Specialist
        • Nov 2006
        • 4677

        #4
        Originally posted by pooppp
        Is it Possible to compare two double datatype values?
        pooppp-

        Please review the Posting Guidelines to this site. We ask that you do things like not double post your question (I have deleted the first instance), and not ask sweeping general questions (such as this) that can be solved with a simple Google search (such as 'c++ compare double' and the large number of helpful responses generated).

        Thanks,

        sicarie

        Comment

        • IanWright
          New Member
          • Jan 2008
          • 179

          #5
          Originally posted by Ganon11
          It's tricky - floating point arithmetic means that comparisons aren't always going to give you exactly what you want. For example, comparing 5.0/3.0 to 1.66666... may or may not work as you expect.

          In general, it is a bad idea to use == to see if two floating point numbers are equal. Instead, write a small function that checks if two floating point numbers are within E of each other, where E is some small difference you can decide on yourself (about 1/10000 might work). If they are 'close enough', you can consider them equal.
          Indeed I have discovered this today! I had an set of instructions saying:

          [code=cpp]
          double dTemp = matrix[i][j];
          dTemp += matrix[a][b];
          dTemp -= matrix[j][i];
          dTemp -= matrix[b][a];

          if (dTemp >= 0.0)
          ...
          [/code]

          Where the value in the matrix [a][b] is the same as [b][a] etc... and was quite surprised when I got 5.678e-15 instead of 0.

          Comment

          Working...