%random% variable not returning a random number

2020-05-10 06:30发布

I'm using this code:

set /a alg=!random!*!activecount!/32768+1

For the most part, it works. HOWEVER, the !random! variable isn't generating a completely random number. instead, it's constantly counting up at a slow pace. Now, assuming the variable !activecount! is equal to 2, it would constantly generate either 1 or 2, without changing, for a VERY long time. Why isn't the random variable randomizing? I tried echoing !random! after the fact, and it generates a random number then. What gives?

1条回答
家丑人穷心不美
2楼-- · 2020-05-10 06:48

You haven't shown enough of your code, but I think I know what your problem is.

Your code works fine in a simple loop within one command session:

@echo off
setlocal enableDelayedExpansion
set "activecount=10"
for /l %%n in (1 1 10) do (
  set /a alg=!random!*activecount/32768+1
  echo !alg!
)

--OUTPUT--

7
8
6
6
9
4
3
1
8
9

But it does not work if each !random! is in a new cmd.exe session. That is because the random sequence is initiated upon cmd.exe startup, and the seed value is derived from the current time, and the seed only changes once per second. See https://stackoverflow.com/a/19697361/1012053

Here is your code with each execution in a new cmd.exe session:

@echo off
setlocal disableDelayedExpansion
set "activecount=10"
for /l %%n in (1 1 10) do (
  cmd /v:on /c "set /a !random!*activecount/32768+1"
  echo(
)

-- OUTPUT --

6
6
6
6
6
6
6
6
6
6

It is easier to see what is happening if we print out the raw !random! value, and if we put a 1 second delay between each cluster of 5:

@echo off
for /l %%n in (1 1 5) do (
  for /l %%m in (1 1 5) do (
    cmd /v:on /c "set /a !random!"
    echo(
  )
  timeout /t 1 >nul
  echo(
)

-- OUTPUT --

21755
21755
21755
21755
21755

21758
21758
21758
21758
21758

21761
21761
21761
21761
21761

21764
21764
21764
21764
21764

21768
21768
21768
21768
21768

Within any given second, the seed value remains constant, so the first random number is constant. But upon each new second, the seed value is incremented a small amount. Given the formula you use to restrict the "random" number to a small range, you can see that it will take a long time for the resultant value to change.

Remember that the first code demonstrates that the pseudo random number works within the same session. But every cmd.exe session that starts within the same second gets the same seed value, so each of those sessions gets the exact same pseudo random sequence.

查看更多
登录 后发表回答