使用System.Random中的mkStdGen生成随机布尔值 [英] Using mkStdGen from System.Random to generate random booleans

查看:150
本文介绍了使用System.Random中的mkStdGen生成随机布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的程序中,为什么每一行都返回 True ?我原以为因为我正在用不同的种子初始化 mkStdGen ,所以一些行应该返回 True ,而其他行返回 False

In the following program why does every single line return True? I would have thought that because I am initializing mkStdGen with different seeds, some of the lines should return True while other lines return False :

module Main where
import System.Random

main = do
  --why every single line prints "True" ?
  print $ fst (random (mkStdGen 1) :: (Bool, StdGen))
  print $ fst (random (mkStdGen 2) :: (Bool, StdGen))
  print $ fst (random (mkStdGen 3) :: (Bool, StdGen))
  print $ fst (random (mkStdGen 4) :: (Bool, StdGen))
  print $ fst (random (mkStdGen 5) :: (Bool, StdGen))
  print $ fst (random (mkStdGen 6) :: (Bool, StdGen))
  print $ fst (random (mkStdGen 7) :: (Bool, StdGen))
  print $ fst (random (mkStdGen 8) :: (Bool, StdGen))
  print $ fst (random (mkStdGen 9) :: (Bool, StdGen))
  print $ fst (random (mkStdGen 10) :: (Bool, StdGen))

即使在 mkStdGen 它声明不同的参数
应该可能产生不同的生成器


Even in the source mkStdGen it states that "distinct arguments should be likely to produce distinct generators" :

{- |
The function 'mkStdGen' provides an alternative way of producing an initial
generator, by mapping an 'Int' into a generator. Again, distinct arguments
should be likely to produce distinct generators.
-}
mkStdGen :: Int -> StdGen -- why not Integer ?
mkStdGen s = mkStdGen32 $ fromIntegral s


推荐答案

有趣的是,这只是在haskell reddit(讨论)和记录在此文章中。文章建议丢弃种子中的第一个生成器,如下所示:

Interestingly this just came up on the haskell reddit (discussion here) and is documented in this post. The article suggests discarding the first generator from a seed, as in:

better_mkStdGen seed = snd $ randomR (1,6) $ mkStdGen seed

或者你可以使用一个随机包来声明分布,比如 mwc-random

Or you could use a random package that makes some claims about the distribution, like mwc-random.

这篇关于使用System.Random中的mkStdGen生成随机布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆