Does randomIO (from System.Random) produce 0?

I understand that randomIO::IO Float produces evenly distributed Float numbers, but my question is, in what range? Is it [0,1] , (0,1) or is it something in between ( [0,1) or (0,1] )?

I could not find anything about it on hackage , and the link to the paper was for a fee.

The reason I'm asking is because you might need to convert a random number, and if you want to evaluate 1/myRandomNumber , it would be helpful to know if you will ever run into Infinity or not.

 import System.Random main=(randomIO::IO Float)>>=print 

Try it now!

+5
source share
1 answer

Short answer : range [0, 1) .

Yes. Random implementation for a Float : [source] :

 instance Random Float where randomR = randomRFloating random rng = -- TODO: Faster to just use 'next' IF it generates enough bits of randomness. case random rng of (x,rng') -> -- We use 24 bits of randomness corresponding to the 24 bit significand: ((fromIntegral (mask24 .&. (x::Int32)) :: Float) / fromIntegral twoto24, rng') -- Note, encodeFloat is another option, but I'm not seeing slightly -- worse performance with the following [2011.06.25]: -- (encodeFloat rand (-24), rng') where mask24 = twoto24 - 1 twoto24 = (2::Int32) ^ (24::Int32) 

It uses a random 32-bit integer x (where zero is the possible value), it masks the first 8 bits and divides this value by 2 24 . As a result, the range 0 (included) to 1 (excluded). The largest value that it can represent is 0.999999940395 .

The reason this works is because Float has a 24-bit mantissa (as well as a 7-bit metric and sign bit). By converting it to this range, we guarantee that each Float value is equally probable: the last 24 bits are first copied to the mantisse Float , then the float is normalized and the exponent changes so that the values โ€‹โ€‹are in the range [0, 1].

+9
source

Source: https://habr.com/ru/post/1274095/


All Articles