Generating random numbers in haskell (fast)

import qualified System.Random.MWC as R 
import Data.Vector.Unboxed as U 

-- A random numbers generator (vector from a uniform distribution). 
random_floats :: Int -> IO (U.Vector Float) 
random_floats n = R.createSystemRandom >>= \gen -> R.uniformVector gen n 
  
-- To scale the random floats in (0, 1.0) to (min, max)
-- y = (max - min) x + min 
 scale_samples :: (Float, Float) -> U.Vector Float -> U.Vector Float 
 scale_samples (min, max) vs = U.map (\v -> (max - min) * v + min ) vs 
  
 -- Sample a given space for n points. 
 sampled_space :: [( Float, Float)] -> Int -> IO [ U.Vector Float ] 
 sampled_space axes n = 
 random_floats n >>= \vv -> return $ Prelude.map (\x -> scale_samples x vv ) axes
main = do 
    vs <- sampled_space [ (1,3), (-1,1) ] 100 
    print vs 
    putStrLn $ "Done"
Advertisements

About Dilawar

Graduate Student at National Center for Biological Sciences, Bangalore.
This entry was posted in Haskell, Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s