Pseudorandom Distribution

Accorinding to this Stack Overflow answer, user CherryDT pointed out this code:

set /a num=%random% %% 100

does not give a uniform distribution.

The internal dynamic variable %random% does gives a uniform distribution, but the above code will not be a uniformed random. This code generates a random number between 0 ~ 99, but the result will not be uniform. 0 ~ 67 will occur more than 68 ~ 99 since 32767 MOD 100 = 67.

To generate a uniform distributed random using the above code, then 100 must be changed. Here is a method to get a number that creates a uniform distribution.

32767 mod (32767 / n)

where n is an integer, between 0 ~ 32767, the result may be decimal and may not work in batch.

Uniform Distribution

set /a result=(%RANDOM%*100/32768)+1

This method will generate a uniform distribution. It avoids using %, which is more like "remainder" then "modulus" in a batch script. Without using %, the result will be uniform.

Alternatively, here is an inefficient, but uniform method.

set /a test=%random%

if %test% geq [yourMinNumber] (
    if %test% leq [yourMaxNumber] (

        rem do something with your random number that is in the range.


Change [yourMinNumber] and [yourMaxNumber] accordingly to your own values.