shr*_*000 3 java floating-point atomic
我需要原子地增加一个浮点值.我通过调用它上面的Float.floatToIntBits得到它的int值.如果我只是做一个i ++并将其转换回浮点数,它就不会给我预期的值.那我该怎么办呢?
(我正在尝试通过AtomicInteger创建一个AtomicFloat,因此这个问题).
编辑:这是我做的:
Float f = 1.25f;
int i = Float.floatToIntBits(f);
i++;
f = Float.intBitsToFloat(i);
Run Code Online (Sandbox Code Playgroud)
我想要2.25,但却获得了1.2500001.
原因是你得到的比特floatToIntBits代表
这样布局:
Repr: Sign Exponent Mantissa
Bit: 31 30......23 22.....................0
Run Code Online (Sandbox Code Playgroud)
将这些字段存储为1的整数递增不会将其表示的浮点值增加1.
我正试图通过AtomicInteger创建一个AtomicFloat,因此这个问题
我在这个问题的答案中做到了这一点:
要添加将float递增1的功能,您可以复制from 的代码incrementAndGetAtomicInteger(并从中更改int为float):
public final float incrementAndGet() {
for (;;) {
float current = get();
float next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
Run Code Online (Sandbox Code Playgroud)
(注意,如果要以最小可能值递增浮点数,请使用上面的代码并更改current + 1为current +Math.ulp(current).)
| 归档时间: |
|
| 查看次数: |
1067 次 |
| 最近记录: |