我需要原子地增加一个浮点值.我通过调用它上面的Float.floatToIntBits得到它的int值.如果我只是做一个i并将其转换回浮动,它不会给我预期的值.那我该怎么办呢?
(我正在尝试通过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
我在这个问题的答案中做到了这一点:
public final float incrementAndGet() {
for (;;) {
float current = get();
float next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
(注意,如果要将浮点数增加最小值,请使用上面的代码并将当前值1更改为当前的Math.ulp(current).)
标签:java,floating-point,atomic
来源: https://codeday.me/bug/20190729/1573897.html