Associativity math: (a + b) + c != a + (b + c)

前端 未结 6 1090
北荒
北荒 2020-12-15 02:40

Recently I was going through an old blog post by Eric Lippert in which, while writing about associativity he mentions that in C#, (a + b) + c is not equivalent

6条回答
  •  不知归路
    2020-12-15 03:21

    On the range of the double type:

    double dbl1 = (double.MinValue + double.MaxValue) + double.MaxValue;
    double dbl2 = double.MinValue + (double.MaxValue + double.MaxValue);
    

    The first one is double.MaxValue, the second one is double.Infinity

    On the precision of the double type:

    double dbl1 = (double.MinValue + double.MaxValue) + double.Epsilon;
    double dbl2 = double.MinValue + (double.MaxValue + double.Epsilon);
    

    Now dbl1 == double.Epsilon, while dbl2 == 0.

    And on literally reading the question :-)

    In checked mode:

    checked
    {
        int i1 = (int.MinValue + int.MaxValue) + int.MaxValue;
    }
    

    i1 is int.MaxValue

    checked
    {
        int temp = int.MaxValue;
        int i2 = int.MinValue + (temp + temp);
    }
    

    (note the use of the temp variable, otherwise the compiler will give an error directly... Technically even this would be a different result :-) Compiles correctly vs doesn't compile)

    this throws an OverflowException... The results are different :-) (int.MaxValue vs Exception)

提交回复
热议问题