Have you ever needed to generate a random number in code? whether it's for rolling a dice, or shuffling a set, this tweet thread is here for you! There's no reason that it should be easy or obvious, very experienced programmers repeat common mistakes. I did, before I learned ...
-
Show this thread
-
O.k. let's start with the most common problem, and the most common mistakes: how do we pick a random number between 0 and N inclusive, let's say N = 5, so like a dice that starts at zero because we're nerds.
1 reply 1 retweet 53 likesShow this thread -
A common solution is to r = rand() % (N + 1). Easy, right? Wrong! This solution is biased. To see how, imagine that RAND_MAX is "15". 0 % 6 == 0, 6 % 6 == 0, and 12 % 6 == 0 , so there are three rand() values each that return 0. Same works for 1, 2, 3 ...
6 replies 6 retweets 63 likesShow this thread -
Replying to @colmmacc
Aren't you way way way over thinking this? r = (rand() % N) + 1. And you should probably look at secure random if the randomness is important -- something like arc4random_uniform or reading /dev/urandom.
1 reply 0 retweets 1 like -
Replying to @defendtheworld @colmmacc
and just use N = 6 if you want a range of 6 values...
1 reply 0 retweets 0 likes -
Replying to @defendtheworld @colmmacc
my thought is that the bias you're referring to is based on the fact that 2^32 is not evenly divisible by 6. in which applications is that rounding error important?
1 reply 0 retweets 1 like
Well ... simulating a fair dice, for the obvious one.
-
-
Replying to @colmmacc
oh derp, and i guess you say the same thing later on in your thread
0 replies 0 retweets 0 likesThanks. Twitter will use this to make your timeline better. UndoUndo
-
Loading seems to be taking a while.
Twitter may be over capacity or experiencing a momentary hiccup. Try again or visit Twitter Status for more information.