# interesting example of lazyness/ghc optimisation

George Russell ger@tzi.de
Thu, 01 Mar 2001 16:58:53 +0100

```I hope nobody actually uses this random number generator.  It appears
to be linear congruential with period less than 140000.  The author
of these benchmarks seem to have got this algorithm from "Numerical
Recipes", whose code (at least, in the early editions)
has come in for some very heavy criticism:
http://math.jpl.nasa.gov/nr/nr.html
I would take these benchmarks more seriously if "random" implied
a slightly more modern algorithm, like the Mersenne Twister
(which has been implemented in Haskell I believe).

Julian Assange wrote:
> Noticing the use of tuples and normalisation at each step of
> the iteration, I re-wrote this as:
>
> module Main(main) where
> import System(getArgs)
> import Numeric(showFFloat)
>
> main = do
>          ~[n] <- getArgs
>          putStrLn (showFFloat (Just 12) (random 42 (read n::Int) 100.0) "")
>          return 1
>
> random :: Int -> Int -> Double -> Double
> random seed n max = norm (rand n seed) max
>     where norm x max = (fromIntegral x) * (max / imd)
>           rand n x   = if n > 0 then rand (n-1) ((x * ia + ic) `mod` im) else x
>           im         = 139968
>           imd        = fromIntegral im
>           ia         = 3877
>           ic         = 29573

```