How to simplify this code (generates a random int between min and max base on unsigned int)?

StackOverflow https://stackoverflow.com/questions/140786

  •  02-07-2019
  •  | 
  •  

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().

Was it helpful?

Solution

The static_cast<double> is redundant because the "+1.0"s will cause promotion to double anyway.

OTHER TIPS

@Andrew Stein

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top