Saturday, August 14, 2010

As if from nowhere, e appears, at it's own pace!

Inspired by this lovely blogpost I decided to write my own slow and arcane "e" maker. Please compile it before running, otherwise it has runtime complexity O(forever).

import System.Random
main = print e
e :: Double
e = (+1).average $ map (length . takeWhile (<1) . scanl1 (+) . randomReals) [1..1000000]
where
average :: [Int] -> Double
average x = fromIntegral (sum x) / fromIntegral (length x) -- This is a rubbish (slow) way to average
randomReals :: Int -> [Double]
randomReals = randomRs (0.0,1) . mkStdGen more than 500000 takes a while
-- This generates a random seed from each number and then makes a list of values in(0,1)
view raw slow slow e.hs hosted with ❤ by GitHub

No comments:

Post a Comment