floating point multiplication vs repeated addition

前端 未结 1 654
时光说笑
时光说笑 2021-01-01 08:33

Let N be an a compile time unsigned integer.

GCC can optimize

unsigned sum = 0;
for(unsigned i=0; i

        
相关标签:
1条回答
  • 2021-01-01 09:08

    There are some fundamental difference between

     float funct( int N, float sum )
     {
         float value = 10.0;
         for( i = 0; i < N ;i ++ ) {
             sum += value;
         }
         return sum;
     }
    

    and

    float funct( int N, float sum )
    {
        float value = 10.0;
        sum += value * N;
        return sum;
    }
    

    When the sum approaches FLT_EPSILON * larger than value, the repeated sum tends towards a no-op. So any large value of N, would result in no change to sum for repeated addition. For the multiplication choice, the result (value * N) needs to be FLT_EPSILON * smaller than sum for the operation to have a no-op.

    So the compiler can't make the optimization, because it can't tell if you wanted the exact behavior (where multiply is better), or the implemented behavior, where the scale of sum affects the result of the addition.

    0 讨论(0)
提交回复
热议问题