问题描述
假设我有两个浮点数: x
和 y
,它们的值非常接近。 在计算机上可以表示一个浮点数的离散数,所以我们可以按照升序列举它们: f_1,f_2,f_3,...
。我希望在这个列表中找到 x
和 y
的距离(即它们是1,2,3,...)。 ..或 n
离散步骤分开?)
是否可以通过仅使用算术运算( + - * /
),而不是看二进制表示?我主要感兴趣的是如何在x86上工作。
假设 y>> x
并且 x
和 y
只有几个步骤(比如说
(yx)/ x / eps
这里 eps
表示机器epsilon。 (机器的epsilon是1.0和下一个最小的浮点数之间的差值。)
浮动按字典顺序排列,因此:
int steps(float a,float b){
int ai = *(int *) &安培;一个; //重新解释为整数
int bi = *(int *)& b; //重新解释为整数
return bi-ai;
}
步骤(5.0e-1,5.0000054e-1); //返回9
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.)
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.
这篇关于寻找“离散的”关闭浮点数之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!