java float floattointbits_Java:通过Float.floatToIntBits递增?

我需要原子地增加一个浮点值.我通过调用它上面的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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值