I want a function getNthFloat(uint32 n) float32
such that for each n,m < 2³²-4 with n≠m, getNthFloat(n)
and getNthFloat(m)
return distinct floats that real numbers (neither NaN nor ±∞). 2³²-4 is chosen because if I understand IEEE 754 correctly, there are two binary representations of NaN, one for ∞ and one for -∞.
I imagine I should convert my uint32 into bits and convert bits into float32, but I can't figure out how to avoid the four values efficiently.
You can't get 2^32-4 valid floating point numbers in a float32. IEEE 754 binary32 numbers have two infinities (negative and positive) and 2^24-2 possible NaN values.
A 32 bit floating point number has the following bits:
31 30...23 22...0
sign exponent mantissa
All exponents with the value 0xff are either infinity (when mantissa is 0) or NaN (when mantissa isn't 0). So you can't generate those exponents.
Then it's just a simple matter or mapping your allowed integers into this format and then use math.Float32frombits
to generate a float32. How you do that is your choice. I'd probably be lazy and just use the lowest bit for the sign and then reject all numbers higher than 2^32 - 2^24 - 1 and then shift the bits around.
So something like this (untested):
func foo(n uint32) float32 {
if n >= 0xff000000 {
panic("xxx")
}
return math.Float32frombits((n & 1) << 31 | (n >> 1))
}
N.B. I'd probably also avoid denormal numbers, that is numbers with the exponent 0 and non-zero mantissa. They can be slow and might not be handled correctly. For example they could all be mapped to zero, there's nothing in the go spec that talks about how denormal numbers are handled, so I'd be careful.