0

I want a random number in Windows batch. Here's my command:

set /a "random_line=(%random%%%total)+1"

Is this going to give me an even distribution of random numbers?

EDIT:

I'd already looked at How to use random in BATCH script?, and CherryDT's answer made me ask the question about even distribution:

Note that this will not be uniformly distributed! Taking the 0~99 example, the numbers 0~67 will occur slightly more often than the numbers 68~99 because 32767 modulo 100 is 67 and not 0 as it would have to be for a uniform distribution. (This %random% %%100 is no magic syntax but actually %random % %% 100 with one less space, where the %% is just an escaped % which stands for modulo.)

So to clarify, will this give me uneven distribution?

Community
  • 1
  • 1
grgoelyk
  • 397
  • 1
  • 3
  • 12
  • http://stackoverflow.com/a/5777608/1683264 – rojo Feb 09 '17 at 19:56
  • Possible duplicate of [How to use random in BATCH script?](http://stackoverflow.com/questions/5777400/how-to-use-random-in-batch-script) – rojo Feb 09 '17 at 19:56
  • You asked, ***"is this going to give me an even distribution?"***, and also ***"will this give me uneven distribution?"***, so the clear answer is **Yes** and **No**, but not necessarily in that order. :) – abelenky Feb 09 '17 at 20:28

1 Answers1

4

Short answer to your question: No, your calculation will not give you a uniform distribution.

Long answer, with a bit of imagination of what you want to achieve,

%random% will give you a uniform distribution

but your code is not probably doing what you pretend.

Because the %RANDOM% dynamic variable generates a random integer from 0 to 32767 both inclusive.

If you want to transform it to a uniform integer distribution between 1 and %total% you need this calculation

SET /a random_line=(%RANDOM%*%total%/32768)+1
PA.
  • 28,486
  • 9
  • 71
  • 95