3 ms·
First off this seems like unordered notes and I spent 15 minutes trying to figure out what the actual requirements were, because it was saying things it needed
by Dylan16807 12y ago
First off this seems like unordered notes and I spent 15 minutes trying to figure out what the actual requirements were, because it was saying things it needed and then talking about solutions that didn't have those features.
Anyway, the main goal seems to be even density of chosen numbers, while also not skipping floats. In other words the probability of any specific float being chosen is proportional to its width.
This is easy to do, and needs no rounding. At least for [0,1)
Observe that floats [.5,1) are half the probability space. Use one random bit to choose between them and smaller values.
Then floats [.25,5) are half the space. Use another random bit.
Once you've chosen the exponent, fill in the mantissa with 52 random bits. All floats in the range are the same distance apart, so random bits work fine.
mantissa := random(2^52)
exponent := -1
while random(2) == 1:
exponent -= 1
return (1 + mantissa/2^52) * 2^exponent
If you really want [0,1], then you must first define how wide of a range of real numbers you want to assign to "1". Rounding toward zero makes more sense. Alternatively, note how nonzero double precision floats go down below 2^-1000. You will never ever actually generate a zero, no matter what you do. Why should "1" be more likely than "0"?
But if you insist on rounding to nearest then you can put in a special clause where a mantissa of 0 has a 50% chance of being treated as 2^52.
- TheLoneWolfling 12y agoIf you really want [0,1], it might be more simple to include a check at the start: if (1-in-number-of-floats-in-[0,1)) return 1; Your version of 50/50 split with the mantissa will mean that 0 and 1 will be less often chosen than others. However, your version won't generate a (quite) uniform distribution anyways, due to subnormals. I think a simple fix for that would be to, if your exponent reaches the subnormals, just return a random mantissa with the subnormal exponent.
- Dylan16807 12y agoI suppose my version might be wrong when it hits a denormal. It would depend on the rounding mode. Also it would never actually get to a denormal. But you're right that to be obviously correct it should stop when it reaches denormals. >Your version of 50/50 split with the mantissa will mean that 0 and 1 will be less often chosen than others. That's intentional, because rounding a real number to the nearest float has the same behavior. The spec is wrong, I advise against following the spec, but that is how you do it.