代码之家  ›  专栏  ›  技术社区  ›  flawr

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

  •  5
  • flawr  · 技术社区  · 8 年前

    我知道随机IO::IO浮点产生均匀分布的浮点数,但我的问题是在什么范围内?它是 [0,1] , (0,1) 还是介于两者之间的任何东西( [0,1) (0,1) )

    我在上找不到关于它的任何信息https://hackage.haskell.org/package/random-1.1/docs/System-Random.html“rel=”nofollow noreferrer“>黑客攻击,参考文件位于付费墙后面

    我这样问的原因是,你可能想变换随机数,如果你想计算1/myRandomNumber,知道你是否会遇到无穷大会很有帮助

    导入系统。随机的 主=(随机::IO浮点)>&燃气轮机=打印

    在线试用! /p中间( [0,1) (0,1] )?

    我在网上找不到关于它的任何信息 hackage ,参考文献位于付费墙后面。

    我之所以这样问,是因为你可能想变换随机数,如果你想计算 1/myRandomNumber 知道你是否会遇到 Infinity 或者不是。

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

    在线试用!

    1 回复  |  直到 8 年前
        1
  •  9
  •   willeM_ Van Onsem    8 年前

    简短回答 :范围为 [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)范围内。

    推荐文章