haskell-numerics / random-fu

A suite of Haskell libraries for representing, manipulating, and sampling random variables
42 stars 21 forks source link

MonadRandom IO instance on Windows #32

Open cmears opened 9 years ago

cmears commented 9 years ago

Hello,

This test program works well on Linux but not on Windows. I am using the library the right way?

import Data.Random.Sample
import Data.Random.Distribution.Uniform
import Data.Random.Source.IO
import Control.Monad

main = print =<< replicateM 10000 (sample (uniform 0 10) :: IO Int)

On Linux I get a random-looking sequence, but on Windows I get big chunks of the same number repeated.

I think the problem is in the instance of MonadRandom:

instance MonadRandom IO where
    getRandomPrim = withSystemRandom . (flip getRandomPrimFrom :: Prim t -> Gen RealWorld -> IO t)

This seems to call withSystemRandom for every random number, which reseeds the generator, and on Windows the current time is used as the seed, so every call within the same second gets the same result. (The documentation for withSystemRandom says that it should only be called once per thread or so [https://github.com/bos/mwc-random/blob/master/System/Random/MWC.hs#L423].)

idontgetoutmuch commented 9 years ago

Very interesting. It will take me some time before I can look at this. I trust you have found a workaround for what you want to do? If not let me know and I can make some suggestions.

cmears commented 9 years ago

Yes, I've worked around it by creating a PureMT explicitly, putting it in an IORef, passing the IORef where needed and using sampleFrom directly. The other way might have been a bit neater, but it's not a big problem. I was definitely surprised by the odd behaviour, though!

eflister commented 8 years ago

same problem here