regarding page https://ss64.com/nt/syntaxrandom.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% % (62+1)) + 2
run it multile times, it will only display values 2,3,4,5,6
regards
Rob
CMD Random

 Posts: 4
 Joined: 2021Aug03, 1:45 am
Re: CMD Random
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/
is a more even distribution anyway.
Code: Select all
set /a rnd=(%RANDOM%%%(maxmin+1))+min
 Simon Sheppard
 Posts: 62
 Joined: 2021Jul10, 7:46 pm
 Contact:
Re: CMD Random
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.
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