我需要自动增加一个浮点值。我通过调用 Float.floatToIntBits 获得它的 int 值。如果我只是做一个 i++ 并将其转换回 float ,它不会给我预期的值。那我该怎么做呢?
(我试图通过 AtomicInteger 创建一个 AtomicFloat,因此出现了这个问题)。
编辑:这是我所做的:
Float f = 1.25f;
int i = Float.floatToIntBits(f);
i++;
f = Float.intBitsToFloat(i);
我想要 2.25,但得到的是 1.2500001。
最佳答案
原因是你从floatToIntBits
得到的位代表
- 签名
- 指数
- 尾数
布局如下:
Repr: Sign Exponent Mantissa
Bit: 31 30......23 22.....................0
将存储这些字段的整数递增 1 不会将其表示的浮点值递增 1。
I'm trying to create an AtomicFloat through AtomicInteger, hence this question
我在回答这个问题时正是这样做的:
要添加将 float 递增 1 的功能,您可以复制 the code of incrementAndGet
from AtomicInteger
(并将 int
更改为 float
):
public final float incrementAndGet() {
for (;;) {
float current = get();
float next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
(请注意,如果您想将 float 增加可能的最小值,您可以采用上述代码并将current + 1
更改为current +
Math.ulp(current)
.)
关于Java:通过 Float.floatToIntBits 递增?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9921690/