Is it Possible to compare two double datatype values?
Comparing two double values
Collapse
X
-
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
-
pooppp-Originally posted by poopppIs it Possible to compare two double datatype values?
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,
sicarieComment
-
Indeed I have discovered this today! I had an set of instructions saying:Originally posted by Ganon11It'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.
[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
Comment