I am trying to understand which circumstances can cause a double to become NaN.
For instance, 0/0 is nan. This is also stated in the official Documentation. https://docs.microsoft.com/en-us/dotnet/api/system.double.nan?view=net-6.0
However, my debug code indicates that the division is not by 0:
public class StandardDeviation
{
public StandardDeviation()
{
Clear();
}
private double M { get; set; }
private double S { get; set; }
private uint Iteration { get; set; }
public double Value
{
get
{
return Math.Sqrt(S / (Iteration - 2));
}
}
public void AddValue(double value)
{
if (double.IsNaN(value))
{
throw new ArgumentException("value IS nan!");
}
double tmpM = M;
M += (value - tmpM) / Iteration;
S += (value - tmpM) * (value - M);
Iteration++;
if (double.IsNaN(M))
{
Console.WriteLine($"\nNAN EXCEPTION!!! divide by: {Iteration}");
Console.WriteLine($"\nNAN EXCEPTION!!! tmpM: {tmpM}");
throw new ArgumentException("m IS nan!");
}
}
public void Clear()
{
M = 0.0;
S = 0.0;
Iteration = 1;
}
}
console message:
NAN EXCEPTION!!! divide by: 3
NAN EXCEPTION!!! tmpM: ∞
The issue primairly seems to be prevalent in release configuration, which makes it hard to debug.
Whenever the exception is thrown, Iteration = 3.