Finding the “discrete” difference between close floating point numbers

孤街醉人 提交于 2019-11-30 23:02:23

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.

You do not have to examine the binary representation directly, but you do have to rely on it to get an exact answer, I think.

Start by using frexp() to break x into exponent exp and mantissa. I believe the next float bigger than x is x + eps * 2^(exp-1). (The "-1" is because frexp returns a mantissa in the range [1/2, 1) and not [1, 2).)

If x and y have the same exponent, you are basically done. Otherwise you need to count how many steps there are per power of 2, which is just 1.0/eps. In other words, the number of steps between 2^n and 2^(n+1) is 1.0/eps.

So, for y > x, count how many steps there are from x to the next power of two; then count how many more steps it takes to get to the largest power of 2 less than y; then count how many more steps it takes to get from there up to y. All of these are pretty easily expressible in terms of eps, I think.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!