Java: increasing with Float.floatToIntBits?
I need to increase the float value atomically. I get its int value by calling Float.floatToIntBits on it. If I just do i ++ and cast it back to float it doesn't give me the expected value. So how would I go about it?
(I'm trying to create an AtomicFloat via 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.
source to share
The reason is that the bits you get from floatToIntBits
represent
- sign
- index
- mantissa
is set out as follows:
Repr: Sign Exponent Mantissa
Bit: 31 30......23 22.....................0
Increasing the integer storing these fields from 1 will not increment the float value it represents by 1.
I am trying to create AtomicFloat via AtomicInteger, so this question
I did exactly that in the answer to this question:
To add functionality to increase the float by one, you can copy the code incrementAndGet
fromAtomicInteger
(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 increase the float by the smallest possible value , you take the above code and change current + 1
to current +
Math.ulp(current)
.)
source to share
The atom part can be implemented on top compareAndSet
for a wrapper class as shown in the aioobe link. Increment operators AtomicInteger
are implemented like this.
The increment part is a completely different problem. Depending on what you mean by "increment a float", this requires either adding it to the number or increasing it by ULP . For the latter in Java 6, the Math.nextUp method is what you are looking for. The Math.nextAfter method is useful for decreasing one ULP .
source to share