简体   繁体   English

Java浮动到双 - 上限和下限?

[英]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不起作用,映射到同一个floatdouble值范围会有所不同。 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-1x-0.5x+0.5之间的每个double float都将映射到相同的值( xfloat值),但x +/- Float.MIN_VALUE == x

I'm not aware of any convenient API methods, so the best I can offer is 我不知道任何方便的API方法,所以我能提供的最好的方法是

  1. convert to double 转换为double
  2. convert the double to the bit representation via doubleTo(Raw)LongBits 通过doubleTo(Raw)LongBitsdouble转换为位表示
  3. add or subtract one of 2 28 or 2 28 -1, depending on whether you want the upper or lower bound and the 2 29 -bit is 0 or 1 (because of round-to-even) 根据您是想要上限还是下限,2 29位是0还是1(因为舍入到偶数),加2或减2 28或2 28 -1中的一个
  4. convert that long to double via 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM