Random Numbers

The Windows CMD shell contains a dynamic variable called %RANDOM% that can be used to generate random numbers.

%RANDOM% generates a random integer from 0 to 32767
To be precise the possible values include 0 but will be less than 32767
 0 =< %RANDOM% < 32767

The range of numbers can be made smaller with a little arithmetic, for example to generate a range between 1 and 500:

@ECHO OFF
SET /a _rand=%RANDOM%*500/32768+1
ECHO Random number in range 1-500=%_rand%

If you try it may look as though a larger range than 32767 might work, but doing this will produce gaps, for example changing 500 in the above to 65536 will result in a sequence of "random" numbers which only consists of odd numbers.

The distribution of numbers returned will be a determined by both the range and the quantity of numbers drawn.

For example if you are drawing random integer numbers where each number is between 0 and 100 then on average:
If you draw 10 numbers then you should expect around 6% to be duplicates.
If you draw 100 numbers then just over 63% will be duplicates i.e. matching one or more of the other 99 numbers.
If you draw 1,000 numbers then almost all will be duplicates as there are only 100 possible values.

Random vs Pseudorandom numbers

A pseudorandom sequence is not truly random but is determined by a small set of initial values (state), the initial seed is often based on the clock time. In the case of the CMD %RANDOM% the seed is based on the clock time when the CMD session started. This can be problematic when running a batch file, if the script always takes about the same time to run before calling %RANDOM% then the number returned will always lie within a small predictable range.

As an example create a file numbers.cmd:

@Echo off
Echo %RANDOM%

Then call the above with

CMD /c numbers.cmd
CMD /c numbers.cmd
CMD /c numbers.cmd

Johannes Baagøe has published a comparison of better random numbers for javascript. The fastest of these is Alea(), which you can find a copy of below. This has a number of advantages, you can create much larger numbers, it will create a lot of numbers quickly and if you call it passing a seed number then the results become repeatable - you can create exactly the same sequence of random numbers again at a later date.

// random.js
// call this from the command line with:
// cscript //E:jscript random.js

// Calling without a seed, the current time will be used as a seed
var srandom=Alea();

// Calling with a seed will return the same value for the same seed
//var seed=1234
//var srandom=Alea(seed);

var i=0

  // Return 10 random numbers
while ( i < 10 ) {
  // Return a number between 1 and 500 million
  WScript.echo(Math.floor((srandom()*500000000)+1) );
  i++;
} 

function Mash() {
  var n = 0xefc8249d;

  var mash = function(data) {
    data = data.toString();
    for (var i = 0; i < data.length; i++) {
      n += data.charCodeAt(i);
      var h = 0.02519603282416938 * n;
      n = h >>> 0;
      h -= n;
      h *= n;
      n = h >>> 0;
      h -= n;
      n += h * 0x100000000; // 2^32
    }
    return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
  };

  mash.version = 'Mash 0.9';
  return mash;
}

function Alea() {
  return (function(args) {
    // Johannes Baagoe <baagoe@baagoe.com>, 2010
    var s0 = 0;
    var s1 = 0;
    var s2 = 0;
    var c = 1;

    if (args.length == 0) {
      args = [+new Date];
    }
    var mash = Mash();
    s0 = mash(' ');
    s1 = mash(' ');
    s2 = mash(' ');

    for (var i = 0; i < args.length; i++) {
      s0 -= mash(args[i]);
      if (s0 < 0) {
        s0 += 1;
      }
      s1 -= mash(args[i]);
      if (s1 < 0) {
        s1 += 1;
      }
      s2 -= mash(args[i]);
      if (s2 < 0) {
        s2 += 1;
      }
    }
    mash = null;

    var random = function() {
      var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32
      s0 = s1;
      s1 = s2;
      return s2 = t - (c = t | 0);
    };
    random.uint32 = function() {
      return random() * 0x100000000; // 2^32
    };
    random.fract53 = function() {
      return random() + 
        (random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
    };
    random.version = 'Alea 0.9';
    random.args = args;
    return random;

  } (Array.prototype.slice.call(arguments)));
};

/* licensed according to the MIT - Expat license:

Copyright (C) 2010 by Johannes Baagoe <baagoe@baagoe.org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */

“Anyone who attempts to generate random numbers by deterministic means is, of course, living in a state of sin” - John von Neumann

Related:

PowerShell Equivalent: Get-Random
VBScript: Rnd - Return a pseudorandom number.
Random.org - Generate true random numbers online.


© Copyright SS64.com 1999-2014
Some rights reserved