Is “(float)integer == integer” guaranteed to be equal in C#?

前端 未结 5 2067
有刺的猬
有刺的猬 2021-01-07 20:05

While \"we all know\" that x == y can be problematic, where x and y are floating point values, this question is a bit more specific:

5条回答
  •  猫巷女王i
    2021-01-07 20:37

    The following experiment reveals that the answer is you do not have that edge case where equality is not true

        static void Main(string[] args)
        {
            Parallel.For(int.MinValue, int.MaxValue, (x) =>
            {
                float r = x;
                // Is the following ALWAYS true?    
                bool equal = r == x;
                if (!equal) Console.WriteLine("Unequal: " + x);                
            });
    
            Console.WriteLine("Done");
            Console.ReadKey();
    
            return;
    }
    

    It seems reasonable that the conversions

    float f = i;
    

    and

    if ((int)f != i)
    

    should follow the same rules. This proves that int -> float and float -> int conversions are a bijection.

    NOTE: the experiment code actually doesn't test the edge case int.MaxValue because Parallel.For's to parameter is exclusive, but I tested that value separately and it also passes the test.

提交回复
热议问题