Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

11
  • 2
    Yuck :-P converting to a double, then multiplying by MAX_UPPER_LIMIT/RAND_MAX is much cleaner and performs better. Commented Jun 13, 2012 at 7:59
  • 24
    @boycy: you've missed the point. If the number of values that rand() can return is not a multiple of n, then whatever you do, you will inevitably get 'modulo bias', unless you discard some of those values. user1413793 explains that nicely (although the solution proposed in that answer is truly yucky). Commented Jun 17, 2012 at 11:31
  • 7
    @TonyK my apologies, I did miss the point. Didn't think hard enough, and thought the bias would only apply with methods using an explicit modulus operation. Thanks for fixing me :-) Commented Jun 18, 2012 at 12:26
  • 5
    This won't work if RAND_MAX == INT_MAX (as it does on most systems). See my second comment to @user1413793 above. Commented Nov 6, 2012 at 22:04
  • 1
    @BlueRaja-DannyPflughoeft On most systems? I've never seen a libc implementation where RAND_MAX isn't 32767 -- Microsoft's Visual libc, GLibC, BSD libc, even across architechtures Commented Jun 26, 2017 at 3:21