4

If you assign a floating point number to a variable and assign this variable to another, is it guaranteed, that the comparison of these two variables always evaluates to true?

Considering the following code.

var r = new Random();
float a = (float)r.NextDouble();
float b = a;
Console.WriteLine(a == b); // Is this guaranteed to print true?

EDIT: Lets assume the value cannot be NaN.

Filip Minx
  • 2,438
  • 1
  • 17
  • 32
  • 3
    Not if `a` is `NaN`. – Lee Aug 29 '18 at 14:56
  • 1
    @vc74 The first part of the question (and the title) is somewhat more generalized. – spender Aug 29 '18 at 14:58
  • On generating `NaN`, I don't think that can happen in this context. `Double` has a much larger space (and more precision) than `float`, but I believe casting an out-of-range value would just throw an exception rather than result in `NaN`. And it's moot anyway. `NextDouble()` is always between 0 and 1, and IIRC the extra precision will just truncate when casting from double to float. – Joel Coehoorn Aug 29 '18 at 15:01
  • 10
    There are a *large* number of internet posts that strongly warn against testing floating point values for equality. This is not guaranteed. x86 is the trouble spot, the a variable might be stored in the FPU stack but the jitter might be forced to spill the b variable to memory, truncating the value from 80 to 64 or 32 bits. You'll never see this go wrong when you debug the code, only happens in the Release build. And you'll never see this go wrong in the first version, only when you maintain the code and never expect it. One more internet post: https://stackoverflow.com/a/14865279/17034 – Hans Passant Aug 29 '18 at 15:05
  • @HansPassant Thats what I was looking for. I had a feeling, that I have read about it before. – Filip Minx Aug 29 '18 at 15:10
  • @HansPassant You're right, now I remember an article on the C# in depth website... I guess there's a huge potential for unexpected bugs in existing apps since few devs must check for `|x - y| < epsilon` instead of `x == y`. +1 for your question Filip. – vc 74 Aug 29 '18 at 15:14
  • @HansPassant, very interesting response since i was not aware of this. So, what should we do or under what circumstances whe can make that comparison deterministic? – Meiker Aug 29 '18 at 15:38
  • 2
    @HansPassant Normally, that's true. But in this specific case, there's really no way for x86 rounding issues to cause a problem. – Joel Coehoorn Aug 29 '18 at 16:13
  • From @HansPassant 's answer: "If you want consistent results then compiling with the AnyCPU target, and a 64-bit operating system, is the quick solution. The x64 jitter uses SSE instead of FPU instructions for floating point math." – NetMage Aug 29 '18 at 21:02

0 Answers0