How to simplify this code (generates a random int between min and max base on unsigned int)?
Question
The code is
return min + static_cast<int>(static_cast<double>(max - min + 1.0) *
(number / (UINT_MAX + 1.0)));
number is a random number obtained by rand_s. min and max are ints and represent minimum and maximum values (inclusive).
If you provide a solution not using unsigned int as a number, please also explain how to make it be random.
Please do not submit solutions using rand().
Solution
The static_cast<double>
is redundant because the "+1.0"s will cause promotion to double anyway.
OTHER TIPS
In Numerical Recipes in C: The Art of Scientific Computing (William H. Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New York: Cambridge University Press, 1992 (2nd ed., p. 277)), the following comments are made:
"If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in
j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
and never by anything resembling
j = 1 + (rand() % 10);
(which uses lower-order bits)."
From man 3 rand
How about Boost:Random
You could do the arithmetic in an unsigned long long instead of a double, but only if ULONGLONG_MAX >= UINT_MAX*UINT_MAX, which is probably implementation defined. But if you're worried about that, you'd be worried about potential loss of precision in the original code in the case where (max - min) or RAND_MAX is large.
Whether the long long is actually faster might depend how good your platform's hardware float is. But integer arithmetic arguably is inherently simpler than floating-point.
Something like
min + number % (max - min + 1)
Check the end-cases