I am doing simulation in Monte Carlo and am currently using System.Random .
import System.Random main = do g <- newStdGen let xs = randoms g :: [Double] -- normally, I'd do other magic here putStrLn $ show $ length $ take 10^9 xs
Unfortunately, this takes a very long time, at least 5 times slower than Python random.random() , not to mention calling C rand() .
With ghc -O2 -optc-ffast-math -optc-O3 -O3
import System.Random main = do g <- newStdGen let xs = randoms h :: [Double] putStrLn $ show $ length $ take (10^7) xs
takes ~ 8s against (in iPython)
import random %timeit len([random.random() for _ in range(10 ** 7)])
takes ~ 1.3s. My goal is one billion, but Haskell cannot generate them for a reasonable amount of time.
I also have a C ++ program that generates a float with rand() . He makes 10^7 samples in 0.2s.
How can I quickly generate random doubles in the range [0-1) in Haskell?
Ideally, the GHC program only generates platoons of rand() POSIX calls and collects them into a list. It turns out the answer with the cleanest and fastest code. (No, 10x code to accelerate 1% is not worth it.)
source share