Java:通过 Float.floatToIntBits 递增?

标签 java floating-point atomic

我需要自动增加一个浮点值。我通过调用 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得到的位代表

  1. 签名
  2. 指数
  3. 尾数

布局如下:

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/

相关文章:

java - 何时对 fragment 使用 onCreateView?

python - python 中的 stdin.readline() 是原子的吗?

assembly - ARM Cortex M3 上的原子 int64_t

java - 原子地执行代码块

c++ - float 错误。 c++怎么知道0.99999982是1?

java - 当子字符串多于值时,将重复出现的子字符串替换为数组值

java - 如何在 JSF 应用程序中引用文件资源

java - 无法覆盖 Spring Boot 安全性

c# - 浮点值的舍入

c - 为什么带有 DBL_MIN 的 strtod() 给出 ERANGE?