Wpf: the Name Does Not Exist in the Namespace

What's the best way to compare Double and Int?

You really can't compare floating point and integral values in a naive way; particularly, since there's the classic floating point representation challenges. What you can do is subtract one from the other and see if the difference between them is less than some precision you care about, like so:

int iValue = 0;
double dValue = 0.0;

var diff = Math.Abs(dvalue - iValue);
if( diff < 0.0000001 ) // need some min threshold to compare floating points
return true; // items equal

You really have to define for yourself what equality means to you. For example, you may want a floating point value to round towards the nearest integer, so that 3.999999981 will be "equal" to 4. Or you may want to truncate the value, so it would effectively be 3. It all depends on what you're trying to achieve.

EDIT: Note that i chose 0.0000001 as an example threshold value ... you need to decide for yourself what precision is sufficient for comparison. Just realize you need to be within the normal representational bounds of double which I believe is defined as Double.Epsilon.

Is it valid to compare a double with an int in java?

Yes, it's valid - it will promote the int to a double before performing the comparison.

See JLS section 15.20.1 (Numerical Comparison Operators) which links to JLS section 5.6.2 (Binary Numeric Promotion).

From the latter:

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

  • If either operand is of type double, the other is converted to double.

  • ...

What is the difference between double? and int? for .Equals comparisons?

You are completely right to find this confusing. It is a mess.

Let's start by clearly saying what happens by looking at more examples, and then we will deduce the correct rules that are being applied here. Let's extend your program to consider all these cases:

    double d = 2;
double? nd = d;
int i = 2;
int? ni = i;
Console.WriteLine(d == d);
Console.WriteLine(d == nd);
Console.WriteLine(d == i);
Console.WriteLine(d == ni);
Console.WriteLine(nd == d);
Console.WriteLine(nd == nd);
Console.WriteLine(nd == i);
Console.WriteLine(nd == ni);
Console.WriteLine(i == d);
Console.WriteLine(i == nd);
Console.WriteLine(i == i);
Console.WriteLine(i == ni);
Console.WriteLine(ni == d);
Console.WriteLine(ni == nd);
Console.WriteLine(ni == i);
Console.WriteLine(ni == ni);
Console.WriteLine(d.Equals(d));
Console.WriteLine(d.Equals(nd));
Console.WriteLine(d.Equals(i));
Console.WriteLine(d.Equals(ni)); // False
Console.WriteLine(nd.Equals(d));
Console.WriteLine(nd.Equals(nd));
Console.WriteLine(nd.Equals(i)); // False
Console.WriteLine(nd.Equals(ni)); // False
Console.WriteLine(i.Equals(d)); // False
Console.WriteLine(i.Equals(nd)); // False
Console.WriteLine(i.Equals(i));
Console.WriteLine(i.Equals(ni));
Console.WriteLine(ni.Equals(d)); // False
Console.WriteLine(ni.Equals(nd)); // False
Console.WriteLine(ni.Equals(i));
Console.WriteLine(ni.Equals(ni));

All of those print True except the ones I have notated as printing false.

I'll now give an analysis of those cases.

The first thing to notice is that the == operator always says True. Why is that?

The semantics of non-nullable == are as follows:

int == int -- compare the integers
int == double -- convert the int to double, compare the doubles
double == int -- same
double == double -- compare the doubles

So in every non-nullable case, integer 2 is equal to double 2.0 because the int 2 is converted to double 2.0, and the comparison is true.

The semantics of nullable == are:

  • If both operands are null, they're equal
  • If one is null and the other is not, they're unequal
  • If both are not null, then fall back to the non-nullable case above.

So again, we see that for the nullable comparisons, int? == double?, int? == double, and so on, we always fall back to the non-nullable cases, convert the int? to double, and do the comparison in doubles. Thus these are also all true.

Now we come to Equals, which is where things get messed up.

There is a fundamental design problem here, which I wrote about in 2009: https://blogs.msdn.microsoft.com/ericlippert/2009/04/09/double-your-dispatch-double-your-fun/ -- the problem is that the meaning of == is resolved based on the compile time types of both operands. But Equals is resolved on the basis of the run time type of the left operand (the receiver), but the compile time type of the right operand (the argument), and that's why things go off the rails.

Let's begin by looking at what double.Equals(object) does. If the receiver of a call to Equals(object) is double then if the argument is not a boxed double, they are considered not equal. That is, Equals requires that the types match, whereas == requires that the types be convertible to a common type.

I'll say that again. double.Equals does not try to convert its argument to double, unlike ==. It just checks to see if it already is double, and if it is not, then it says they are not equal.

That then explains why d.Equals(i) is false... but... wait a minute, it is not false above! What explains this?

double.Equals is overloaded! Above we are actually calling double.Equals(double), which -- you guessed it -- converts the int to a double before doing the call! If we had said d.Equals((object)i)) then that would be false.

All right, so we know why double.Equals(int) is true -- because the int is converted to double.

We also know why double.Equals(int?) is false. int? is not convertible to double, but it is to object. So we call double.Equals(object) and box the int, and now its not equal.

What about nd.Equals(object) ? The semantics of that is:

  • If the receiver is null and the argument is null, they are equal
  • If the receiver is not null then defer to the non-nullable semantics of d.Equals(object)

So now we know why nd.Equals(x) works if x is a double or double? but not if it is int or int?. (Though interestingly, of course (default(double?)).Equals(default(int?)) would be true since they are both null!)

Finally, by similar logic we see why int.Equals(object) gives the behaviour it has. It checks to see if its argument is a boxed int, and if it is not, then it returns false. Thus i.Equals(d) is false. The i cannot be converted to double, and the d cannot be converted to int.

This is a huge mess. We would like equality to be an equivalence relation, and it is not! An equality relationship should have these properties:

  • Reflexivity: a thing is equal to itself. That is usually true in C# though there are a few exceptions.
  • Symmetry: If A is equal to B then B is equal to A. That is true of == in C# but not of A.Equals(B), as we've seen.
  • Transitivity: If A equals B and B equals C then A also equals C. That is absolutely not the case in C#.

So, its a mess on all levels. == and Equals have different dispatch mechanisms and give different results, neither of them are equivalence relations, and it's all confusing all the time. Apologies for getting you into this mess, but it was a mess when I arrived.

For a slightly different take on why equality is terrible in C#, see item number nine on my list of regrettable language decisions, here: http://www.informit.com/articles/article.aspx?p=2425867

BONUS EXERCISE: Repeat the above analysis, but for x?.Equals(y) for the cases where x is nullable. When do you get the same results as for non-nullable receivers, and when do you get different results?

What is correct way to compare 2 doubles values?

So the question will be is there a generic solution/workaround for this

There will not be a universal solution for finite precision floating point that would apply to all use cases. There cannot be, because the correct threshold is specific to each calculation, and cannot generally be known automatically.

You have to know what you are comparing and what you are expecting from the comparison. Full explanation won't fit in this answer, but you can find most information from this blog: https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ (not mine).


There is however a generic solution/workaround that side-steps the issue: Use infinite precision arithmetic. The C++ standard library does not provide an implementation of infinite precision arithmetic.

Comparing a double and int, without casting or conversion

You're going to get the "usual conversions" when dealing with values of different primitive types. I don't think there's any way around this.

If you're comparing ints to doubles you're going to need to come up with whatever rules you want to use when determining if two values are "close enough." You may consider using the std::modf function (in <cmath>) in making the comparison.

Consider:

#include <iostream>
#include <cmath>

int main()
{
double d = 6.15 - 3.15;
std::cout << std::boolalpha;
std::cout << "d == 3.0: " << (d == 3.0) << '\n';
double i;
d = std::modf(d, &i);
std::cout << "i = " << i << ", d = " << d << '\n';
std::cout << "i == 3.0: " << (i == 3.0) << '\n';
}

Using Visual Studio 2010 on default settings (i.e., NOT using fastmath) I get:

d == 3.0: false
i = 3, d = 4.44089e-016
i == 3.0: true

3.0 may be representable exactly in binary floating point math, but 6.15 - 3.15 isn't 3.0 in binary floating point math.


There have already been two references to the paper "What Every Computer Scientist Should Know About Floating-Point Arithmetic" which describes how binary floating point math works, and how it doesn't always fit with human expectations. The main point to remember is that you hardly ever want to compare two floating point numbers for equality, especially if one (or both) of those numbers is the result of a math operation.

In your case, though, you're trying to compare a double with an int, and I have to assume you want some rounding. You might want to consider 3.1 to be equivalent to 3. You might not. I really have no idea.

If you were to use the rounding conventions taught in elementary school (round up on .5 or higher), you might do something like:

#include <iostream>
#include <cmath>

int main()
{
double d = 6.15 - 3.15;
std::cout << std::boolalpha;
std::cout << "d == 3.0: " << (d == 3.0) << '\n';
// note: this rounds negative numbers the wrong direction
std::cout << "d is 'close enough' to 3.0: " << (std::floor(d + 0.5) == 3.0) << '\n';
}

There are much more complex possibilities, including one described in the paper.

The right way to compare a System.Double to '0' (a number, int?)

Well, how close do you need the value to be to 0? If you go through a lot of floating point operations which in "infinite precision" might result in 0, you could end up with a result "very close" to 0.

Typically in this situation you want to provide some sort of epsilon, and check that the result is just within that epsilon:

if (Math.Abs(something) < 0.001)

The epsilon you should use is application-specific - it depends on what you're doing.

Of course, if the result should be exactly zero, then a simple equality check is fine.



Related Topics



Leave a reply



Submit