简短回答
:范围为
[0, 1)
.
对实施
Random
暂时
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)
它使用一个随机的32位整数
x
(其中0是一个可能的值),它屏蔽了前8位,并将该值除以
2.
24
. 因此,范围为0(包括)到1(排除)。它所能代表的最大值是
0.999999940395
.
它这样工作的原因是
浮动
具有24位尾数(以及7位指数和符号位)。通过在该范围内进行转换,我们保证
浮动
值的概率相等:最后24位首先复制到
浮动
,然后对浮点进行归一化,并更改指数,使值处于[0,1)范围内。