My current function goes like:
float random(){
return (float)rand_xor128()/UINT_MAX;
}
But then I realised that once the value is converted to float, it would lose precision, right?
Should i first convert it to double perhaps?
float random(){
return (float)((double)rand_xor128()/UINT_MAX);
}
But it doesn’t feel the right thing to do. How should I do it?
You have a 32-bit value that you want to squeeze into the range [0,1). That requires you to be able to represent
2^32different values in that range.A
floathas 2^32` possible values in total. In other words, a float can never ever ever do what you need. If you return a double, you might be able to do this (I haven’t run the numbers to determine it exactly), but otherwise, you’ll have to write your own datatype which does exactly what you need.But if you store that value into a float, you’re going to lose precision, because it simply doesn’t have enough precision in the [0,1) range to satisfy your requirements.