简体   繁体   中英

How to Map a double value to a float one In Java?

At first glance, my question could seem a bit odd; but casting a double to a float value is not what i want. Since when you cast it, you just lose some precision with respect to the rules defined IEEE-754 and can't achieve actual mapping of a double value to the range of float; it is useless. The following expression works, but it is very very expensive when you have a great amount of input:

float mappedVal = (float)((val * MAX_FLOAT_VALUE + 1) / MAX_DOUBLE_VALUE);

Can I approximate the result to the "mappedVal" mentioned above via some sort of bitwise operations to speed-up the very same computation?

I'm not sure what you're trying to achieve, since some double values are far outside the range of float.

But if you're willing to risk losing values that are too big for float, try this:

float f = new Double(val).floatValue();

Edit: which is exactly the same as casting to float. :)

This maps a double precision value into the float that has the same highest 32 bits:

float mappedVal = Float.intBitsToFloat((int)(Double.doubleToLongBits(val)>>32));

The arithmetic interpretation of this operation is a little complicated though, parts of the exponent are mapped into the mantissa...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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