Bash终端中的Unix $ RANDOM函数不是随机的 [英] Unix $RANDOM function not random in Bash terminal

查看:63
本文介绍了Bash终端中的Unix $ RANDOM函数不是随机的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用bash终端中的$ RANDOM函数来生成指定范围之间的随机数.问题在于它生成的数字似乎根本不是随机的.我正在使用的脚本是:

I'm trying to generate a random number in between a specified range by using the $RANDOM function in the bash terminal. The problem is that the numbers it is generating don't appear to be random at all. The script I am using is:

RANDOM=$$;

a=$RANDOM
b=9; #Number of scripts in collection -1
c=`expr $a % $b `; #Random number between 0 and b

if (( c==0 ));
then

echo "script 1 (random = $a, mod = $c)";

elif (( c==1 ));
then

echo "stript 2 (random = $a, mod = $c)";

...

else

echo "error (random = $a, mod = $c)";

fi;

如果我在for in循环中运行此程序,例如:

If I run this in a for in loop I get, for example:

script 8 (random = 17845, mod = 7)
script 8 (random = 18754, mod = 7)
script 8 (random = 19663, mod = 7)
script 7 (random = 20571, mod = 6)
script 7 (random = 21480, mod = 6)
script 6 (random = 22388, mod = 5)
script 6 (random = 23297, mod = 5)
script 6 (random = 24206, mod = 5)
script 5 (random = 25114, mod = 4)
script 5 (random = 26023, mod = 4)

显然不是随机的.

我尝试删除$ a并开始运行

I tried removing the $a and just running

c=`expr $RANDOM % $b`; 

然后将代码更改为另一种版本

and then altering the code to another variation

c=`expr $a \* $b \/ 32767`;

但是这些(毫不奇怪)返回了相同的结果.我究竟做错了什么?还是这只是$ RANDOM的一个令人讨厌的限制?任何建议将不胜感激.

But these (unsurprisingly) returned the same result. What am I doing wrong? Or is this just a slightly irritating limitation for $RANDOM? Any advice would be greatly appreciated.

推荐答案

您一直使用相同的数字播种RANDOM.尝试不要播种或使用更随机的项目播种:

You kept seeding RANDOM with the same number. Try not to seed it or seed it with a more random item instead:

RANDOM=$$

显然, $$ 不会总是更改,因为它始终是外壳程序的主要PID(而不是子外壳程序PID).如果您实际上调用的是不同的Shell,则可能没有太大区别,因为每个PID播种的数字仅递增1.因此,您可以删除它,或在/dev/urandom 等位置获得另一个随机种子.

Apparently $$ doesn't change always as it's always the main PID (not subshell PID) of your shell. If you're actually calling different shells, probably there isn't much difference since the numbers seeded by every PID increments only by ones. So either you could remove that or get another random seed somewhere like /dev/urandom, etc.

一种通过/dev/urandom 应用随机种子的好方法:

One good way to apply a random seed by /dev/urandom:

RANDOM=$(tr -dc 0-9 < /dev/urandom | head -c10)

又过了几毫微秒(似乎比这些数字大似乎效果不佳):

Another through nanoseconds (seeding larger numbers than these seems to not give a good effect):

RANDOM=$(date '+%N')

还要使它在不同的子流程中看起来更加独特,请在种子中添加BASHPID(优于$$):

Also to make it look more unique among different subprocesses, add BASHPID (better than $$) to your seed:

RANDOM=$(( BASHPID + $(date '+%N') ))

这篇关于Bash终端中的Unix $ RANDOM函数不是随机的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆