简体   繁体   English

如何在Java中将双精度值映射到浮点型?

[英]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. 但是将double转换为float值不是我想要的。 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; 因为当您进行转换时,相对于IEEE-754所定义的规则,您只是失去了一些精度,并且无法实现双精度值到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? 我可以通过某种按位运算将结果近似于上述“ mappedVal”,以加快相同的计算速度吗?

I'm not sure what you're trying to achieve, since some double values are far outside the range of float. 我不确定您要达到的目标,因为某些double值远远超出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: 这会将双精度值映射到具有相同的最高32位的float中:

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... 但是,此运算的算术解释有些复杂,部分指数已映射到尾数...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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