Given an integer I would like to produce a unique floating point number in the interval [0,1]. (this number will be used as id).
The problem I found with all functions I have thought about, is that they encounter duplicates before running out of integer values.
For example if f(a:int):float = 0.a then f(16000) = 0.16 and f(16001) = 0.16001. But since it is floating point, 0.16 and 0.16001 may be represented the same.
In other words, I need a function that produce not only unique numbers, but also numbers that are represented uniquely (at least forthe C++ integer domain).
I know the answer is dependent on the size of integer and floating point in a specific environment, but if you can give an example for specific sizes it will still be helpful.
As someone else pointed out you can simply cast an int to a float of the same size to get a unique float (with some post-filtering for NaN and -0 and Inf). However, that will not meet your requirement of being in [0,1]. In fact, you can use that relation to show that there are not enough floats in [0,1] to represent the set of integers. If you use double then the mantissa is easily large enough for a 32-bit int and an expression like I / (double)INT_MAX should be sufficient (obviously allow for unsignedness if you need to).
If 23 bits are enough, you could build a float from int n like this:
float f;
*((__int32*)&f) = (0x7E<<23) | (n & 0x7FFFFF); // exponent=0x7E-0x7F=-1, fraction=n
It will map integers [0, 2^23-1] into floats [0.5, 1.0) according to the IEEE floating point standard.
If 23 bits are not enough, you have a solution at the link that you cited yourself. There are some other important notes, by the way, be sure to understand all the limitations.
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