寻找“离散”接近的浮点数之间的差异
假设我有两个浮点数,x
和 y
,它们的值非常接近。
计算机上可以表示离散数量的浮点数,因此我们可以按升序枚举它们:f_1、f_2、f_3、...
。我希望找到此列表中 x
和 y
的距离(即它们是 1、2、3、... 或 n
离散的步骤分开?)
是否可以仅使用算术运算(+-*/
)而不查看二进制表示来做到这一点?我主要感兴趣的是它在 x86 上的工作原理。
假设 y > ,以下近似值是否正确? x 并且 x
和 y
仅相距几步(例如,<100)? (可能不是...)
(y-x) / x / eps
这里 eps 表示机器 epsilon。 (机器 epsilon 是 1.0 和下一个最小浮点数之间的差。)
Suppose I have two floating point numbers, x
and y
, with their values being very close.
There's a discrete number of floating point numbers representable on a computer, so we can enumerate them in increasing order: f_1, f_2, f_3, ...
. I wish to find the distance of x
and y
in this list (i.e. are they 1, 2, 3, ... or n
discrete steps apart?)
Is it possible to do this by only using arithmetic operations (+-*/
), and not looking at the binary representation? I'm primarily interested in how this works on x86.
Is the following approximation correct, assuming that y > x
and that x
and y
are only a few steps (say, < 100) apart? (Probably not ...)
(y-x) / x / eps
Here eps
denotes the machine epsilon. (The machine epsilon is the difference between 1.0 and the next smallest floating point number.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
浮点数是按字典顺序排序的,因此:
这样的技术在比较浮点数时使用点数。
Floats are lexicographically ordered, therefore:
Such a technique is used when comparing floating point numbers.
我认为,您不必直接检查二进制表示形式,但您必须依赖它才能获得准确的答案。
首先使用 frexp() 将 x 分解为指数
exp
和尾数。我相信下一个大于 x 的浮点数是 x + eps * 2^(exp-1)。 (“-1”是因为 frexp 返回 [1/2, 1) 范围内的尾数,而不是 [1, 2)。)如果 x 和 y 具有相同的指数,则基本上完成。否则,您需要计算 2 的幂有多少步,即
1.0/eps
。换句话说,2^n 和 2^(n+1) 之间的步数为1.0/eps
。因此,对于 y > x,计算从x到下一个2的幂有多少步;然后计算需要多少步才能得到小于 y 的最大 2 次方;然后计算从那里到 y 还需要多少步。我认为,所有这些都可以很容易地用 eps 来表达。
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 isx + 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) is1.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.