[英]Java float to double - upper and lower bounds?
As most here will know, double -> float incurs a loss in precision. 正如大多数人都知道的那样,double - > float会导致精度损失。 This means, multiple double values may be mapped to the same float value.
这意味着,可以将多个double值映射到相同的float值。 But how do I go the other way?
但是我该如何走另一条路呢? Given a normal (I'm not caring about the extreme cases) float, how do I find the upper and lower value of double precision that are still mapped to the same float?
给定一个正常(我不关心极端情况)浮点数,如何找到仍然映射到同一浮点数的双精度的上限和下限值?
Or, to speak in code: 或者,用代码说话:
function boolean testInterval(float lowF, float highF, double queryD) {
float queryF = (float) queryD;
return (lowF <= queryF) && (queryF <= highF);
}
and 和
function boolean testInterval(float lowF, float highF, double queryD) {
double lowD = (double) lowF;
double highD = (double) highF;
return (lowD <= queryD) && (queryD <= highD);
}
do not always give the same result. 并不总是给出相同的结果。 I'm looking for two functions float-> double to make the second function return the same result at the first.
我正在寻找两个函数float-> double来使第二个函数在第一个函数返回相同的结果。
This could work, but it looks like a hack and not the proper solution to me. 这可能有用,但它看起来像黑客,而不是我的正确解决方案。
function boolean testIntervalHack(float lowF, float highF, double queryD) {
double lowD = (double) lowF - Float.MIN_VALUE;
double highD = (double) highF + Float.MIN_VALUE;
return (lowD <= queryD) && (queryD <= highD);
}
Your testIntervalHack
doesn't work, the range of double
values mapping to the same float
varies. testIntervalHack
不起作用,映射到同一个float
的double
值范围会有所不同。 For example, with x = 2^24-1
, every double
between x-0.5
and x+0.5
will be mapped to the same value (the float
value of x
), but x +/- Float.MIN_VALUE == x
. 例如,当
x = 2^24-1
, x-0.5
和x+0.5
之间的每个double
float
都将映射到相同的值( x
的float
值),但x +/- Float.MIN_VALUE == x
。
I'm not aware of any convenient API methods, so the best I can offer is 我不知道任何方便的API方法,所以我能提供的最好的方法是
double
double
double
to the bit representation via doubleTo(Raw)LongBits
doubleTo(Raw)LongBits
将double
转换为位表示 longBitsToDouble
longBitsToDouble
将long转换为double Well, that's for finite values in float
range. 嗯,这是
float
范围内的有限值。 For NaN
s, you can stop after step 1., for infinities, it's a bit more delicate, since double
values larger than or equal to 2 128 -2 103 are converted to (float)Infinity
, which is quite a bit away from the bit representation of (double)Infinity
. 对于
NaN
s,您可以在步骤1之后停止。对于无穷大,它更精细一些,因为大于或等于2 128 -2 103的 double
值被转换为(float)Infinity
,这与相当远离(double)Infinity
位表示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.