Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: How to seed (set the entropy used by) Data.Random?

The random-fu (Data.Random) package in Haskell offers the following example:

import Data.Random
import System.Random.MWC

logNormal :: Double -> Double -> RVar Double
logNormal mu sigmaSq = do
  x <- normal mu sigmaSq
  return (exp x)

main = do
  mwc <- create
  y <- sampleFrom mwc (logNormal 5 1)
  print y

It always generates the same result. I want to seed it from the clock. Ideally without having to get my hands dirty by actually reading the time.

(I haven't seen the word "seed" anywhere in the random-fu documentation, but I have found the phrsae "source of entropy" in a few places.)

like image 691
Jeffrey Benjamin Brown Avatar asked Nov 21 '25 13:11

Jeffrey Benjamin Brown


1 Answers

If you want to seed it from the clock, you can get the time with getPOSIXTime . It probably makes more sense to use createSystemRandom as Silvio Mayolo suggested. Both methods are demonstrated in the code below.

import Data.Random
import Data.Vector (singleton)
import Data.Time.Clock.POSIX (getPOSIXTime)
import System.Random.MWC

logNormal :: Double -> Double -> RVar Double
logNormal mu sigmaSq = do
  x <- normal mu sigmaSq
  return (exp x)

main = do

  t0 <- getPOSIXTime 
  mwc <- initialize (singleton (floor t0))
  y <- sampleFrom mwc (logNormal 5 1)
  print y

  mwc2 <- createSystemRandom
  z <- sampleFrom mwc2 (logNormal 5 1)
  print z
like image 153
Dave Compton Avatar answered Nov 24 '25 05:11

Dave Compton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!