Skip to content

Commit

Permalink
Mirror code more exactly to the references
Browse files Browse the repository at this point in the history
  • Loading branch information
idontgetoutmuch committed Apr 6, 2020
1 parent 9610530 commit 126d534
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions System/Random.hs
Original file line number Diff line number Diff line change
Expand Up @@ -1090,20 +1090,22 @@ uniformIntegerM (l, h) gen
let v' = v * b + fromIntegral x
v' `seq` f (mag * b) v'

-- | A slightly modified version of what can be found in [Lemire's
-- paper](https://arxiv.org/pdf/1805.10941.pdf), [O'Neill's
-- blogpost](https://www.pcg-random.org/posts/bounded-rands.html) and
-- more directly from [O'Neill's github
-- repo](https://github.com/imneme/bounded-rands/blob/3d71f53c975b1e5b29f2f3b05a74e26dab9c3d84/bounded32.cpp#L234).
-- The modification is we want the range to be [0,t] not [0,t) to be
-- compatible with unsignedBitmaskWithRejectionRM.
-- | Uniformly generate Word32 in @[0, s]@.
unbiasedWordMult32 :: MonadRandom g m => Word32 -> g -> m Word32
unbiasedWordMult32 s g
| s == maxBound = uniformWord32 g
| otherwise = go
| otherwise = unbiasedWordMult32Exclusive (s+1) g
{-# INLINE unbiasedWordMult32 #-}

-- | See [Lemire's paper](https://arxiv.org/pdf/1805.10941.pdf),
-- [O'Neill's
-- blogpost](https://www.pcg-random.org/posts/bounded-rands.html) and
-- more directly [O'Neill's github
-- repo](https://github.com/imneme/bounded-rands/blob/3d71f53c975b1e5b29f2f3b05a74e26dab9c3d84/bounded32.cpp#L234).
-- N.B. The range is [0,t) **not** [0,t].
unbiasedWordMult32Exclusive :: MonadRandom g m => Word32 -> g -> m Word32
unbiasedWordMult32Exclusive r g = go
where
r :: Word32
r = s + 1
t :: Word32
t = (-r) `mod` r -- Calculates 2^32 `mod` r!!!
go = do
Expand Down

0 comments on commit 126d534

Please sign in to comment.