CMD Random

Microsoft Windows
Post Reply
Rob
Posts: 1
Joined: 2021-Dec-17, 11:05 am
Location: Netherlands

CMD Random

Post by Rob »

regarding page https://ss64.com/nt/syntax-random.html and the example shown
---
@ECHO OFF
SET /a _rand=(%RANDOM%*500/32768)+1
ECHO Random number %_rand%

---
I find it not always working. Type the following in CMD and run it multile times:
SET /a _rand=(%RANDOM%*6/32768)+2
It will display random digits 2,3,4,5,6 but it will also sometimes display 7


What works for me is:
---
SET /a _rand=(%random% %% (%high%-%low%+1)) + %low%
---
as part of a line in a CMD file, with high and low being variables containing the upper and lower values.

example directly in cmd:
SET /a _rand=(%random% % (6-2+1)) + 2
run it multile times, it will only display values 2,3,4,5,6

regards
Rob
Shadow Thief
Posts: 12
Joined: 2021-Aug-03, 1:45 am

Re: CMD Random

Post by Shadow Thief »

I did an analysis of the two random number generation methods a while back and posted it on Reddit: https://www.reddit.com/r/Batch/comments ... lying_and/

Code: Select all

set /a rnd=(%RANDOM%%%(max-min+1))+min
is a more even distribution anyway.
User avatar
Simon Sheppard
Posts: 190
Joined: 2021-Jul-10, 7:46 pm
Contact:

Re: CMD Random

Post by Simon Sheppard »

When you divide %RANDOM% by 32768 you will get a random number between 0 and almost 1 (0.999969)
notice we are dividing by 32768 rather than 32767, so we should never get 1 which would give us an uneven distribution of numbers.

if you multiply that by 6 you will get a random number between 0 and 5.9999
If you add 2 you now get a random number between 2 and 7.9999
when rounded down that becomes 2 to 7 as you have found

So if you want a higher starting point without changing the maximum possible value then you need to add 2 but only multiply by 5
giving a random number between 0 and 4.9999
You add 2 to get a random number between 2 and 6.9999
when rounded down that becomes 2 to 6.

Code: Select all

SET /a _rand=(%RANDOM%*5/32768)+2
Post Reply