Calculate Nth float

With 32-bit floats, I think there is something like 2 ^ 31 - 1 representable floats. In java, you can take an existing float and find the “next float” using the Math library. But let's say you don't have an initial swim, is there a way to calculate the nth float? I don't care which language, if there is a language with a library function, I will take it.

Of course, I could just put all the floats in an array and index into it, but this is inefficient.

Here is another clarification. I could start with Float.MIN and increment N times with nextFloat, but this seems inefficient because I need to perform this operation many times.

+7
source share
1 answer

Depends on how you want to order them. Keep in mind that not all floats are ordered at all; for example, a pair of different NaNs is disordered (i.e., they are not equal, but none is larger than the other).

If you don't mind ending up with them, you can simply reinterpret the integer as a float. How you do this varies from language to language; here's the C implementation:

float int_to_float(uint32_t in) { union { float f; uint32_t i; } u; ui = in; return uf; } 

This has the convenient property of giving you basically ordered results - going to zero gets you 0.0, you get 1.4e-45, 2 you get 2.8e-45, and so on. The results will start to go crazy once you get into the NaN / Inf values, and eventually start to decrease as soon as you hit 0x80000000 (-0.0), but for now it should be pretty good.

+7
source

All Articles