Debojyoti Das

Debojyoti Das

  • NA
  • 4
  • 1.9k

Double Comparison Method Misbehaviour

Jun 21 2014 9:29 AM
I have a code that populates 2 ArrayLists.

    x_i.Clear();
    x_j.Clear();
    for (int i = 0; i < iter; i++)
    {                   
        x_i.Add(Relax(((double)v_1[i] + (double)x_1[i])));
        x_j.Add(Relax(((double)v_2[i] + (double)x_2[i])));
    }

And Here is the relaxation step if that is necessary.

    private static double Relax(double eval)
            {
    
                if (eval < min)
                {
                    return min;
                }
                else if (eval > max)
                {
                    return max;
                }
                else
                {
                    return eval;
                }
            }

**max is set to 1.0 and min = 0.0** and the relaxation step sets eval to 0 if it is less than min and to 1 if it is more than max.

The problem is although the evaluation generates different numbers, the output of the x_i and x_j are always same. A sample run with some Console.WriteLine Will clear the problem.

    x_i Sans relax: 0.255135946560249 and Relax: 1.65849559394646
    x_j Sans relax: -0.297522860941407 and Relax: 1.65849559394646
    Added x_i: 1.658 and x_j: 1.658

And here is the code that generates the output:

    for (int i = 0; i < iter; i++)
    {
    Console.WriteLine("x_i Sans relax: {0} and Relax: {1}", ((double)v_1[i] + (double)x_1[i]), Relax(((double)v_1[i] + (double)x_1[i])));
    Console.WriteLine("x_j Sans relax: {0} and Relax: {1}", ((double)v_2[i] + (double)x_2[i]), Relax(((double)v_2[i] + (double)x_2[i])));
    x_i.Add(Relax(((double)v_1[i] + (double)x_1[i])));
    x_j.Add(Relax(((double)v_2[i] + (double)x_2[i])));
    Console.WriteLine("Added x_i: {0} and x_j: {1}",  string.Format("{0:0.000}",x_i[i]),  string.Format("{0:0.000}",x_j[i]));
    }

Why is the Relax() method generating spurious output? Please comment if any further information is required. Any help is highly appreciated.