0

This always generates 83, which is neither random nor within the desired range:

set /a result=(%random%*67/32768)+65

This generates random numbers but still not within the range I want:

set /a result=%random% %% 67+65

This generates random numbers, all of which seem negative and cover a vast range:

set /a result=%random% %% 67-65

These are the options I've found via Googling.

koberulz
  • 155
  • 8

2 Answers2

3

On the command line it is:

set /a _test=(%RANDOM% % 3) + 65

In a batch file it is:

set /a _test=(%RANDOM% %% 3) + 65
jwdonahue
  • 6,199
  • 2
  • 21
  • 43
0

For your specific case of 65-67, you can use:

SET /A result=%RANDOM% * 3 / 32768 + 65

The general formula is:

%RANDOM% * (%MAX% - %MIN% + 1) / 32768 + %MINIMUM%

Adapted from a comment in How to use random in BATCH script?.

aphoria
  • 19,796
  • 7
  • 64
  • 73
  • Yeah, I think that's what I was going for in my first example but I messed up and put "max" instead of "range". But I've run it several times now and generated 65 every time, same as my example always generated 83. – koberulz Feb 27 '20 at 20:00
  • Are you doing this inside a loop? You probably need to add `SETLOCAL ENABLEDELAYEDEXPANSION` and use `!RANDOM!` instead of `%RANDOM%`. – aphoria Feb 27 '20 at 20:22
  • What's the difference? But no, it's not in a loop. – koberulz Feb 27 '20 at 20:35
  • You would need delayed expansion enabled if doing it inside a loop. Can you post your complete code or at least more of it for better context? – aphoria Feb 27 '20 at 20:43
  • It seems it is generating a random result, but it changes so infrequently as to be meaningless. The %RANDOM% is always random, but the /3/32768+65 keeps ending up at the same number for several minutes at a time. jwdonahue's answer gets me much more random results. – koberulz Feb 28 '20 at 03:49
  • That's certainly strange and I can't replicate that result. I didn't do a statistical analysis, but using my formula and the one from jwdonahue's answer generate about the same distribution of numbers for me. – aphoria Feb 28 '20 at 12:57