我理解randomIO::IO Float产生均匀分布的Float数字,但我的问题是在什么范围内?是[0,1],(0,1)还是介于([0,1)或(0,1])之间的任何东西?
我在hackage上找不到任何关于它的东西,引用的论文是在付费墙背后.
我问的原因是因为你可能想要改变随机数,如果你想评估1/myRandomNumber它会有助于知道你是否会遇到Infinity.
import System.Random
main=(randomIO::IO Float)>>=print
Run Code Online (Sandbox Code Playgroud)
简答:范围是[0,1).
是.实施Random为一个Float是[来源]:
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)
Run Code Online (Sandbox Code Playgroud)
它使用随机的32位整数x(其中零是一个可能的值),它屏蔽前8位,并将该值除以2 24.结果,范围是0(包括)到1(不包括).它可以代表的最大值是0.999999940395.
它以这种方式工作的原因是因为a Float有一个24位的mantisse(以及7位指数和一个符号位).通过在该范围内对其进行转换,我们保证每个Float值都是同等可能的:最后24位首先被复制到mantisse中Float,然后浮点数被归一化,并且指数被改变,使得值在[0,1]中) 范围.
| 归档时间: |
|
| 查看次数: |
125 次 |
| 最近记录: |