Unbias a random generator: Difference between revisions

Content added Content deleted
(added haskell)
Line 451: Line 451:
randN(6) 166900 833100 16.69%
randN(6) 166900 833100 16.69%
unbiased 499973 500027 50.00%
unbiased 499973 500027 50.00%
</pre>

=={{header|Haskell}}==
Crappy implementation using <code>IO</code>
<lang haskell>import Control.Monad
import Random
import Data.IORef
import Text.Printf

randN :: Integer -> IO Bool
randN n = randomRIO (1,n) >>= return . (== 1)

unbiased :: Integer -> IO Bool
unbiased n = do
a <- randN n
b <- randN n
if a /= b then return a else unbiased n

main :: IO ()
main = forM_ [3..6] $ \n -> do
cb <- newIORef 0
cu <- newIORef 0
replicateM_ 50000 $ do
b <- randN n
u <- unbiased n
when b $ modifyIORef cb (+ 1)
when u $ modifyIORef cu (+ 1)
tb <- readIORef cb
tu <- readIORef cu
printf "%d: %5.2f%% %5.2f%%\n" n
(100 * fromIntegral tb / fromIntegral trials :: Double)
(100 * fromIntegral tu / fromIntegral trials :: Double)
where trials = 50000</lang>

Output:

<pre>
3: 33.72% 50.08%
4: 25.26% 50.15%
5: 19.99% 50.07%
6: 16.67% 50.10%
</pre>
</pre>