Java float for double - upper and lower bounds?

As most of them recognize, double → float suffers a loss of precision. This means that multiple double values ​​can be matched with the same float value. But how do I go the other way? Given a normal (I don't care about extreme cases) float, how do I find the upper and lower double precision values ​​that are still mapped to the same float?

Or, 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 am looking for two functions float-> double so that the second function returns the same result in the first place.

It might work, but it seems like a hack, not the right solution for 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); } 
+4
source share
1 answer

Your testIntervalHack not working, the range of double values ​​matched by the same float is changing. For example, with x = 2^24-1 each double between x-0.5 and x+0.5 will be mapped to the same value ( float x value), but x +/- Float.MIN_VALUE == x .

I don’t know any convenient API methods, so the best I can offer is

  • convert to double
  • convert double to bit representation via doubleTo(Raw)LongBits
  • add or subtract one from 2 28 or 2 28 -1, depending on whether you want the upper or lower border and 2 29 -bit - 0 or 1 (due to rounding to parity)
  • convert it to double through longBitsToDouble

Good thing for the final values ​​in the float range. For NaN s, you can stop after step 1. For infinities, this is a little more subtle, because double values ​​greater than or equal to 2 128 -2 103 are converted to (float)Infinity , which is quite a bit from the bit representation of (double)Infinity .

+3
source

Source: https://habr.com/ru/post/1382963/


All Articles