In today’s Programming Praxis exercise our task is to determine how many random numbers between 0 and 1 we have to sum on average to exceed 1. Let’s get started, shall we?
Some imports:
import Control.Monad import System.Random
First, the algorithm itself, which counts the number of required additions.
f :: Float -> IO Int f s = if s > 1 then return 0 else fmap succ . f . (s +) =<< randomRIO (0, 1)
To get an average, we run the algorithm a number of times and take the average.
test :: Int -> IO Float test n = fmap ((/ toEnum n) . toEnum . sum) $ replicateM n (f 0)
As usual, a test to see if everything works:
main :: IO () main = print =<< test 100000
Three sequential test produce 2.72085, 2.71691 and 2.71838. Certainly in the right ballpark of the expected result of e, with the last one accurate to three places behind the comma, so it looks like everything’s okay.
Tags: bonsai, code, e, Haskell, kata, praxis, programming, random