Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
rand in a closed interval on the ints
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Michael Mair, post: 2468590"] It looks right -- had you formatted the code in a more readable manner, this would have been easier. Three remarks: 1) You are "admitting" that your implementation is based on rand(). I'd rather use an void init_rand_in_range (long seed); function from the start -- even if it only wraps srand(), this will make it easier if you ever want to use another pseudorandom number generator -- just "compile and link" instead of "replace all srand() calls in every bit of code by an init....() call". 2) In older rand() implementations, there often were problems with the modulo approach as you got shorter cycle lengths than for the division approach (see below). 3) Be verbose: int rand_in_range(int m, int n) { /*seed srand in main */ /* [m, n] is range */ int roll_again_threshold, divisor, result; int offset = m; int num_results = n - m + 1; if (num_results == 1) { return m; } if (num_results <= 0) { num_results = m - n + 1; offset = n; } roll_again_threshold = RAND_MAX - RAND_MAX%num_results; divisor = roll_again_threshold/num_results; do { result = rand(); } while (result >= roll_again_threshold); result /= divisor; return offset + result; } This is exaggerated but IMO more helpful than your code: Why say "diff + 1" if you mean the number of results? Or t and p? top vs roll_again_threshold is mostly a matter of taste -- the latter offers itself for the division. Cheers Michael [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
rand in a closed interval on the ints
Top