Reputation: 75
i've stumbled about a strange bug in my application, when I attached the visual studio debugger.
Here is the code snippet of what I want to talk about:
double lowerLimit = valueProvider.LowerLimit.Value; //valueProvider.LowerLimit.Value = Double.NaN
double upperLimit = valueProvider.UpperLimit.Value; //valueProvider.LowerLimit.Value = Double.NaN
if (Double.IsNaN(upperLimit))
{
var value = StaticClass.DeviceA.GetValue();
upperLimit = value + 0.2;
lowerLimit = value - 0.2;
}
I want to assign the two variables "lowerLimit" and "upperLimit" from the values of the object "valueProvider". The object valueProvider has been deserialized from XML before. Both values of the valueProvider object are Double.NaN. So my variables "lowerLimit" and "upperLimit" will be Double.NaN too, right? Thats right, but sometimes, they will change to Double.NegativeInfinity. Therefore, my logic below won't be executed.
So it looks like this:
double lowerLimit = valueProvider.LowerLimit.Value; //valueProvider.LowerLimit.Value = Double.NaN
double upperLimit = valueProvider.UpperLimit.Value; //valueProvider.LowerLimit.Value = Double.NaN
//lowerLimit = -Infinity
//upperLimit = -Infinity
Actually, this bug happens in under 1% of the executions of this code. I'm pretty sure, that I do not modify these values somewhere else. I've took a look into the Double class and found this declaration for the constants NaN, -Infinity and +Infinity:
public const Double NegativeInfinity = -1D / 0D;
public const Double PositiveInfinity = 1D / 0D;
public const Double NaN = 0D / 0D;
So my questions are:
Edit: There is only one change where the values are changed. This was in the hidden logic, I've added it. The object of "DeviceA" comes from another library out of my control. If it returns -Infinity it will keep -Infinity, so I would have to search there. Thanks for your help!
Upvotes: 2
Views: 162
Reputation: 6514
NaN is a result of an expression 0/0. PositiveInfinity and NegativeInfinity are the result of expressions such as 1/0 or -1/0. So, there is no better way to represent NaN.
In Javascript, parsing a string will result in NaN. However in C# it will result in an exception with Float.Parse().
To answer your questions:
The mentioned constants seems to be calculated. Is there a chance, that the processor can mess this up? No Is there even a chance that this simple variable assignment can go wrong? No Is there a better way to represent NaN? No.
Upvotes: 2