Finding the “discrete” difference between close floating point numbers

后端 未结 2 1704
臣服心动
臣服心动 2021-01-06 08:47

Suppose I have two floating point numbers, x and y, with their values being very close.

There\'s a discrete number of floating point number

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-06 09:18

    Floats are lexicographically ordered, therefore:

    int steps(float a, float b){
    
      int ai = *(int*)&a;  // reinterpret as integer
      int bi = *(int*)&b;  // reinterpret as integer
      return bi - ai;
    }
    
    steps(5.0e-1, 5.0000054e-1);  // returns 9
    

    Such a technique is used when comparing floating point numbers.

提交回复
热议问题