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
floatToIntBitsrepresentslaid out like this:
Incrementing the integer storing these fields with 1 won’t increment the float value it represents by 1.
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
incrementAndGetfromAtomicInteger(and change frominttofloat):(Note that if you want to increment the float by the smallest possible value, you take the above code and change
current + 1tocurrent +Math.ulp(current).)