randomIO(来自System.Random)是否产生0?

时间:2017-12-15 10:53:01

标签: haskell random

我了解randomIO::IO Float生成均匀分布的Float数字,但我的问题是在什么范围内?它是[0,1](0,1)还是介于两者之间的任何内容([0,1)(0,1])?

我无法在hackage找到任何关于它的信息,参考文件背后是付费墙。

我问的原因是因为您可能想要转换随机数,如果您想评估1/myRandomNumber,那么了解您是否会遇到Infinity会很有帮助或不。

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

Try it online!

1 个答案:

答案 0 :(得分:9)

简短回答:范围 [0,1)

是。 Random的{​​{1}}的实施是[source]

Float

它使用随机的32位整数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) (其中零是一个可能的值),它掩盖了前8位,并将该值除以 2 24 。结果,范围是0(包括)到1(不包括)。它可以代表的最大值是x

它以这种方式工作的原因是因为0.999999940395有一个24位的mantisse(以及7位指数和一个符号位)。通过在该范围内对其进行转换,我们保证每个Float值都是同等可能的:最后24位首先被复制到Float的mantisse中,然后浮点数被归一化,并且指数改变为值在[0,1]范围内。