I need to increment a float value atomically. I get its int value by calling Float.floatToIntBits on it. If I just do an i++ and convert it back to float, it does not give me the expected value. So how would I go about it?
(I'm trying to create an AtomicFloat through AtomicInteger, hence this question).
EDIT: here's what I did:
Float f = 1.25f;
int i = Float.floatToIntBits(f);
i++;
f = Float.intBitsToFloat(i);
I wanted 2.25, but got 1.2500001 instead.
The reason is that the bits you get from floatToIntBits represents
laid out like this:
Repr: Sign Exponent Mantissa
Bit: 31 30......23 22.....................0
Incrementing the integer storing these fields with 1 won't increment the float value it represents by 1.
I'm trying to create an AtomicFloat through AtomicInteger, hence this question
I did precisely this in an answer to this question:
To add functionality to increment the float by one, you could copy the code of incrementAndGet from AtomicInteger (and change from int to float):
public final float incrementAndGet() {
for (;;) {
float current = get();
float next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
(Note that if you want to increment the float by the smallest possible value, you take the above code and change current + 1 to current +Math.ulp(current).)
The atomic part can be implemented atop compareAndSet for a wrapper class as shown in the link of aioobe. The increment operators of AtomicInteger are implemented like that.
The increment part is a completely different problem. Depending on what you mean by "increment a float", it either requires you to add one to the number, or increment it by one ULP. For the latter, in Java 6, the Math.nextUp method is what you are looking for. For decrement by one ULP, the Math.nextAfter method is useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With