Generate Random Numbers in Batch Script

The random number follows two conditions. Firstly, it is uniformly distributed over a pre-defined set or interval; secondly, future values can be predicted based on past or present ones.

Random numbers play an important role in statistical analysis and probability theory.

This article will show how we can generate random numbers in Batch. Also, we will see necessary examples and explanations for better understanding.

Generate Random Numbers in Batch Script

There is a built-in variable in Batch named `RANDOM`. This variable generates random numbers from 0 to 32767 by using some arithmetic.

Here is a simple and basic example:

``````ECHO The random number is %RANDOM%
``````

This is a very simple example of the variable `RANDOM`. The output of our example code will look like the one below.

Output:

``````The random number is 17586
``````

Let’s see another example in Batch for generating random numbers.

``````@echo off
Set /A RAND=(%RANDOM%*500/32768)+1
Echo The random number is %RAND%
``````

The above example will generate a random number from 0 to 500. The output of our example code will look like the following.

Output:

``````The random number is 278
``````

In our next example, we will generate a large random number. The Batch code for this example is shown below.

``````@echo off
Set /A RAND=(%RANDOM%*%RANDOM%)+1
Echo The large random number is %RAND%
``````

Through the above Batch script, we will generate a random number with many digits. The output of the example code is displayed below.

Output:

``````The large random number is 276676113
``````

Random numbers are mainly used by the system for various purposes like data encryption keys, complex modeling, simulating, and selecting random samples from data sets that are big enough.

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.