GCC problem with raw double type comparisons

前端 未结 3 1482
孤独总比滥情好
孤独总比滥情好 2021-01-05 03:54

I have the following bit of code, however when compiling it with GCC 4.4 with various optimization flags I get some unexpected results when its run.

#include         


        
3条回答
  •  半阙折子戏
    2021-01-05 04:20

    The problem is likely the result of losing some precision when storing the result of an expression vs. the compiler not doing so in a local as an optimization:

    double d = v[i % 4] * i;  // the result, `d`, might be kept in a register 
                              //   instead of storing it in a memory location, 
                              //   keeping full precision
    
    if(lst[i] != d) {         // the value stored in lst[i] may have lost some 
                              //   precision since it had to be stored in memory,
                              //   which might not be able to hold the full 
                              //   precision that the expression generated
    

    The C99 standard says in 6.3.1.8/2 "Usual arithmetic conversions":

    The values of floating operands and of the results of floating expressions may be represented in greater precision and range than that required by the type; the types are not changed thereby.

提交回复
热议问题