I wrote a code that runs inconsistently on 3 different machines. Now I'm trying to track the reason of inconsistency and I found the following:
This code generates randomly erroneous results on my computer (didn't try on another yet):
using System;
using System.Collections.Generic;
namespace justfortest
{
class param : IComparable<param>
{
public int par1;
public int par2;
public int par3;
public int par4;
public int par5;
public int par6;
public int par7;
public double par8;
public double par9;
public double par10;
public double par11;
int IComparable<param>.CompareTo(param other)
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
List<param> paramList = new List<param>(10000000);
for (int par1 = 8; par1 <= 20; par1 += 4)
{
for (int par2 = 10; par2 <= 25; par2 += 5)
{
for (int par3 = 6; par3 <= 18; par3 += 4)
{
for (int par4 = 14; par4 <= 20; par4 += 3)
{
for (int par5 = 10; par5 <= 20; par5 += 5)
{
for (int par6 = 4; par6 <= 10; par6 += 2)
{
for (int par7 = 5; par7 <= 30; par7 += 5)
{
for (double par8 = 1.0005; par8 <= 1.002; par8 += 0.0005)
{
for (double par9 = 1.002; par9 <= 1.0048; par9 += 0.0007)
{
for (double par10 = 0.2; par10 <= 0.5; par10 += 0.1)
{
for (double par11 = 0.5; par11 <= 2; par11 += 0.5)
{
param p = new param();
p.par1 = par1;
p.par2 = par2;
p.par3 = par3;
p.par4 = par4;
p.par5 = par5;
p.par6 = par6;
p.par7 = par7;
p.par8 = par8;
p.par9 = par9;
p.par10 = par10;
p.par11 = par11;
paramList.Add(p);
}
}
}
}
}
}
}
}
}
}
}
Console.WriteLine(); //to place a break here and observe the results
}
}
}
The problem is about par8 to par11 that are defined as double. Their value is not always what is expected. For example sometimes par10 becomes 0.30000000000000004 instead of 0.3. After this par10==0.3 evaluates as false in the code later. The above sample reproduces the error for me.
I use .NET 4.5.2 and I tried the same in 4.6.1.
It seems that this behaviour appears randomly, at least I could not find a pattern. The only thing I noticed that with time it gets worse. In the beginning maybe only 1 of the doubles is like this in a param, but 100.000 items later all of them.
I really don't know what to do about this. Any clues?